1 // Copyright (c) 2013 The Chromium 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.
5 #include "base/command_line.h"
6 #include "base/file_util.h"
7 #include "base/logging.h"
8 #include "base/process/kill.h"
9 #include "base/process/launch.h"
10 #include "base/strings/string_number_conversions.h"
11 #include "base/strings/utf_string_conversions.h"
12 #include "base/time/time.h"
13 #include "build/build_config.h"
14 #include "tools/gn/err.h"
15 #include "tools/gn/filesystem_utils.h"
16 #include "tools/gn/functions.h"
17 #include "tools/gn/input_conversion.h"
18 #include "tools/gn/input_file.h"
19 #include "tools/gn/parse_tree.h"
20 #include "tools/gn/scheduler.h"
21 #include "tools/gn/trace.h"
22 #include "tools/gn/value.h"
27 #include "base/win/scoped_handle.h"
28 #include "base/win/scoped_process_information.h"
35 #include "base/posix/file_descriptor_shuffle.h"
42 const char kNoExecSwitch
[] = "no-exec";
45 bool ExecProcess(const CommandLine
& cmdline
,
46 const base::FilePath
& startup_dir
,
50 SECURITY_ATTRIBUTES sa_attr
;
51 // Set the bInheritHandle flag so pipe handles are inherited.
52 sa_attr
.nLength
= sizeof(SECURITY_ATTRIBUTES
);
53 sa_attr
.bInheritHandle
= TRUE
;
54 sa_attr
.lpSecurityDescriptor
= NULL
;
56 // Create the pipe for the child process's STDOUT.
57 HANDLE out_read
= NULL
;
58 HANDLE out_write
= NULL
;
59 if (!CreatePipe(&out_read
, &out_write
, &sa_attr
, 0)) {
60 NOTREACHED() << "Failed to create pipe";
63 base::win::ScopedHandle
scoped_out_read(out_read
);
64 base::win::ScopedHandle
scoped_out_write(out_write
);
66 // Create the pipe for the child process's STDERR.
67 HANDLE err_read
= NULL
;
68 HANDLE err_write
= NULL
;
69 if (!CreatePipe(&err_read
, &err_write
, &sa_attr
, 0)) {
70 NOTREACHED() << "Failed to create pipe";
73 base::win::ScopedHandle
scoped_err_read(err_read
);
74 base::win::ScopedHandle
scoped_err_write(err_write
);
76 // Ensure the read handle to the pipe for STDOUT/STDERR is not inherited.
77 if (!SetHandleInformation(out_read
, HANDLE_FLAG_INHERIT
, 0)) {
78 NOTREACHED() << "Failed to disabled pipe inheritance";
81 if (!SetHandleInformation(err_read
, HANDLE_FLAG_INHERIT
, 0)) {
82 NOTREACHED() << "Failed to disabled pipe inheritance";
86 base::FilePath::StringType
cmdline_str(cmdline
.GetCommandLineString());
88 base::win::ScopedProcessInformation proc_info
;
89 STARTUPINFO start_info
= { 0 };
91 start_info
.cb
= sizeof(STARTUPINFO
);
92 start_info
.hStdOutput
= out_write
;
93 // Keep the normal stdin.
94 start_info
.hStdInput
= GetStdHandle(STD_INPUT_HANDLE
);
95 // FIXME(brettw) set stderr here when we actually read it below.
96 //start_info.hStdError = err_write;
97 start_info
.hStdError
= GetStdHandle(STD_ERROR_HANDLE
);
98 start_info
.dwFlags
|= STARTF_USESTDHANDLES
;
100 // Create the child process.
101 if (!CreateProcess(NULL
,
104 TRUE
, // Handles are inherited.
106 startup_dir
.value().c_str(),
107 &start_info
, proc_info
.Receive())) {
111 // Close our writing end of pipes now. Otherwise later read would not be able
112 // to detect end of child's output.
113 scoped_out_write
.Close();
114 scoped_err_write
.Close();
116 // Read output from the child process's pipe for STDOUT
117 const int kBufferSize
= 1024;
118 char buffer
[kBufferSize
];
120 // FIXME(brettw) read from stderr here! This is complicated because we want
121 // to read both of them at the same time, probably need overlapped I/O.
122 // Also uncomment start_info code above.
124 DWORD bytes_read
= 0;
125 BOOL success
= ReadFile(out_read
, buffer
, kBufferSize
, &bytes_read
, NULL
);
126 if (!success
|| bytes_read
== 0)
128 std_out
->append(buffer
, bytes_read
);
131 // Let's wait for the process to finish.
132 WaitForSingleObject(proc_info
.process_handle(), INFINITE
);
135 GetExitCodeProcess(proc_info
.process_handle(), &dw_exit_code
);
136 *exit_code
= static_cast<int>(dw_exit_code
);
141 bool ExecProcess(const CommandLine
& cmdline
,
142 const base::FilePath
& startup_dir
,
143 std::string
* std_out
,
144 std::string
* std_err
,
146 *exit_code
= EXIT_FAILURE
;
148 std::vector
<std::string
> argv
= cmdline
.argv();
152 base::InjectiveMultimap fd_shuffle1
, fd_shuffle2
;
153 scoped_ptr
<char*[]> argv_cstr(new char*[argv
.size() + 1]);
155 fd_shuffle1
.reserve(3);
156 fd_shuffle2
.reserve(3);
158 if (pipe(pipe_fd
) < 0)
161 switch (pid
= fork()) {
168 // DANGER: no calls to malloc are allowed from now on:
169 // http://crbug.com/36678
171 // Obscure fork() rule: in the child, if you don't end up doing exec*(),
172 // you call _exit() instead of exit(). This is because _exit() does not
173 // call any previously-registered (in the parent) exit handlers, which
174 // might do things like block waiting for threads that don't even exist
176 int dev_null
= open("/dev/null", O_WRONLY
);
180 fd_shuffle1
.push_back(
181 base::InjectionArc(pipe_fd
[1], STDOUT_FILENO
, true));
182 fd_shuffle1
.push_back(
183 base::InjectionArc(dev_null
, STDERR_FILENO
, true));
184 fd_shuffle1
.push_back(
185 base::InjectionArc(dev_null
, STDIN_FILENO
, true));
186 // Adding another element here? Remeber to increase the argument to
189 std::copy(fd_shuffle1
.begin(), fd_shuffle1
.end(),
190 std::back_inserter(fd_shuffle2
));
192 if (!ShuffleFileDescriptors(&fd_shuffle1
))
195 file_util::SetCurrentDirectory(startup_dir
);
197 // TODO(brettw) the base version GetAppOutput does a
198 // CloseSuperfluousFds call here. Do we need this?
200 for (size_t i
= 0; i
< argv
.size(); i
++)
201 argv_cstr
[i
] = const_cast<char*>(argv
[i
].c_str());
202 argv_cstr
[argv
.size()] = NULL
;
203 execvp(argv_cstr
[0], argv_cstr
.get());
208 // Close our writing end of pipe now. Otherwise later read would not
209 // be able to detect end of child's output (in theory we could still
210 // write to the pipe).
214 ssize_t bytes_read
= 0;
217 bytes_read
= HANDLE_EINTR(read(pipe_fd
[0], buffer
, sizeof(buffer
)));
220 std_out
->append(buffer
, bytes_read
);
224 return base::WaitForExitCode(pid
, exit_code
);
234 const char kExecScript
[] = "exec_script";
235 const char kExecScript_Help
[] =
236 "exec_script: Synchronously run a script and return the output.\n"
238 " exec_script(filename, arguments, input_conversion,\n"
239 " [file_dependencies])\n"
241 " Runs the given script, returning the stdout of the script. The build\n"
242 " generation will fail if the script does not exist or returns a nonzero\n"
245 " The current directory when executing the script will be the root\n"
246 " build directory. If you are passing file names, you will want to use\n"
247 " the to_build_dir() function to make file names relative to this\n"
248 " path (see \"gn help to_build_dir\").\n"
253 " File name of python script to execute. Non-absolute names will\n"
254 " be treated as relative to the current build file.\n"
257 " A list of strings to be passed to the script as arguments.\n"
259 " input_conversion:\n"
260 " Controls how the file is read and parsed.\n"
261 " See \"gn help input_conversion\".\n"
264 " (Optional) A list of files that this script reads or otherwise\n"
265 " depends on. These dependencies will be added to the build result\n"
266 " such that if any of them change, the build will be regenerated and\n"
267 " the script will be re-run.\n"
269 " The script itself will be an implicit dependency so you do not\n"
270 " need to list it.\n"
274 " all_lines = exec_script(\"myscript.py\", [some_input], \"list lines\",\n"
275 " [ to_build_dir(\"data_file.txt\") ])\n";
277 Value
RunExecScript(Scope
* scope
,
278 const FunctionCallNode
* function
,
279 const std::vector
<Value
>& args
,
281 if (args
.size() != 3 && args
.size() != 4) {
282 *err
= Err(function
->function(), "Wrong number of args to write_file",
283 "I expected three or four arguments.");
287 const Settings
* settings
= scope
->settings();
288 const BuildSettings
* build_settings
= settings
->build_settings();
289 const SourceDir
& cur_dir
= scope
->GetSourceDir();
291 // Find the python script to run.
292 if (!args
[0].VerifyTypeIs(Value::STRING
, err
))
294 SourceFile script_source
=
295 cur_dir
.ResolveRelativeFile(args
[0].string_value());
296 base::FilePath script_path
= build_settings
->GetFullPath(script_source
);
297 if (!build_settings
->secondary_source_path().empty() &&
298 !base::PathExists(script_path
)) {
299 // Fall back to secondary source root when the file doesn't exist.
300 script_path
= build_settings
->GetFullPathSecondary(script_source
);
303 ScopedTrace
trace(TraceItem::TRACE_SCRIPT_EXECUTE
, script_source
.value());
304 trace
.SetToolchain(settings
->toolchain()->label());
306 // Add all dependencies of this script, including the script itself, to the
308 g_scheduler
->AddGenDependency(script_path
);
309 if (args
.size() == 4) {
310 const Value
& deps_value
= args
[3];
311 if (!deps_value
.VerifyTypeIs(Value::LIST
, err
))
314 for (size_t i
= 0; i
< deps_value
.list_value().size(); i
++) {
315 if (!deps_value
.list_value()[0].VerifyTypeIs(Value::STRING
, err
))
317 g_scheduler
->AddGenDependency(
318 build_settings
->GetFullPath(cur_dir
.ResolveRelativeFile(
319 deps_value
.list_value()[0].string_value())));
323 // Make the command line.
324 const base::FilePath
& python_path
= build_settings
->python_path();
325 CommandLine
cmdline(python_path
);
326 cmdline
.AppendArgPath(script_path
);
328 const Value
& script_args
= args
[1];
329 if (!script_args
.VerifyTypeIs(Value::LIST
, err
))
331 for (size_t i
= 0; i
< script_args
.list_value().size(); i
++) {
332 if (!script_args
.list_value()[i
].VerifyTypeIs(Value::STRING
, err
))
334 cmdline
.AppendArg(script_args
.list_value()[i
].string_value());
337 // Log command line for debugging help.
338 trace
.SetCommandLine(cmdline
);
339 base::TimeTicks begin_exec
;
340 if (g_scheduler
->verbose_logging()) {
342 g_scheduler
->Log("Pythoning", UTF16ToUTF8(cmdline
.GetCommandLineString()));
344 g_scheduler
->Log("Pythoning", cmdline
.GetCommandLineString());
346 begin_exec
= base::TimeTicks::Now();
349 base::FilePath startup_dir
=
350 build_settings
->GetFullPath(build_settings
->build_dir());
352 // Execute the process.
353 // TODO(brettw) set the environment block.
355 std::string stderr_output
; // TODO(brettw) not hooked up, see above.
357 if (!CommandLine::ForCurrentProcess()->HasSwitch(kNoExecSwitch
)) {
358 if (!ExecProcess(cmdline
, startup_dir
,
359 &output
, &stderr_output
, &exit_code
)) {
360 *err
= Err(function
->function(), "Could not execute python.",
361 "I was trying to execute \"" + FilePathToUTF8(python_path
) + "\".");
365 if (g_scheduler
->verbose_logging()) {
366 g_scheduler
->Log("Pythoning", script_source
.value() + " took " +
368 (base::TimeTicks::Now() - begin_exec
).InMilliseconds()) +
372 // TODO(brettw) maybe we need stderr also for reasonable stack dumps.
373 if (exit_code
!= 0) {
374 std::string msg
= "Current dir: " + FilePathToUTF8(startup_dir
) +
375 "\nCommand: " + FilePathToUTF8(cmdline
.GetCommandLineString()) +
376 "\nReturned " + base::IntToString(exit_code
);
378 msg
+= " and printed out:\n\n" + output
;
381 *err
= Err(function
->function(), "Script returned non-zero exit code.",
386 return ConvertInputToValue(output
, function
, args
[2], err
);
389 } // namespace functions