cmcldeps.cxx 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664
  1. /*
  2. ninja's subprocess.h
  3. */
  4. // Copyright 2012 Google Inc. All Rights Reserved.
  5. //
  6. // Licensed under the Apache License, Version 2.0 (the "License");
  7. // you may not use this file except in compliance with the License.
  8. // You may obtain a copy of the License at
  9. //
  10. // http://www.apache.org/licenses/LICENSE-2.0
  11. //
  12. // Unless required by applicable law or agreed to in writing, software
  13. // distributed under the License is distributed on an "AS IS" BASIS,
  14. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. // See the License for the specific language governing permissions and
  16. // limitations under the License.
  17. #ifndef NINJA_SUBPROCESS_H_
  18. #define NINJA_SUBPROCESS_H_
  19. #include <string>
  20. #include <vector>
  21. #include <queue>
  22. using namespace std;
  23. #ifdef _WIN32
  24. #include <windows.h>
  25. #else
  26. #include <signal.h>
  27. #endif
  28. //#include "exit_status.h"
  29. enum ExitStatus {
  30. ExitSuccess,
  31. ExitFailure,
  32. ExitInterrupted
  33. };
  34. /// Subprocess wraps a single async subprocess. It is entirely
  35. /// passive: it expects the caller to notify it when its fds are ready
  36. /// for reading, as well as call Finish() to reap the child once done()
  37. /// is true.
  38. struct Subprocess {
  39. ~Subprocess();
  40. /// Returns ExitSuccess on successful process exit, ExitInterrupted if
  41. /// the process was interrupted, ExitFailure if it otherwise failed.
  42. ExitStatus Finish();
  43. bool Done() const;
  44. const string& GetOutput() const;
  45. int ExitCode() const { return exit_code_; }
  46. private:
  47. Subprocess();
  48. bool Start(struct SubprocessSet* set, const string& command);
  49. void OnPipeReady();
  50. string buf_;
  51. #ifdef _WIN32
  52. /// Set up pipe_ as the parent-side pipe of the subprocess; return the
  53. /// other end of the pipe, usable in the child process.
  54. HANDLE SetupPipe(HANDLE ioport);
  55. HANDLE child_;
  56. HANDLE pipe_;
  57. OVERLAPPED overlapped_;
  58. char overlapped_buf_[4 << 10];
  59. bool is_reading_;
  60. int exit_code_;
  61. #else
  62. int fd_;
  63. pid_t pid_;
  64. #endif
  65. friend struct SubprocessSet;
  66. };
  67. /// SubprocessSet runs a ppoll/pselect() loop around a set of Subprocesses.
  68. /// DoWork() waits for any state change in subprocesses; finished_
  69. /// is a queue of subprocesses as they finish.
  70. struct SubprocessSet {
  71. SubprocessSet();
  72. ~SubprocessSet();
  73. Subprocess* Add(const string& command);
  74. bool DoWork();
  75. Subprocess* NextFinished();
  76. void Clear();
  77. vector<Subprocess*> running_;
  78. queue<Subprocess*> finished_;
  79. #ifdef _WIN32
  80. static BOOL WINAPI NotifyInterrupted(DWORD dwCtrlType);
  81. static HANDLE ioport_;
  82. #else
  83. static void SetInterruptedFlag(int signum);
  84. static bool interrupted_;
  85. struct sigaction old_act_;
  86. sigset_t old_mask_;
  87. #endif
  88. };
  89. #endif // NINJA_SUBPROCESS_H_
  90. /*
  91. ninja's util functions
  92. */
  93. static void Fatal(const char* msg, ...) {
  94. va_list ap;
  95. fprintf(stderr, "ninja: FATAL: ");
  96. va_start(ap, msg);
  97. vfprintf(stderr, msg, ap);
  98. va_end(ap);
  99. fprintf(stderr, "\n");
  100. #ifdef _WIN32
  101. // On Windows, some tools may inject extra threads.
  102. // exit() may block on locks held by those threads, so forcibly exit.
  103. fflush(stderr);
  104. fflush(stdout);
  105. ExitProcess(1);
  106. #else
  107. exit(1);
  108. #endif
  109. }
  110. #ifdef _WIN32
  111. string GetLastErrorString() {
  112. DWORD err = GetLastError();
  113. char* msg_buf;
  114. FormatMessageA(
  115. FORMAT_MESSAGE_ALLOCATE_BUFFER |
  116. FORMAT_MESSAGE_FROM_SYSTEM |
  117. FORMAT_MESSAGE_IGNORE_INSERTS,
  118. NULL,
  119. err,
  120. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  121. (char*)&msg_buf,
  122. 0,
  123. NULL);
  124. string msg = msg_buf;
  125. LocalFree(msg_buf);
  126. return msg;
  127. }
  128. #endif
  129. #define snprintf _snprintf
  130. /*
  131. ninja's subprocess-win32.cc
  132. */
  133. // Copyright 2012 Google Inc. All Rights Reserved.
  134. //
  135. // Licensed under the Apache License, Version 2.0 (the "License");
  136. // you may not use this file except in compliance with the License.
  137. // You may obtain a copy of the License at
  138. //
  139. // http://www.apache.org/licenses/LICENSE-2.0
  140. //
  141. // Unless required by applicable law or agreed to in writing, software
  142. // distributed under the License is distributed on an "AS IS" BASIS,
  143. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  144. // See the License for the specific language governing permissions and
  145. // limitations under the License.
  146. //#include "subprocess.h"
  147. #include <stdio.h>
  148. #include <algorithm>
  149. //#include "util.h"
  150. namespace {
  151. void Win32Fatal(const char* function) {
  152. Fatal("%s: %s", function, GetLastErrorString().c_str());
  153. }
  154. } // anonymous namespace
  155. Subprocess::Subprocess() : child_(NULL) , overlapped_(), is_reading_(false),
  156. exit_code_(1) {
  157. }
  158. Subprocess::~Subprocess() {
  159. if (pipe_) {
  160. if (!CloseHandle(pipe_))
  161. Win32Fatal("CloseHandle");
  162. }
  163. // Reap child if forgotten.
  164. if (child_)
  165. Finish();
  166. }
  167. HANDLE Subprocess::SetupPipe(HANDLE ioport) {
  168. char pipe_name[100];
  169. snprintf(pipe_name, sizeof(pipe_name),
  170. "\\\\.\\pipe\\ninja_pid%u_sp%p", GetCurrentProcessId(), this);
  171. pipe_ = ::CreateNamedPipeA(pipe_name,
  172. PIPE_ACCESS_INBOUND | FILE_FLAG_OVERLAPPED,
  173. PIPE_TYPE_BYTE,
  174. PIPE_UNLIMITED_INSTANCES,
  175. 0, 0, INFINITE, NULL);
  176. if (pipe_ == INVALID_HANDLE_VALUE)
  177. Win32Fatal("CreateNamedPipe");
  178. if (!CreateIoCompletionPort(pipe_, ioport, (ULONG_PTR)this, 0))
  179. Win32Fatal("CreateIoCompletionPort");
  180. memset(&overlapped_, 0, sizeof(overlapped_));
  181. if (!ConnectNamedPipe(pipe_, &overlapped_) &&
  182. GetLastError() != ERROR_IO_PENDING) {
  183. Win32Fatal("ConnectNamedPipe");
  184. }
  185. // Get the write end of the pipe as a handle inheritable across processes.
  186. HANDLE output_write_handle = CreateFile(pipe_name, GENERIC_WRITE, 0,
  187. NULL, OPEN_EXISTING, 0, NULL);
  188. HANDLE output_write_child;
  189. if (!DuplicateHandle(GetCurrentProcess(), output_write_handle,
  190. GetCurrentProcess(), &output_write_child,
  191. 0, TRUE, DUPLICATE_SAME_ACCESS)) {
  192. Win32Fatal("DuplicateHandle");
  193. }
  194. CloseHandle(output_write_handle);
  195. return output_write_child;
  196. }
  197. bool Subprocess::Start(SubprocessSet* set, const string& command) {
  198. HANDLE child_pipe = SetupPipe(set->ioport_);
  199. SECURITY_ATTRIBUTES security_attributes;
  200. memset(&security_attributes, 0, sizeof(SECURITY_ATTRIBUTES));
  201. security_attributes.nLength = sizeof(SECURITY_ATTRIBUTES);
  202. security_attributes.bInheritHandle = TRUE;
  203. // Must be inheritable so subprocesses can dup to children.
  204. HANDLE nul = CreateFile("NUL", GENERIC_READ,
  205. FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
  206. &security_attributes, OPEN_EXISTING, 0, NULL);
  207. if (nul == INVALID_HANDLE_VALUE)
  208. Fatal("couldn't open nul");
  209. STARTUPINFOA startup_info;
  210. memset(&startup_info, 0, sizeof(startup_info));
  211. startup_info.cb = sizeof(STARTUPINFO);
  212. startup_info.dwFlags = STARTF_USESTDHANDLES;
  213. startup_info.hStdInput = nul;
  214. startup_info.hStdOutput = child_pipe;
  215. startup_info.hStdError = child_pipe;
  216. PROCESS_INFORMATION process_info;
  217. memset(&process_info, 0, sizeof(process_info));
  218. // Do not prepend 'cmd /c' on Windows, this breaks command
  219. // lines greater than 8,191 chars.
  220. if (!CreateProcessA(NULL, (char*)command.c_str(), NULL, NULL,
  221. /* inherit handles */ TRUE, CREATE_NEW_PROCESS_GROUP,
  222. NULL, NULL,
  223. &startup_info, &process_info)) {
  224. DWORD error = GetLastError();
  225. if (error == ERROR_FILE_NOT_FOUND) {
  226. // file (program) not found error is treated
  227. // as a normal build action failure
  228. if (child_pipe)
  229. CloseHandle(child_pipe);
  230. CloseHandle(pipe_);
  231. CloseHandle(nul);
  232. pipe_ = NULL;
  233. // child_ is already NULL;
  234. buf_ =
  235. "CreateProcess failed: The system cannot find the file specified.\n";
  236. return true;
  237. } else {
  238. Win32Fatal("CreateProcess"); // pass all other errors to Win32Fatal
  239. }
  240. }
  241. // Close pipe channel only used by the child.
  242. if (child_pipe)
  243. CloseHandle(child_pipe);
  244. CloseHandle(nul);
  245. CloseHandle(process_info.hThread);
  246. child_ = process_info.hProcess;
  247. return true;
  248. }
  249. void Subprocess::OnPipeReady() {
  250. DWORD bytes;
  251. if (!GetOverlappedResult(pipe_, &overlapped_, &bytes, TRUE)) {
  252. if (GetLastError() == ERROR_BROKEN_PIPE) {
  253. CloseHandle(pipe_);
  254. pipe_ = NULL;
  255. return;
  256. }
  257. Win32Fatal("GetOverlappedResult");
  258. }
  259. if (is_reading_ && bytes)
  260. buf_.append(overlapped_buf_, bytes);
  261. memset(&overlapped_, 0, sizeof(overlapped_));
  262. is_reading_ = true;
  263. if (!::ReadFile(pipe_, overlapped_buf_, sizeof(overlapped_buf_),
  264. &bytes, &overlapped_)) {
  265. if (GetLastError() == ERROR_BROKEN_PIPE) {
  266. CloseHandle(pipe_);
  267. pipe_ = NULL;
  268. return;
  269. }
  270. if (GetLastError() != ERROR_IO_PENDING)
  271. Win32Fatal("ReadFile");
  272. }
  273. // Even if we read any bytes in the readfile call, we'll enter this
  274. // function again later and get them at that point.
  275. }
  276. ExitStatus Subprocess::Finish() {
  277. if (!child_)
  278. return ExitFailure;
  279. // TODO: add error handling for all of these.
  280. WaitForSingleObject(child_, INFINITE);
  281. DWORD exit_code = 0;
  282. GetExitCodeProcess(child_, &exit_code);
  283. CloseHandle(child_);
  284. child_ = NULL;
  285. exit_code_ = exit_code;
  286. return exit_code == 0 ? ExitSuccess :
  287. exit_code == CONTROL_C_EXIT ? ExitInterrupted :
  288. ExitFailure;
  289. }
  290. bool Subprocess::Done() const {
  291. return pipe_ == NULL;
  292. }
  293. const string& Subprocess::GetOutput() const {
  294. return buf_;
  295. }
  296. HANDLE SubprocessSet::ioport_;
  297. SubprocessSet::SubprocessSet() {
  298. ioport_ = ::CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 1);
  299. if (!ioport_)
  300. Win32Fatal("CreateIoCompletionPort");
  301. if (!SetConsoleCtrlHandler(NotifyInterrupted, TRUE))
  302. Win32Fatal("SetConsoleCtrlHandler");
  303. }
  304. SubprocessSet::~SubprocessSet() {
  305. Clear();
  306. SetConsoleCtrlHandler(NotifyInterrupted, FALSE);
  307. CloseHandle(ioport_);
  308. }
  309. BOOL WINAPI SubprocessSet::NotifyInterrupted(DWORD dwCtrlType) {
  310. if (dwCtrlType == CTRL_C_EVENT || dwCtrlType == CTRL_BREAK_EVENT) {
  311. if (!PostQueuedCompletionStatus(ioport_, 0, 0, NULL))
  312. Win32Fatal("PostQueuedCompletionStatus");
  313. return TRUE;
  314. }
  315. return FALSE;
  316. }
  317. Subprocess *SubprocessSet::Add(const string& command) {
  318. Subprocess *subprocess = new Subprocess;
  319. if (!subprocess->Start(this, command)) {
  320. delete subprocess;
  321. return 0;
  322. }
  323. if (subprocess->child_)
  324. running_.push_back(subprocess);
  325. else
  326. finished_.push(subprocess);
  327. return subprocess;
  328. }
  329. bool SubprocessSet::DoWork() {
  330. DWORD bytes_read;
  331. Subprocess* subproc;
  332. OVERLAPPED* overlapped;
  333. if (!GetQueuedCompletionStatus(ioport_, &bytes_read, (PULONG_PTR)&subproc,
  334. &overlapped, INFINITE)) {
  335. if (GetLastError() != ERROR_BROKEN_PIPE)
  336. Win32Fatal("GetQueuedCompletionStatus");
  337. }
  338. if (!subproc) // A NULL subproc indicates that we were interrupted and is
  339. // delivered by NotifyInterrupted above.
  340. return true;
  341. subproc->OnPipeReady();
  342. if (subproc->Done()) {
  343. vector<Subprocess*>::iterator end =
  344. std::remove(running_.begin(), running_.end(), subproc);
  345. if (running_.end() != end) {
  346. finished_.push(subproc);
  347. running_.resize(end - running_.begin());
  348. }
  349. }
  350. return false;
  351. }
  352. Subprocess* SubprocessSet::NextFinished() {
  353. if (finished_.empty())
  354. return NULL;
  355. Subprocess* subproc = finished_.front();
  356. finished_.pop();
  357. return subproc;
  358. }
  359. void SubprocessSet::Clear() {
  360. for (vector<Subprocess*>::iterator i = running_.begin();
  361. i != running_.end(); ++i) {
  362. if ((*i)->child_)
  363. if (!GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT,
  364. GetProcessId((*i)->child_)))
  365. Win32Fatal("GenerateConsoleCtrlEvent");
  366. }
  367. for (vector<Subprocess*>::iterator i = running_.begin();
  368. i != running_.end(); ++i)
  369. delete *i;
  370. running_.clear();
  371. }
  372. // Copyright 2011 Google Inc. All Rights Reserved.
  373. //
  374. // Licensed under the Apache License, Version 2.0 (the "License");
  375. // you may not use this file except in compliance with the License.
  376. // You may obtain a copy of the License at
  377. //
  378. // http://www.apache.org/licenses/LICENSE-2.0
  379. //
  380. // Unless required by applicable law or agreed to in writing, software
  381. // distributed under the License is distributed on an "AS IS" BASIS,
  382. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  383. // See the License for the specific language governing permissions and
  384. // limitations under the License.
  385. // Wrapper around cl that adds /showIncludes to command line, and uses that to
  386. // generate .d files that match the style from gcc -MD.
  387. //
  388. // /showIncludes is equivalent to -MD, not -MMD, that is, system headers are
  389. // included.
  390. #include <windows.h>
  391. #include <sstream>
  392. //#include "subprocess.h"
  393. //#include "util.h"
  394. // We don't want any wildcard expansion.
  395. // See http://msdn.microsoft.com/en-us/library/zay8tzh6(v=vs.85).aspx
  396. void _setargv() {}
  397. static void usage(const char* msg) {
  398. Fatal("%s\n\nusage:\n"
  399. " cldeps "
  400. "<source file> "
  401. "<output path for *.d file> "
  402. "<output path for *.obj file> "
  403. "<prefix of /showIncludes> "
  404. "<path to cl> "
  405. "<rest of command ...>\n", msg);
  406. }
  407. static string trimLeadingSpace(const string& cmdline) {
  408. int i = 0;
  409. for (; cmdline[i] == ' '; ++i)
  410. ;
  411. return cmdline.substr(i);
  412. }
  413. static void doEscape(string& str, const string& search, const string& repl) {
  414. string::size_type pos = 0;
  415. while ((pos = str.find(search, pos)) != string::npos) {
  416. str.replace(pos, search.size(), repl);
  417. pos += repl.size();
  418. }
  419. }
  420. // Strips one argument from the cmdline and returns it. "surrounding quotes"
  421. // are removed from the argument if there were any.
  422. static string getArg(string& cmdline) {
  423. string ret;
  424. bool in_quoted = false;
  425. unsigned int i = 0;
  426. cmdline = trimLeadingSpace(cmdline);
  427. for (;; ++i) {
  428. if (i >= cmdline.size())
  429. usage("Couldn't parse arguments.");
  430. if (!in_quoted && cmdline[i] == ' ')
  431. break; // "a b" "x y"
  432. if (cmdline[i] == '"')
  433. in_quoted = !in_quoted;
  434. }
  435. ret = cmdline.substr(0, i);
  436. if (ret[0] == '"' && ret[i - 1] == '"')
  437. ret = ret.substr(1, ret.size() - 2);
  438. cmdline = cmdline.substr(i);
  439. return ret;
  440. }
  441. static void parseCommandLine(LPTSTR wincmdline,
  442. string& srcfile,
  443. string& dfile,
  444. string& objfile,
  445. string& prefix,
  446. string& clpath,
  447. string& rest) {
  448. string cmdline(wincmdline);
  449. /* self */ getArg(cmdline);
  450. srcfile = getArg(cmdline);
  451. std::string::size_type pos = srcfile.rfind("\\");
  452. if (pos != string::npos) {
  453. srcfile = srcfile.substr(pos + 1);
  454. } else {
  455. srcfile = "";
  456. }
  457. dfile = getArg(cmdline);
  458. objfile = getArg(cmdline);
  459. prefix = getArg(cmdline);
  460. clpath = getArg(cmdline);
  461. rest = trimLeadingSpace(cmdline);
  462. }
  463. static void outputDepFile(const string& dfile, const string& objfile,
  464. vector<string>& incs) {
  465. // strip duplicates
  466. sort(incs.begin(), incs.end());
  467. incs.erase(unique(incs.begin(), incs.end()), incs.end());
  468. FILE* out = fopen(dfile.c_str(), "wb");
  469. // FIXME should this be fatal or not? delete obj? delete d?
  470. if (!out)
  471. return;
  472. string tmp = objfile;
  473. doEscape(tmp, " ", "\\ ");
  474. fprintf(out, "%s: \\\n", tmp.c_str());
  475. for (vector<string>::iterator i(incs.begin()); i != incs.end(); ++i) {
  476. tmp = *i;
  477. doEscape(tmp, "\\", "/");
  478. doEscape(tmp, " ", "\\ ");
  479. //doEscape(tmp, "(", "\\("); // TODO ninja can't read ( and )
  480. //doEscape(tmp, ")", "\\)");
  481. fprintf(out, "%s \\\n", tmp.c_str());
  482. }
  483. fprintf(out, "\n");
  484. fclose(out);
  485. }
  486. bool startsWith(const std::string& str, const std::string& what) {
  487. return str.compare(0, what.size(), what) == 0;
  488. }
  489. bool contains(const std::string& str, const std::string& what) {
  490. return str.find(what) != std::string::npos;
  491. }
  492. int main() {
  493. // Use the Win32 api instead of argc/argv so we can avoid interpreting the
  494. // rest of command line after the .d and .obj. Custom parsing seemed
  495. // preferable to the ugliness you get into in trying to re-escape quotes for
  496. // subprocesses, so by avoiding argc/argv, the subprocess is called with
  497. // the same command line verbatim.
  498. string srcfile, dfile, objfile, prefix, clpath, rest;
  499. parseCommandLine(GetCommandLine(), srcfile, dfile, objfile,
  500. prefix, clpath, rest);
  501. #if 0
  502. fprintf(stderr, "\n\ncmcldebug:\n");
  503. fprintf(stderr, ".d : %s\n", dfile.c_str());
  504. fprintf(stderr, "OBJ : %s\n", objfile.c_str());
  505. fprintf(stderr, "CL : %s\n", clpath.c_str());
  506. fprintf(stderr, "REST: %s\n", rest.c_str());
  507. fprintf(stderr, "\n\n");
  508. #endif
  509. SubprocessSet subprocs;
  510. Subprocess* subproc = subprocs.Add(clpath + " /showIncludes " + rest);
  511. if(!subproc)
  512. return 2;
  513. while ((subproc = subprocs.NextFinished()) == NULL) {
  514. subprocs.DoWork();
  515. }
  516. bool success = subproc->Finish() == ExitSuccess;
  517. int exit_code = subproc->ExitCode();
  518. string output = subproc->GetOutput();
  519. delete subproc;
  520. // process the include directives and output everything else
  521. stringstream ss(output);
  522. string line;
  523. vector<string> includes;
  524. bool isFirstLine = true; // cl prints always first the source filename
  525. while (getline(ss, line)) {
  526. if (startsWith(line, prefix)) {
  527. if (!contains(line, "(") && !contains(line, ")")) {
  528. string inc = trimLeadingSpace(line.substr(prefix.size()).c_str());
  529. if (inc[inc.size() - 1] == '\r') // blech, stupid \r\n
  530. inc = inc.substr(0, inc.size() - 1);
  531. includes.push_back(inc);
  532. }
  533. } else {
  534. if (!isFirstLine || !startsWith(line, srcfile)) {
  535. fprintf(stdout, "%s\n", line.c_str());
  536. } else {
  537. isFirstLine = false;
  538. }
  539. }
  540. }
  541. if (!success)
  542. return exit_code;
  543. // don't update .d until/unless we succeed compilation
  544. outputDepFile(dfile, objfile, includes);
  545. return 0;
  546. }