Debian Codegraph @

src/kj/io.c++

raw symbols SCIP
1 // Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
2 // Licensed under the MIT License:
3 //
4 // Permission is hereby granted, free of charge, to any person obtaining a copy
5 // of this software and associated documentation files (the "Software"), to deal
6 // in the Software without restriction, including without limitation the rights
7 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 // copies of the Software, and to permit persons to whom the Software is
9 // furnished to do so, subject to the following conditions:
10 //
11 // The above copyright notice and this permission notice shall be included in
12 // all copies or substantial portions of the Software.
13 //
14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 // THE SOFTWARE.
21
22 #ifndef _GNU_SOURCE
23 #define _GNU_SOURCE
24 #endif
25
26 #if _WIN32
27 #include "win32-api-version.h"
28 #endif
29
30 #include "io.h"
31 #include "debug.h"
32 #include "miniposix.h"
33 #include <algorithm>
34 #include <errno.h>
35 #include "vector.h"
36 #include <limits.h>
37
38 #if _WIN32
39 #include <windows.h>
40 #include "windows-sanity.h"
41 #else
42 #include <sys/uio.h>
43 #endif
44
45 namespace kj {
46
47 InputStream::~InputStream() noexcept(false) {}
48 OutputStream::~OutputStream() noexcept(false) {}
49 BufferedInputStream::~BufferedInputStream() noexcept(false) {}
50 BufferedOutputStream::~BufferedOutputStream() noexcept(false) {}
51
52 size_t InputStream::read(void* buffer, size_t minBytes, size_t maxBytes) {
53 size_t n = tryRead(buffer, minBytes, maxBytes);
54 KJ_REQUIRE(n >= minBytes, "Premature EOF") {
55 // Pretend we read zeros from the input.
56 memset(reinterpret_cast<byte*>(buffer) + n, 0, minBytes - n);
57 return minBytes;
58 }
59 return n;
60 }
61
62 void InputStream::skip(size_t bytes) {
63 char scratch[8192];
64 while (bytes > 0) {
65 size_t amount = std::min(bytes, sizeof(scratch));
66 read(scratch, amount);
67 bytes -= amount;
68 }
69 }
70
71
72 namespace {
73
74 Array<byte> readAll(InputStream& input, uint64_t limit, bool nulTerminate) {
75 Vector<Array<byte>> parts;
76 constexpr size_t BLOCK_SIZE = 4096;
77
78 for (;;) {
79 KJ_REQUIRE(limit > 0, "Reached limit before EOF.");
80 auto part = heapArray<byte>(kj::min(BLOCK_SIZE, limit));
81 size_t n = input.tryRead(part.begin(), part.size(), part.size());
82 limit -= n;
83 if (n < part.size()) {
84 auto result = heapArray<byte>(parts.size() * BLOCK_SIZE + n + nulTerminate);
85 byte* pos = result.begin();
86 for (auto& p: parts) {
87 memcpy(pos, p.begin(), BLOCK_SIZE);
88 pos += BLOCK_SIZE;
89 }
90 memcpy(pos, part.begin(), n);
91 pos += n;
92 if (nulTerminate) *pos++ = '\0';
93 KJ_ASSERT(pos == result.end());
94 return result;
95 } else {
96 parts.add(kj::mv(part));
97 }
98 }
99 }
100
101 } // namespace
102
103 String InputStream::readAllText(uint64_t limit) {
104 return String(readAll(*this, limit, true).releaseAsChars());
105 }
106 Array<byte> InputStream::readAllBytes(uint64_t limit) {
107 return readAll(*this, limit, false);
108 }
109
110 void OutputStream::write(ArrayPtr<const ArrayPtr<const byte>> pieces) {
111 for (auto piece: pieces) {
112 write(piece.begin(), piece.size());
113 }
114 }
115
116 ArrayPtr<const byte> BufferedInputStream::getReadBuffer() {
117 auto result = tryGetReadBuffer();
118 KJ_REQUIRE(result.size() > 0, "Premature EOF");
119 return result;
120 }
121
122 // =======================================================================================
123
124 BufferedInputStreamWrapper::BufferedInputStreamWrapper(InputStream& inner, ArrayPtr<byte> buffer)
125 : inner(inner), ownedBuffer(buffer == nullptr ? heapArray<byte>(8192) : nullptr),
126 buffer(buffer == nullptr ? ownedBuffer : buffer) {}
127
128 BufferedInputStreamWrapper::~BufferedInputStreamWrapper() noexcept(false) {}
129
130 ArrayPtr<const byte> BufferedInputStreamWrapper::tryGetReadBuffer() {
131 if (bufferAvailable.size() == 0) {
132 size_t n = inner.tryRead(buffer.begin(), 1, buffer.size());
133 bufferAvailable = buffer.slice(0, n);
134 }
135
136 return bufferAvailable;
137 }
138
139 size_t BufferedInputStreamWrapper::tryRead(void* dst, size_t minBytes, size_t maxBytes) {
140 if (minBytes <= bufferAvailable.size()) {
141 // Serve from current buffer.
142 size_t n = std::min(bufferAvailable.size(), maxBytes);
143 memcpy(dst, bufferAvailable.begin(), n);
144 bufferAvailable = bufferAvailable.slice(n, bufferAvailable.size());
145 return n;
146 } else {
147 // Copy current available into destination.
148 memcpy(dst, bufferAvailable.begin(), bufferAvailable.size());
149 size_t fromFirstBuffer = bufferAvailable.size();
150
151 dst = reinterpret_cast<byte*>(dst) + fromFirstBuffer;
152 minBytes -= fromFirstBuffer;
153 maxBytes -= fromFirstBuffer;
154
155 if (maxBytes <= buffer.size()) {
156 // Read the next buffer-full.
157 size_t n = inner.tryRead(buffer.begin(), minBytes, buffer.size());
158 size_t fromSecondBuffer = std::min(n, maxBytes);
159 memcpy(dst, buffer.begin(), fromSecondBuffer);
160 bufferAvailable = buffer.slice(fromSecondBuffer, n);
161 return fromFirstBuffer + fromSecondBuffer;
162 } else {
163 // Forward large read to the underlying stream.
164 bufferAvailable = nullptr;
165 return fromFirstBuffer + inner.tryRead(dst, minBytes, maxBytes);
166 }
167 }
168 }
169
170 void BufferedInputStreamWrapper::skip(size_t bytes) {
171 if (bytes <= bufferAvailable.size()) {
172 bufferAvailable = bufferAvailable.slice(bytes, bufferAvailable.size());
173 } else {
174 bytes -= bufferAvailable.size();
175 if (bytes <= buffer.size()) {
176 // Read the next buffer-full.
177 size_t n = inner.read(buffer.begin(), bytes, buffer.size());
178 bufferAvailable = buffer.slice(bytes, n);
179 } else {
180 // Forward large skip to the underlying stream.
181 bufferAvailable = nullptr;
182 inner.skip(bytes);
183 }
184 }
185 }
186
187 // -------------------------------------------------------------------
188
189 BufferedOutputStreamWrapper::BufferedOutputStreamWrapper(OutputStream& inner, ArrayPtr<byte> buffer)
190 : inner(inner),
191 ownedBuffer(buffer == nullptr ? heapArray<byte>(8192) : nullptr),
192 buffer(buffer == nullptr ? ownedBuffer : buffer),
193 bufferPos(this->buffer.begin()) {}
194
195 BufferedOutputStreamWrapper::~BufferedOutputStreamWrapper() noexcept(false) {
196 unwindDetector.catchExceptionsIfUnwinding([&]() {
197 flush();
198 });
199 }
200
201 void BufferedOutputStreamWrapper::flush() {
202 if (bufferPos > buffer.begin()) {
203 inner.write(buffer.begin(), bufferPos - buffer.begin());
204 bufferPos = buffer.begin();
205 }
206 }
207
208 ArrayPtr<byte> BufferedOutputStreamWrapper::getWriteBuffer() {
209 return arrayPtr(bufferPos, buffer.end());
210 }
211
212 void BufferedOutputStreamWrapper::write(const void* src, size_t size) {
213 if (src == bufferPos) {
214 // Oh goody, the caller wrote directly into our buffer.
215 bufferPos += size;
216 } else {
217 size_t available = buffer.end() - bufferPos;
218
219 if (size <= available) {
220 memcpy(bufferPos, src, size);
221 bufferPos += size;
222 } else if (size <= buffer.size()) {
223 // Too much for this buffer, but not a full buffer's worth, so we'll go ahead and copy.
224 memcpy(bufferPos, src, available);
225 inner.write(buffer.begin(), buffer.size());
226
227 size -= available;
228 src = reinterpret_cast<const byte*>(src) + available;
229
230 memcpy(buffer.begin(), src, size);
231 bufferPos = buffer.begin() + size;
232 } else {
233 // Writing so much data that we might as well write directly to avoid a copy.
234 inner.write(buffer.begin(), bufferPos - buffer.begin());
235 bufferPos = buffer.begin();
236 inner.write(src, size);
237 }
238 }
239 }
240
241 // =======================================================================================
242
243 ArrayInputStream::ArrayInputStream(ArrayPtr<const byte> array): array(array) {}
244 ArrayInputStream::~ArrayInputStream() noexcept(false) {}
245
246 ArrayPtr<const byte> ArrayInputStream::tryGetReadBuffer() {
247 return array;
248 }
249
250 size_t ArrayInputStream::tryRead(void* dst, size_t minBytes, size_t maxBytes) {
251 size_t n = std::min(maxBytes, array.size());
252 memcpy(dst, array.begin(), n);
253 array = array.slice(n, array.size());
254 return n;
255 }
256
257 void ArrayInputStream::skip(size_t bytes) {
258 KJ_REQUIRE(array.size() >= bytes, "ArrayInputStream ended prematurely.") {
259 bytes = array.size();
260 break;
261 }
262 array = array.slice(bytes, array.size());
263 }
264
265 // -------------------------------------------------------------------
266
267 ArrayOutputStream::ArrayOutputStream(ArrayPtr<byte> array): array(array), fillPos(array.begin()) {}
268 ArrayOutputStream::~ArrayOutputStream() noexcept(false) {}
269
270 ArrayPtr<byte> ArrayOutputStream::getWriteBuffer() {
271 return arrayPtr(fillPos, array.end());
272 }
273
274 void ArrayOutputStream::write(const void* src, size_t size) {
275 if (src == fillPos && fillPos != array.end()) {
276 // Oh goody, the caller wrote directly into our buffer.
277 KJ_REQUIRE(size <= array.end() - fillPos, size, fillPos, array.end() - fillPos);
278 fillPos += size;
279 } else {
280 KJ_REQUIRE(size <= (size_t)(array.end() - fillPos),
281 "ArrayOutputStream's backing array was not large enough for the data written.");
282 memcpy(fillPos, src, size);
283 fillPos += size;
284 }
285 }
286
287 // -------------------------------------------------------------------
288
289 VectorOutputStream::VectorOutputStream(size_t initialCapacity)
290 : vector(heapArray<byte>(initialCapacity)), fillPos(vector.begin()) {}
291 VectorOutputStream::~VectorOutputStream() noexcept(false) {}
292
293 ArrayPtr<byte> VectorOutputStream::getWriteBuffer() {
294 // Grow if needed.
295 if (fillPos == vector.end()) {
296 grow(vector.size() + 1);
297 }
298
299 return arrayPtr(fillPos, vector.end());
300 }
301
302 void VectorOutputStream::write(const void* src, size_t size) {
303 if (src == fillPos && fillPos != vector.end()) {
304 // Oh goody, the caller wrote directly into our buffer.
305 KJ_REQUIRE(size <= vector.end() - fillPos, size, fillPos, vector.end() - fillPos);
306 fillPos += size;
307 } else {
308 if (vector.end() - fillPos < size) {
309 grow(fillPos - vector.begin() + size);
310 }
311
312 memcpy(fillPos, src, size);
313 fillPos += size;
314 }
315 }
316
317 void VectorOutputStream::grow(size_t minSize) {
318 size_t newSize = vector.size() * 2;
319 while (newSize < minSize) newSize *= 2;
320 auto newVector = heapArray<byte>(newSize);
321 memcpy(newVector.begin(), vector.begin(), fillPos - vector.begin());
322 fillPos = fillPos - vector.begin() + newVector.begin();
323 vector = kj::mv(newVector);
324 }
325
326 // =======================================================================================
327
328 AutoCloseFd::~AutoCloseFd() noexcept(false) {
329 if (fd >= 0) {
330 // Don't use SYSCALL() here because close() should not be repeated on EINTR.
331 if (miniposix::close(fd) < 0) {
332 KJ_FAIL_SYSCALL("close", errno, fd) {
333 // This ensures we don't throw an exception if unwinding.
334 break;
335 }
336 }
337 }
338 }
339
340 FdInputStream::~FdInputStream() noexcept(false) {}
341
342 size_t FdInputStream::tryRead(void* buffer, size_t minBytes, size_t maxBytes) {
343 byte* pos = reinterpret_cast<byte*>(buffer);
344 byte* min = pos + minBytes;
345 byte* max = pos + maxBytes;
346
347 while (pos < min) {
348 miniposix::ssize_t n;
349 KJ_SYSCALL(n = miniposix::read(fd, pos, max - pos), fd);
350 if (n == 0) {
351 break;
352 }
353 pos += n;
354 }
355
356 return pos - reinterpret_cast<byte*>(buffer);
357 }
358
359 FdOutputStream::~FdOutputStream() noexcept(false) {}
360
361 #if _WIN32 || __APPLE__
362 // On platforms that can't handle writes of more than INT_MAX (e.g. Windows, Mac), we will clamp
363 // writes to this size. We use 1GB rather than INT_MAX since INT_MAX is 2GB minus 1 byte. Being
364 // off by one from a big round number feels rude (alignment issues may harm performance), and 1GB
365 // should be plenty in any case.
366 static constexpr size_t WRITE_CLAMP_SIZE = 1u << 30;
367 #endif
368
369 void FdOutputStream::write(const void* buffer, size_t size) {
370 const char* pos = reinterpret_cast<const char*>(buffer);
371
372 while (size > 0) {
373 miniposix::ssize_t n;
374 #if _WIN32 || __APPLE__
375 // Windows and Mac suffer from bugs in which they will fail if given more than INT_MAX bytes
376 // in a single write operation. We can just clamp the size since the loop will then handle
377 // writing the rest. I don't know why these platforms don't just do this themselves.
378 KJ_SYSCALL(n = miniposix::write(fd, pos, kj::min(size, WRITE_CLAMP_SIZE)), fd);
379 #else
380 KJ_SYSCALL(n = miniposix::write(fd, pos, size), fd);
381 #endif
382 KJ_ASSERT(n > 0, "write() returned zero.");
383 pos += n;
384 size -= n;
385 }
386 }
387
388 void FdOutputStream::write(ArrayPtr<const ArrayPtr<const byte>> pieces) {
389 #if _WIN32
390 // Windows has no reasonable writev(). It has WriteFileGather, but this call has the unreasonable
391 // restriction that each segment must be page-aligned. So, fall back to the default implementation
392
393 OutputStream::write(pieces);
394
395 #else
396 const size_t iovmax = miniposix::iovMax();
397 while (pieces.size() > iovmax) {
398 write(pieces.slice(0, iovmax));
399 pieces = pieces.slice(iovmax, pieces.size());
400 }
401
402 KJ_STACK_ARRAY(struct iovec, iov, pieces.size(), 16, 128);
403
404 for (uint i = 0; i < pieces.size(); i++) {
405 // writev() interface is not const-correct. :(
406 iov[i].iov_base = const_cast<byte*>(pieces[i].begin());
407 iov[i].iov_len = pieces[i].size();
408 }
409
410 struct iovec* current = iov.begin();
411
412 // Advance past any leading empty buffers so that a write full of only empty buffers does not
413 // cause a syscall at all.
414 while (current < iov.end() && current->iov_len == 0) {
415 ++current;
416 }
417
418 while (current < iov.end()) {
419 size_t iovCount = iov.end() - current;
420
421 #if __APPLE__
422 // MacOS will fail if you give it more than INT_MAX bytes to write at once. We can solve this
423 // by carefully truncating the list to a lesser number. Why the OS doesn't just return a short
424 // write itself, I don't know.
425 size_t totalSize = 0;
426 struct iovec* editedPiece = nullptr;
427 size_t editedPieceOriginalLen = 0;
428 for (auto i: kj::zeroTo(iovCount)) {
429 auto& piece = *(current + i);
430 totalSize += piece.iov_len;
431 if (totalSize >= WRITE_CLAMP_SIZE) {
432 // Truncate the list after this piece.
433 iovCount = i + 1;
434
435 if (totalSize > WRITE_CLAMP_SIZE) {
436 // We also have to truncate this piece. Patch it in-place and plan to fix it later.
437 editedPiece = &piece;
438 editedPieceOriginalLen = piece.iov_len;
439 size_t overage = totalSize - WRITE_CLAMP_SIZE;
440 piece.iov_len -= overage;
441 }
442
443 break;
444 }
445 }
446 #endif
447
448 // Issue the write.
449 ssize_t n = 0;
450 KJ_SYSCALL(n = ::writev(fd, current, iovCount), fd);
451 KJ_ASSERT(n > 0, "writev() returned zero.");
452
453 #if __APPLE__
454 // If we patched the list above, unpatch now.
455 if (editedPiece != nullptr) {
456 editedPiece->iov_len = editedPieceOriginalLen;
457 }
458 #endif
459
460 // Advance past all buffers that were fully-written.
461 while (current < iov.end() && static_cast<size_t>(n) >= current->iov_len) {
462 n -= current->iov_len;
463 ++current;
464 }
465
466 // If we only partially-wrote one of the buffers, adjust the pointer and size to include only
467 // the unwritten part.
468 if (n > 0) {
469 current->iov_base = reinterpret_cast<byte*>(current->iov_base) + n;
470 current->iov_len -= n;
471 }
472 }
473 #endif
474 }
475
476 // =======================================================================================
477
478 #if _WIN32
479
480 AutoCloseHandle::~AutoCloseHandle() noexcept(false) {
481 if (handle != (void*)-1) {
482 KJ_WIN32(CloseHandle(handle));
483 }
484 }
485
486 HandleInputStream::~HandleInputStream() noexcept(false) {}
487
488 size_t HandleInputStream::tryRead(void* buffer, size_t minBytes, size_t maxBytes) {
489 byte* pos = reinterpret_cast<byte*>(buffer);
490 byte* min = pos + minBytes;
491 byte* max = pos + maxBytes;
492
493 while (pos < min) {
494 DWORD n;
495 KJ_WIN32(ReadFile(handle, pos, kj::min(max - pos, DWORD(kj::maxValue)), &n, nullptr));
496 if (n == 0) {
497 break;
498 }
499 pos += n;
500 }
501
502 return pos - reinterpret_cast<byte*>(buffer);
503 }
504
505 HandleOutputStream::~HandleOutputStream() noexcept(false) {}
506
507 void HandleOutputStream::write(const void* buffer, size_t size) {
508 const char* pos = reinterpret_cast<const char*>(buffer);
509
510 while (size > 0) {
511 DWORD n;
512 KJ_WIN32(WriteFile(handle, pos, kj::min(size, DWORD(kj::maxValue)), &n, nullptr));
513 KJ_ASSERT(n > 0, "write() returned zero.");
514 pos += n;
515 size -= n;
516 }
517 }
518
519 #endif // _WIN32
520
521 } // namespace kj