• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Copyright 2021 The ChromiumOS Authors
2  * 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 
write_to_pipe(const std::string & content)17 FILE* write_to_pipe(const std::string& content) {
18   int pipefd[2];
19   if (pipe(pipefd) == -1) {
20     die("pipe(pipefd) failed");
21   }
22 
23   size_t len = content.length();
24   if (len > MAX_PIPE_CAPACITY)
25     die("write_to_pipe cannot handle >4KB content.");
26   size_t i = 0;
27   unsigned int attempts = 0;
28   ssize_t ret;
29   while (i < len) {
30     ret = write(pipefd[1], content.c_str() + i, len - i);
31     if (ret == -1) {
32       close(pipefd[0]);
33       close(pipefd[1]);
34       return NULL;
35     }
36 
37     /* If we write 0 bytes three times in a row, fail. */
38     if (ret == 0) {
39       if (++attempts >= 3) {
40         close(pipefd[0]);
41         close(pipefd[1]);
42         warn("write() returned 0 three times in a row");
43         return NULL;
44       }
45       continue;
46     }
47 
48     attempts = 0;
49     i += (size_t)ret;
50   }
51 
52   close(pipefd[1]);
53   return fdopen(pipefd[0], "r");
54 }
55 
source_path(const std::string & file)56 std::string source_path(const std::string& file) {
57   std::string srcdir = getenv("SRC") ?: ".";
58   return srcdir + "/" + file;
59 }
60