2 * Copyright 2016 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/SysFile.h>
24 #include <folly/portability/Unistd.h>
26 template <class F, class... Args>
27 static int wrapPositional(F f, int fd, off_t offset, Args... args) {
28 off_t origLoc = lseek(fd, 0, SEEK_CUR);
29 if (origLoc == off_t(-1)) {
32 if (lseek(fd, offset, SEEK_SET) == off_t(-1)) {
36 int res = (int)f(fd, args...);
39 if (lseek(fd, origLoc, SEEK_SET) == off_t(-1)) {
50 #if !FOLLY_HAVE_PREADV
51 extern "C" ssize_t preadv(int fd, const iovec* iov, int count, off_t offset) {
52 return wrapPositional(readv, fd, offset, iov, count);
56 #if !FOLLY_HAVE_PWRITEV
57 extern "C" ssize_t pwritev(int fd, const iovec* iov, int count, off_t offset) {
58 return wrapPositional(writev, fd, offset, iov, count);
63 template <bool isRead>
64 static ssize_t doVecOperation(int fd, const iovec* iov, int count) {
68 if (count < 0 || count > folly::kIovMax) {
73 if (lockf(fd, F_LOCK, 0) == -1) {
76 SCOPE_EXIT { lockf(fd, F_ULOCK, 0); };
78 ssize_t bytesProcessed = 0;
80 void* curBase = iov[0].iov_base;
81 size_t curLen = iov[0].iov_len;
82 while (curIov < count) {
85 res = read(fd, curBase, (unsigned int)curLen);
86 if (res == 0 && curLen != 0) {
90 res = write(fd, curBase, (unsigned int)curLen);
91 // Write of zero bytes is fine.
100 if (curIov < count) {
101 curBase = iov[curIov].iov_base;
102 curLen = iov[curIov].iov_len;
105 curBase = (void*)((char*)curBase + res);
109 if (bytesProcessed + res < 0) {
114 bytesProcessed += res;
117 return bytesProcessed;
120 extern "C" ssize_t readv(int fd, const iovec* iov, int count) {
121 return doVecOperation<true>(fd, iov, count);
124 extern "C" ssize_t writev(int fd, const iovec* iov, int count) {
125 return doVecOperation<false>(fd, iov, count);