Add utility functions needed for rect-based event targeting
[chromium-blink-merge.git] / tools / gn / function_exec_script.cc
blob540d189069aae8803d5aa2c316637bd7bca0b95c
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"
24 #if defined(OS_WIN)
25 #include <windows.h>
27 #include "base/win/scoped_handle.h"
28 #include "base/win/scoped_process_information.h"
29 #endif
31 #if defined(OS_POSIX)
32 #include <fcntl.h>
33 #include <unistd.h>
35 #include "base/posix/file_descriptor_shuffle.h"
36 #endif
38 namespace functions {
40 namespace {
42 const char kNoExecSwitch[] = "no-exec";
44 #if defined(OS_WIN)
45 bool ExecProcess(const CommandLine& cmdline,
46 const base::FilePath& startup_dir,
47 std::string* std_out,
48 std::string* std_err,
49 int* exit_code) {
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";
61 return false;
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";
71 return false;
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";
79 return false;
81 if (!SetHandleInformation(err_read, HANDLE_FLAG_INHERIT, 0)) {
82 NOTREACHED() << "Failed to disabled pipe inheritance";
83 return false;
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,
102 &cmdline_str[0],
103 NULL, NULL,
104 TRUE, // Handles are inherited.
105 0, NULL,
106 startup_dir.value().c_str(),
107 &start_info, proc_info.Receive())) {
108 return false;
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.
123 for (;;) {
124 DWORD bytes_read = 0;
125 BOOL success = ReadFile(out_read, buffer, kBufferSize, &bytes_read, NULL);
126 if (!success || bytes_read == 0)
127 break;
128 std_out->append(buffer, bytes_read);
131 // Let's wait for the process to finish.
132 WaitForSingleObject(proc_info.process_handle(), INFINITE);
134 DWORD dw_exit_code;
135 GetExitCodeProcess(proc_info.process_handle(), &dw_exit_code);
136 *exit_code = static_cast<int>(dw_exit_code);
138 return true;
140 #else
141 bool ExecProcess(const CommandLine& cmdline,
142 const base::FilePath& startup_dir,
143 std::string* std_out,
144 std::string* std_err,
145 int* exit_code) {
146 *exit_code = EXIT_FAILURE;
148 std::vector<std::string> argv = cmdline.argv();
150 int pipe_fd[2];
151 pid_t pid;
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)
159 return false;
161 switch (pid = fork()) {
162 case -1: // error
163 close(pipe_fd[0]);
164 close(pipe_fd[1]);
165 return false;
166 case 0: // child
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
175 // in the child.
176 int dev_null = open("/dev/null", O_WRONLY);
177 if (dev_null < 0)
178 _exit(127);
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
187 // reserve(), above.
189 std::copy(fd_shuffle1.begin(), fd_shuffle1.end(),
190 std::back_inserter(fd_shuffle2));
192 if (!ShuffleFileDescriptors(&fd_shuffle1))
193 _exit(127);
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());
204 _exit(127);
206 default: // parent
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).
211 close(pipe_fd[1]);
213 char buffer[256];
214 ssize_t bytes_read = 0;
216 while (true) {
217 bytes_read = HANDLE_EINTR(read(pipe_fd[0], buffer, sizeof(buffer)));
218 if (bytes_read <= 0)
219 break;
220 std_out->append(buffer, bytes_read);
222 close(pipe_fd[0]);
224 return base::WaitForExitCode(pid, exit_code);
228 return false;
230 #endif
232 } // namespace
234 const char kExecScript[] = "exec_script";
235 const char kExecScript_Help[] =
236 "exec_script: Synchronously run a script and return the output.\n"
237 "\n"
238 " exec_script(filename, arguments, input_conversion,\n"
239 " [file_dependencies])\n"
240 "\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"
243 " exit code.\n"
244 "\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"
249 "\n"
250 "Arguments:\n"
251 "\n"
252 " filename:\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"
255 "\n"
256 " arguments:\n"
257 " A list of strings to be passed to the script as arguments.\n"
258 "\n"
259 " input_conversion:\n"
260 " Controls how the file is read and parsed.\n"
261 " See \"gn help input_conversion\".\n"
262 "\n"
263 " dependencies:\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"
268 "\n"
269 " The script itself will be an implicit dependency so you do not\n"
270 " need to list it.\n"
271 "\n"
272 "Example:\n"
273 "\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,
280 Err* err) {
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.");
284 return Value();
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))
293 return Value();
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
307 // build deps.
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))
312 return Value();
314 for (size_t i = 0; i < deps_value.list_value().size(); i++) {
315 if (!deps_value.list_value()[0].VerifyTypeIs(Value::STRING, err))
316 return Value();
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))
330 return Value();
331 for (size_t i = 0; i < script_args.list_value().size(); i++) {
332 if (!script_args.list_value()[i].VerifyTypeIs(Value::STRING, err))
333 return Value();
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()) {
341 #if defined(OS_WIN)
342 g_scheduler->Log("Pythoning", UTF16ToUTF8(cmdline.GetCommandLineString()));
343 #else
344 g_scheduler->Log("Pythoning", cmdline.GetCommandLineString());
345 #endif
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.
354 std::string output;
355 std::string stderr_output; // TODO(brettw) not hooked up, see above.
356 int exit_code = 0;
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) + "\".");
362 return Value();
365 if (g_scheduler->verbose_logging()) {
366 g_scheduler->Log("Pythoning", script_source.value() + " took " +
367 base::Int64ToString(
368 (base::TimeTicks::Now() - begin_exec).InMilliseconds()) +
369 "ms");
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);
377 if (!output.empty())
378 msg += " and printed out:\n\n" + output;
379 else
380 msg += ".";
381 *err = Err(function->function(), "Script returned non-zero exit code.",
382 msg);
383 return Value();
386 return ConvertInputToValue(output, function, args[2], err);
389 } // namespace functions