2 * Copyright 2016-present Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #include <folly/portability/SysUio.h>
22 #include <folly/ScopeGuard.h>
23 #include <folly/portability/Sockets.h>
24 #include <folly/portability/SysFile.h>
25 #include <folly/portability/Unistd.h>
27 template <class F, class... Args>
28 static int wrapPositional(F f, int fd, off_t offset, Args... args) {
29 off_t origLoc = lseek(fd, 0, SEEK_CUR);
30 if (origLoc == off_t(-1)) {
33 if (lseek(fd, offset, SEEK_SET) == off_t(-1)) {
37 int res = (int)f(fd, args...);
40 if (lseek(fd, origLoc, SEEK_SET) == off_t(-1)) {
51 #if !FOLLY_HAVE_PREADV
52 extern "C" ssize_t preadv(int fd, const iovec* iov, int count, off_t offset) {
53 return wrapPositional(readv, fd, offset, iov, count);
57 #if !FOLLY_HAVE_PWRITEV
58 extern "C" ssize_t pwritev(int fd, const iovec* iov, int count, off_t offset) {
59 return wrapPositional(writev, fd, offset, iov, count);
64 template <bool isRead>
65 static ssize_t doVecOperation(int fd, const iovec* iov, int count) {
69 if (count < 0 || count > folly::kIovMax) {
74 // We only need to worry about locking if the file descriptor is
75 // not a socket. We have no way of locking sockets :(
76 // The correct way to do this for sockets is via sendmsg/recvmsg,
77 // but this is good enough for now.
78 bool shouldLock = !folly::portability::sockets::is_fh_socket(fd);
79 if (shouldLock && lockf(fd, F_LOCK, 0) == -1) {
84 lockf(fd, F_ULOCK, 0);
88 ssize_t bytesProcessed = 0;
90 void* curBase = iov[0].iov_base;
91 size_t curLen = iov[0].iov_len;
92 while (curIov < count) {
95 res = read(fd, curBase, (unsigned int)curLen);
96 if (res == 0 && curLen != 0) {
100 res = write(fd, curBase, (unsigned int)curLen);
101 // Write of zero bytes is fine.
108 if (size_t(res) == curLen) {
110 if (curIov < count) {
111 curBase = iov[curIov].iov_base;
112 curLen = iov[curIov].iov_len;
115 curBase = (void*)((char*)curBase + res);
119 if (bytesProcessed + res < 0) {
124 bytesProcessed += res;
127 return bytesProcessed;
130 extern "C" ssize_t readv(int fd, const iovec* iov, int count) {
131 return doVecOperation<true>(fd, iov, count);
134 extern "C" ssize_t writev(int fd, const iovec* iov, int count) {
135 return doVecOperation<false>(fd, iov, count);