1 // Copyright 2016 The Fuchsia Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "util.h"
6
7 #include <errno.h>
8 #include <fcntl.h>
9 #include <stdlib.h>
10 #include <strings.h>
11 #include <unistd.h>
12
13 #include <unittest/unittest.h>
14
15 // readable: is the pipe readable on the child side?
16 // returns [our_fd, child_fd]
stdio_pipe(int pipe_fds[2],bool readable)17 int stdio_pipe(int pipe_fds[2], bool readable) {
18 int r;
19 if ((r = pipe(pipe_fds)) != 0) { // Initially gives [reader, writer]
20 return r;
21 }
22
23 if (readable) {
24 // If child is to be readable, we want
25 // [our_fd: writer, child_fd: reader], so we must swap
26 int tmp = pipe_fds[0];
27 pipe_fds[0] = pipe_fds[1];
28 pipe_fds[1] = tmp;
29 }
30
31 return 0;
32 }
33
read_to_end(int fd,uint8_t ** buf,size_t * buf_size)34 int read_to_end(int fd, uint8_t** buf, size_t* buf_size) {
35 size_t start_len = *buf_size;
36 size_t unused = 16;
37
38 *buf_size += unused;
39 *buf = realloc(*buf, *buf_size);
40
41 while (1) {
42 if (unused == 0) {
43 // Double the buffer size
44 unused = *buf_size;
45 *buf_size += unused;
46 *buf = realloc(*buf, *buf_size);
47 }
48
49 uint8_t* buf_slice = &(*buf)[*buf_size-unused];
50 int result = read(fd, buf_slice, unused);
51 if (result == 0) {
52 *buf_size -= unused;
53 return *buf_size - start_len;
54 } else if (result > 0) {
55 unused -= result;
56 } else if (result == EINTR) {
57 } else {
58 *buf_size -= unused;
59 return result;
60 }
61 }
62 }
63