Line data Source code
1 : /* C++ wrapper around libiberty's pex API.
2 : Copyright (C) 2025-2026 Free Software Foundation, Inc.
3 : Contributed by David Malcolm <dmalcolm@redhat.com>.
4 :
5 : This file is part of GCC.
6 :
7 : GCC is free software; you can redistribute it and/or modify it
8 : under the terms of the GNU General Public License as published by
9 : the Free Software Foundation; either version 3, or (at your option)
10 : any later version.
11 :
12 : GCC is distributed in the hope that it will be useful, but
13 : WITHOUT ANY WARRANTY; without even the implied warranty of
14 : MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 : General Public License for more details.
16 :
17 : You should have received a copy of the GNU General Public License
18 : along with GCC; see the file COPYING3. If not see
19 : <http://www.gnu.org/licenses/>. */
20 :
21 : #define INCLUDE_STRING
22 : #define INCLUDE_VECTOR
23 : #include "config.h"
24 : #include "system.h"
25 : #include "coretypes.h"
26 : #include "pex.h"
27 :
28 : /* Read the contents of FILE into memory, or return nullptr
29 : if there are any problems. */
30 :
31 : static std::unique_ptr<std::vector<char>>
32 49 : read_all_of_file (FILE *f_in)
33 : {
34 : /* Read content, allocating a buffer for it. */
35 49 : auto result = std::make_unique<std::vector<char>> ();
36 49 : char buf[4096];
37 49 : size_t iter_sz_in;
38 :
39 322 : while ( (iter_sz_in = fread (buf, 1, sizeof (buf), f_in)) )
40 : {
41 224 : size_t old_total_sz = result->size ();
42 224 : size_t new_total_sz = old_total_sz + iter_sz_in;
43 224 : size_t old_alloc_sz = result->capacity ();
44 224 : if (new_total_sz > old_alloc_sz)
45 : {
46 144 : size_t new_alloc_sz = std::max (old_alloc_sz * 2, new_total_sz);
47 144 : result->reserve (new_alloc_sz);
48 : }
49 224 : gcc_assert (result->capacity () >= new_total_sz);
50 224 : result->resize (new_total_sz);
51 224 : memcpy (result->data () + old_total_sz, buf, iter_sz_in);
52 : }
53 :
54 49 : if (!feof (f_in))
55 0 : return nullptr;
56 :
57 49 : return result;
58 49 : }
59 :
60 : // struct file_wrapper
61 :
62 : std::unique_ptr<std::vector<char>>
63 49 : file_wrapper::read_all ()
64 : {
65 49 : return read_all_of_file (m_file);
66 : }
67 :
68 : // struct pex
69 :
70 : const char *
71 49 : pex::run (int flags, const char *executable, const std::vector<std::string> &args,
72 : const char *outname, const char *errname, int *err)
73 : {
74 49 : std::vector<char *> argv;
75 147 : for (auto &iter : args)
76 98 : argv.push_back (const_cast<char *> (iter.c_str ()));
77 49 : argv.push_back (nullptr);
78 49 : return pex_run (m_obj, flags, executable, argv.data (),
79 49 : outname, errname, err);
80 49 : }
|