blob: bbe0215bfe905fe3b96957ef152e0a2322360aec [file] [log] [blame]
Mike Frysinger4c331892022-09-13 05:17:08 -04001/* Copyright 2021 The ChromiumOS Authors
Zi Lin171ee1e2021-10-13 03:12:18 +00002 * Use of this source code is governed by a BSD-style license that can be
3 * found in the LICENSE file.
4 */
5
6#include "test_util.h"
7
8#include <stdio.h>
9#include <stdlib.h>
10#include <string.h>
11#include <unistd.h>
12
13#include "util.h"
14
15#define MAX_PIPE_CAPACITY (4096)
16
Christian Blichmann2b9f5be2022-01-10 15:56:25 +010017FILE *write_to_pipe(const std::string& content)
Zi Lin171ee1e2021-10-13 03:12:18 +000018{
19 int pipefd[2];
20 if (pipe(pipefd) == -1) {
21 die("pipe(pipefd) failed");
22 }
23
24 size_t len = content.length();
25 if (len > MAX_PIPE_CAPACITY)
26 die("write_to_pipe cannot handle >4KB content.");
27 size_t i = 0;
28 unsigned int attempts = 0;
29 ssize_t ret;
30 while (i < len) {
31 ret = write(pipefd[1], content.c_str() + i, len - i);
32 if (ret == -1) {
33 close(pipefd[0]);
34 close(pipefd[1]);
35 return NULL;
36 }
37
38 /* If we write 0 bytes three times in a row, fail. */
39 if (ret == 0) {
40 if (++attempts >= 3) {
41 close(pipefd[0]);
42 close(pipefd[1]);
43 warn("write() returned 0 three times in a row");
44 return NULL;
45 }
46 continue;
47 }
48
49 attempts = 0;
50 i += (size_t)ret;
51 }
52
53 close(pipefd[1]);
54 return fdopen(pipefd[0], "r");
55}
Christian Blichmanna83c4a72022-01-10 15:56:25 +010056
57std::string source_path(const std::string& file) {
58 std::string srcdir = getenv("SRC") ? : ".";
59 return srcdir + "/" + file;
60}