Branch data Line data Source code
1 : : /* C++ wrapper around libiberty's pex API.
2 : : Copyright (C) 2025 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 : 4 : read_all_of_file (FILE *f_in)
33 : : {
34 : : /* Read content, allocating a buffer for it. */
35 : 4 : auto result = std::make_unique<std::vector<char>> ();
36 : 4 : char buf[4096];
37 : 4 : size_t iter_sz_in;
38 : :
39 : 82 : while ( (iter_sz_in = fread (buf, 1, sizeof (buf), f_in)) )
40 : : {
41 : 74 : size_t old_total_sz = result->size ();
42 : 74 : size_t new_total_sz = old_total_sz + iter_sz_in;
43 : 74 : size_t old_alloc_sz = result->capacity ();
44 : 74 : if (new_total_sz > old_alloc_sz)
45 : : {
46 : 12 : size_t new_alloc_sz = std::max (old_alloc_sz * 2, new_total_sz);
47 : 12 : result->reserve (new_alloc_sz);
48 : : }
49 : 74 : gcc_assert (result->capacity () >= new_total_sz);
50 : 74 : result->resize (new_total_sz);
51 : 74 : memcpy (result->data () + old_total_sz, buf, iter_sz_in);
52 : : }
53 : :
54 : 4 : if (!feof (f_in))
55 : 0 : return nullptr;
56 : :
57 : 4 : return result;
58 : 4 : }
59 : :
60 : : // struct file_wrapper
61 : :
62 : : std::unique_ptr<std::vector<char>>
63 : 4 : file_wrapper::read_all ()
64 : : {
65 : 4 : return read_all_of_file (m_file);
66 : : }
67 : :
68 : : // struct pex
69 : :
70 : : const char *
71 : 4 : pex::run (int flags, const char *executable, const std::vector<std::string> &args,
72 : : const char *outname, const char *errname, int *err)
73 : : {
74 : 4 : std::vector<char *> argv;
75 : 12 : for (auto &iter : args)
76 : 8 : argv.push_back (const_cast<char *> (iter.c_str ()));
77 : 4 : argv.push_back (nullptr);
78 : 4 : return pex_run (m_obj, flags, executable, argv.data (),
79 : 4 : outname, errname, err);
80 : 4 : }
|