cmcldeps.cxx 20.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/*
    ninja's subprocess.h
*/

// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef NINJA_SUBPROCESS_H_
#define NINJA_SUBPROCESS_H_

#include <string>
#include <vector>
#include <queue>
25
#include <cstdio>
26
#include <algorithm>
27

28 29 30 31 32 33 34

#ifdef _WIN32
#include <windows.h>
#else
#include <signal.h>
#endif

35 36 37 38

// bcc32 only finds remove(const char*)
namespace stlport { }

39 40 41 42 43 44
#if defined(_WIN64)
typedef unsigned __int64 cmULONG_PTR;
#else
typedef unsigned long cmULONG_PTR;
#endif

45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
//#include "exit_status.h"
enum ExitStatus {
  ExitSuccess,
  ExitFailure,
  ExitInterrupted
};

/// Subprocess wraps a single async subprocess.  It is entirely
/// passive: it expects the caller to notify it when its fds are ready
/// for reading, as well as call Finish() to reap the child once done()
/// is true.
struct Subprocess {
  ~Subprocess();

  /// Returns ExitSuccess on successful process exit, ExitInterrupted if
  /// the process was interrupted, ExitFailure if it otherwise failed.
  ExitStatus Finish();

  bool Done() const;

Peter Kuemmel's avatar
Peter Kuemmel committed
65
  const std::string& GetOutput() const;
66

67 68
  int ExitCode() const { return exit_code_; }

69 70
 private:
  Subprocess();
71 72
  bool Start(struct SubprocessSet* set, const std::string& command,
                                        const std::string& dir);
73 74
  void OnPipeReady();

Peter Kuemmel's avatar
Peter Kuemmel committed
75
  std::string buf_;
76 77 78 79 80 81

#ifdef _WIN32
  /// Set up pipe_ as the parent-side pipe of the subprocess; return the
  /// other end of the pipe, usable in the child process.
  HANDLE SetupPipe(HANDLE ioport);

82
  PROCESS_INFORMATION child_;
83 84 85 86
  HANDLE pipe_;
  OVERLAPPED overlapped_;
  char overlapped_buf_[4 << 10];
  bool is_reading_;
87
  int exit_code_;
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
#else
  int fd_;
  pid_t pid_;
#endif

  friend struct SubprocessSet;
};

/// SubprocessSet runs a ppoll/pselect() loop around a set of Subprocesses.
/// DoWork() waits for any state change in subprocesses; finished_
/// is a queue of subprocesses as they finish.
struct SubprocessSet {
  SubprocessSet();
  ~SubprocessSet();

Peter Kuemmel's avatar
Peter Kuemmel committed
103
  Subprocess* Add(const std::string& command, const std::string& dir);
104 105 106 107
  bool DoWork();
  Subprocess* NextFinished();
  void Clear();

Peter Kuemmel's avatar
Peter Kuemmel committed
108 109
  std::vector<Subprocess*> running_;
  std::queue<Subprocess*> finished_;
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150

#ifdef _WIN32
  static BOOL WINAPI NotifyInterrupted(DWORD dwCtrlType);
  static HANDLE ioport_;
#else
  static void SetInterruptedFlag(int signum);
  static bool interrupted_;

  struct sigaction old_act_;
  sigset_t old_mask_;
#endif
};

#endif // NINJA_SUBPROCESS_H_


/*
    ninja's util functions
*/


static void Fatal(const char* msg, ...) {
  va_list ap;
  fprintf(stderr, "ninja: FATAL: ");
  va_start(ap, msg);
  vfprintf(stderr, msg, ap);
  va_end(ap);
  fprintf(stderr, "\n");
#ifdef _WIN32
  // On Windows, some tools may inject extra threads.
  // exit() may block on locks held by those threads, so forcibly exit.
  fflush(stderr);
  fflush(stdout);
  ExitProcess(1);
#else
  exit(1);
#endif
}


#ifdef _WIN32
Peter Kuemmel's avatar
Peter Kuemmel committed
151
std::string GetLastErrorString() {
152 153 154 155 156 157 158 159 160 161 162 163 164
  DWORD err = GetLastError();

  char* msg_buf;
  FormatMessageA(
        FORMAT_MESSAGE_ALLOCATE_BUFFER |
        FORMAT_MESSAGE_FROM_SYSTEM |
        FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL,
        err,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
        (char*)&msg_buf,
        0,
        NULL);
Peter Kuemmel's avatar
Peter Kuemmel committed
165
  std::string msg = msg_buf;
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
  LocalFree(msg_buf);
  return msg;
}
#endif

#define snprintf _snprintf


/*
    ninja's subprocess-win32.cc
*/

// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//#include "subprocess.h"

#include <stdio.h>

#include <algorithm>

//#include "util.h"

namespace {

void Win32Fatal(const char* function) {
  Fatal("%s: %s", function, GetLastErrorString().c_str());
}

}  // anonymous namespace

208
Subprocess::Subprocess() : overlapped_(), is_reading_(false),
Peter Kuemmel's avatar
Peter Kuemmel committed
209
                           exit_code_(1) {
210
  child_.hProcess = NULL;
211 212 213 214 215 216 217 218
}

Subprocess::~Subprocess() {
  if (pipe_) {
    if (!CloseHandle(pipe_))
      Win32Fatal("CloseHandle");
  }
  // Reap child if forgotten.
219
  if (child_.hProcess)
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
    Finish();
}

HANDLE Subprocess::SetupPipe(HANDLE ioport) {
  char pipe_name[100];
  snprintf(pipe_name, sizeof(pipe_name),
           "\\\\.\\pipe\\ninja_pid%u_sp%p", GetCurrentProcessId(), this);

  pipe_ = ::CreateNamedPipeA(pipe_name,
                             PIPE_ACCESS_INBOUND | FILE_FLAG_OVERLAPPED,
                             PIPE_TYPE_BYTE,
                             PIPE_UNLIMITED_INSTANCES,
                             0, 0, INFINITE, NULL);
  if (pipe_ == INVALID_HANDLE_VALUE)
    Win32Fatal("CreateNamedPipe");

236
  if (!CreateIoCompletionPort(pipe_, ioport, (cmULONG_PTR)this, 0))
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
    Win32Fatal("CreateIoCompletionPort");

  memset(&overlapped_, 0, sizeof(overlapped_));
  if (!ConnectNamedPipe(pipe_, &overlapped_) &&
      GetLastError() != ERROR_IO_PENDING) {
    Win32Fatal("ConnectNamedPipe");
  }

  // Get the write end of the pipe as a handle inheritable across processes.
  HANDLE output_write_handle = CreateFile(pipe_name, GENERIC_WRITE, 0,
                                          NULL, OPEN_EXISTING, 0, NULL);
  HANDLE output_write_child;
  if (!DuplicateHandle(GetCurrentProcess(), output_write_handle,
                       GetCurrentProcess(), &output_write_child,
                       0, TRUE, DUPLICATE_SAME_ACCESS)) {
    Win32Fatal("DuplicateHandle");
  }
  CloseHandle(output_write_handle);

  return output_write_child;
}

Peter Kuemmel's avatar
Peter Kuemmel committed
259 260
bool Subprocess::Start(SubprocessSet* set, const std::string& command,
                                           const std::string& dir) {
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
  HANDLE child_pipe = SetupPipe(set->ioport_);

  SECURITY_ATTRIBUTES security_attributes;
  memset(&security_attributes, 0, sizeof(SECURITY_ATTRIBUTES));
  security_attributes.nLength = sizeof(SECURITY_ATTRIBUTES);
  security_attributes.bInheritHandle = TRUE;
  // Must be inheritable so subprocesses can dup to children.
  HANDLE nul = CreateFile("NUL", GENERIC_READ,
          FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
          &security_attributes, OPEN_EXISTING, 0, NULL);
  if (nul == INVALID_HANDLE_VALUE)
    Fatal("couldn't open nul");

  STARTUPINFOA startup_info;
  memset(&startup_info, 0, sizeof(startup_info));
  startup_info.cb = sizeof(STARTUPINFO);
  startup_info.dwFlags = STARTF_USESTDHANDLES;
  startup_info.hStdInput = nul;
  startup_info.hStdOutput = child_pipe;
  startup_info.hStdError = child_pipe;

  PROCESS_INFORMATION process_info;
  memset(&process_info, 0, sizeof(process_info));

  // Do not prepend 'cmd /c' on Windows, this breaks command
  // lines greater than 8,191 chars.
  if (!CreateProcessA(NULL, (char*)command.c_str(), NULL, NULL,
                      /* inherit handles */ TRUE, CREATE_NEW_PROCESS_GROUP,
289
                      NULL, (dir.empty() ? NULL : dir.c_str()),
290 291
                      &startup_info, &process_info)) {
    DWORD error = GetLastError();
Peter Kuemmel's avatar
Peter Kuemmel committed
292 293 294
    if (error == ERROR_FILE_NOT_FOUND) {
      // file (program) not found error is treated
      // as a normal build action failure
295 296 297 298 299 300
      if (child_pipe)
        CloseHandle(child_pipe);
      CloseHandle(pipe_);
      CloseHandle(nul);
      pipe_ = NULL;
      // child_ is already NULL;
Peter Kuemmel's avatar
Peter Kuemmel committed
301 302
      buf_ =
       "CreateProcess failed: The system cannot find the file specified.\n";
303 304 305 306 307 308 309 310 311 312 313 314
      return true;
    } else {
      Win32Fatal("CreateProcess");    // pass all other errors to Win32Fatal
    }
  }

  // Close pipe channel only used by the child.
  if (child_pipe)
    CloseHandle(child_pipe);
  CloseHandle(nul);

  CloseHandle(process_info.hThread);
315
  child_ = process_info;
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351

  return true;
}

void Subprocess::OnPipeReady() {
  DWORD bytes;
  if (!GetOverlappedResult(pipe_, &overlapped_, &bytes, TRUE)) {
    if (GetLastError() == ERROR_BROKEN_PIPE) {
      CloseHandle(pipe_);
      pipe_ = NULL;
      return;
    }
    Win32Fatal("GetOverlappedResult");
  }

  if (is_reading_ && bytes)
    buf_.append(overlapped_buf_, bytes);

  memset(&overlapped_, 0, sizeof(overlapped_));
  is_reading_ = true;
  if (!::ReadFile(pipe_, overlapped_buf_, sizeof(overlapped_buf_),
                  &bytes, &overlapped_)) {
    if (GetLastError() == ERROR_BROKEN_PIPE) {
      CloseHandle(pipe_);
      pipe_ = NULL;
      return;
    }
    if (GetLastError() != ERROR_IO_PENDING)
      Win32Fatal("ReadFile");
  }

  // Even if we read any bytes in the readfile call, we'll enter this
  // function again later and get them at that point.
}

ExitStatus Subprocess::Finish() {
352
  if (!child_.hProcess)
353 354 355
    return ExitFailure;

  // TODO: add error handling for all of these.
356
  WaitForSingleObject(child_.hProcess, INFINITE);
357 358

  DWORD exit_code = 0;
359
  GetExitCodeProcess(child_.hProcess, &exit_code);
360

361 362
  CloseHandle(child_.hProcess);
  child_.hProcess = NULL;
363
  exit_code_ = exit_code;
364 365 366 367 368 369 370 371 372
  return exit_code == 0              ? ExitSuccess :
         exit_code == CONTROL_C_EXIT ? ExitInterrupted :
                                       ExitFailure;
}

bool Subprocess::Done() const {
  return pipe_ == NULL;
}

Peter Kuemmel's avatar
Peter Kuemmel committed
373
const std::string& Subprocess::GetOutput() const {
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
  return buf_;
}

HANDLE SubprocessSet::ioport_;

SubprocessSet::SubprocessSet() {
  ioport_ = ::CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 1);
  if (!ioport_)
    Win32Fatal("CreateIoCompletionPort");
  if (!SetConsoleCtrlHandler(NotifyInterrupted, TRUE))
    Win32Fatal("SetConsoleCtrlHandler");
}

SubprocessSet::~SubprocessSet() {
  Clear();

  SetConsoleCtrlHandler(NotifyInterrupted, FALSE);
  CloseHandle(ioport_);
}

BOOL WINAPI SubprocessSet::NotifyInterrupted(DWORD dwCtrlType) {
  if (dwCtrlType == CTRL_C_EVENT || dwCtrlType == CTRL_BREAK_EVENT) {
    if (!PostQueuedCompletionStatus(ioport_, 0, 0, NULL))
      Win32Fatal("PostQueuedCompletionStatus");
    return TRUE;
  }

  return FALSE;
}

404 405
Subprocess *SubprocessSet::Add(const std::string& command,
                               const std::string& dir) {
406
  Subprocess *subprocess = new Subprocess;
407
  if (!subprocess->Start(this, command, dir)) {
408 409 410
    delete subprocess;
    return 0;
  }
411
  if (subprocess->child_.hProcess)
412 413 414 415 416 417 418 419 420 421 422
    running_.push_back(subprocess);
  else
    finished_.push(subprocess);
  return subprocess;
}

bool SubprocessSet::DoWork() {
  DWORD bytes_read;
  Subprocess* subproc;
  OVERLAPPED* overlapped;

423
  if (!GetQueuedCompletionStatus(ioport_, &bytes_read, (cmULONG_PTR*)&subproc,
424 425 426 427 428 429 430 431 432 433 434 435
                                 &overlapped, INFINITE)) {
    if (GetLastError() != ERROR_BROKEN_PIPE)
      Win32Fatal("GetQueuedCompletionStatus");
  }

  if (!subproc) // A NULL subproc indicates that we were interrupted and is
                // delivered by NotifyInterrupted above.
    return true;

  subproc->OnPipeReady();

  if (subproc->Done()) {
436 437
    using namespace std;
    using namespace stlport;
Peter Kuemmel's avatar
Peter Kuemmel committed
438
    std::vector<Subprocess*>::iterator end =
439
        remove(running_.begin(), running_.end(), subproc);
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
    if (running_.end() != end) {
      finished_.push(subproc);
      running_.resize(end - running_.begin());
    }
  }

  return false;
}

Subprocess* SubprocessSet::NextFinished() {
  if (finished_.empty())
    return NULL;
  Subprocess* subproc = finished_.front();
  finished_.pop();
  return subproc;
}

void SubprocessSet::Clear() {
Peter Kuemmel's avatar
Peter Kuemmel committed
458 459 460
  std::vector<Subprocess*>::iterator it = running_.begin();
  for (; it != running_.end(); ++it) {
    if ((*it)->child_.hProcess) {
Peter Kuemmel's avatar
Peter Kuemmel committed
461
      if (!GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT,
Peter Kuemmel's avatar
Peter Kuemmel committed
462
                                    (*it)->child_.dwProcessId))
463
        Win32Fatal("GenerateConsoleCtrlEvent");
464
      }
465
  }
Peter Kuemmel's avatar
Peter Kuemmel committed
466 467 468
  it = running_.begin();
  for (; it != running_.end(); ++it)
    delete *it;
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
  running_.clear();
}


// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.


// Wrapper around cl that adds /showIncludes to command line, and uses that to
// generate .d files that match the style from gcc -MD.
//
// /showIncludes is equivalent to -MD, not -MMD, that is, system headers are
// included.


#include <windows.h>
#include <sstream>
//#include "subprocess.h"
//#include "util.h"

// We don't want any wildcard expansion.
// See http://msdn.microsoft.com/en-us/library/zay8tzh6(v=vs.85).aspx
void _setargv() {}

static void usage(const char* msg) {
Peter Kuemmel's avatar
Peter Kuemmel committed
505 506 507 508 509 510 511 512 513
  Fatal("%s\n\nusage:\n    "
          "cmcldeps "
          "<language C, CXX or RC>  "
          "<source file path>  "
          "<output path for *.d file>  "
          "<output path for *.obj file>  "
          "<prefix of /showIncludes>  "
          "<path to cl.exe>  "
          "<path to tool (cl or rc)>  "
514 515 516
          "<rest of command ...>\n", msg);
}

Peter Kuemmel's avatar
Peter Kuemmel committed
517
static std::string trimLeadingSpace(const std::string& cmdline) {
518 519 520 521 522 523
  int i = 0;
  for (; cmdline[i] == ' '; ++i)
    ;
  return cmdline.substr(i);
}

524 525
static void doEscape(std::string& str, const std::string& search,
                                       const std::string& repl) {
Peter Kuemmel's avatar
Peter Kuemmel committed
526 527
  std::string::size_type pos = 0;
  while ((pos = str.find(search, pos)) != std::string::npos) {
528 529 530 531 532 533 534
    str.replace(pos, search.size(), repl);
    pos += repl.size();
  }
}

// Strips one argument from the cmdline and returns it. "surrounding quotes"
// are removed from the argument if there were any.
Peter Kuemmel's avatar
Peter Kuemmel committed
535 536
static std::string getArg(std::string& cmdline) {
  std::string ret;
537 538 539 540 541 542 543 544 545
  bool in_quoted = false;
  unsigned int i = 0;

  cmdline = trimLeadingSpace(cmdline);

  for (;; ++i) {
    if (i >= cmdline.size())
      usage("Couldn't parse arguments.");
    if (!in_quoted && cmdline[i] == ' ')
546
      break; // "a b" "x y"
547 548 549 550 551 552 553 554 555 556 557 558
    if (cmdline[i] == '"')
      in_quoted = !in_quoted;
  }

  ret = cmdline.substr(0, i);
  if (ret[0] == '"' && ret[i - 1] == '"')
    ret = ret.substr(1, ret.size() - 2);
  cmdline = cmdline.substr(i);
  return ret;
}

static void parseCommandLine(LPTSTR wincmdline,
Peter Kuemmel's avatar
Peter Kuemmel committed
559 560 561 562 563 564 565 566 567
                             std::string& lang,
                             std::string& srcfile,
                             std::string& dfile,
                             std::string& objfile,
                             std::string& prefix,
                             std::string& clpath,
                             std::string& binpath,
                             std::string& rest) {
  std::string cmdline(wincmdline);
568
  /* self */ getArg(cmdline);
569
  lang = getArg(cmdline);
570 571 572 573 574
  srcfile = getArg(cmdline);
  dfile = getArg(cmdline);
  objfile = getArg(cmdline);
  prefix = getArg(cmdline);
  clpath = getArg(cmdline);
575
  binpath = getArg(cmdline);
576 577 578
  rest = trimLeadingSpace(cmdline);
}

Peter Kuemmel's avatar
Peter Kuemmel committed
579 580
static void outputDepFile(const std::string& dfile, const std::string& objfile,
        std::vector<std::string>& incs) {
581

582 583 584
  if (dfile.empty())
    return;

585
  // strip duplicates
Peter Kuemmel's avatar
Peter Kuemmel committed
586 587
  std::sort(incs.begin(), incs.end());
  incs.erase(std::unique(incs.begin(), incs.end()), incs.end());
588 589 590 591 592 593 594

  FILE* out = fopen(dfile.c_str(), "wb");

  // FIXME should this be fatal or not? delete obj? delete d?
  if (!out)
    return;

Peter Kuemmel's avatar
Peter Kuemmel committed
595
  std::string tmp = objfile;
596 597 598
  doEscape(tmp, " ", "\\ ");
  fprintf(out, "%s: \\\n", tmp.c_str());

599 600 601
  std::vector<std::string>::iterator it = incs.begin();
  for (; it != incs.end(); ++it) {
    tmp = *it;
602
    doEscape(tmp, "\\", "/");
603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619
    doEscape(tmp, " ", "\\ ");
    fprintf(out, "%s \\\n", tmp.c_str());
  }

  fprintf(out, "\n");
  fclose(out);
}


bool startsWith(const std::string& str, const std::string& what) {
  return str.compare(0, what.size(), what) == 0;
}

bool contains(const std::string& str, const std::string& what) {
  return str.find(what) != std::string::npos;
}

620 621
std::string replace(const std::string& str, const std::string& what,
                    const std::string& replacement) {
622 623 624 625 626 627
  size_t pos = str.find(what);
  if (pos == std::string::npos)
    return str;
  std::string replaced = str;
  return replaced.replace(pos, what.size(), replacement);
}
628 629 630



Peter Kuemmel's avatar
Peter Kuemmel committed
631 632 633 634 635 636
static int process( const std::string& srcfilename,
                    const std::string& dfile,
                    const std::string& objfile,
                    const std::string& prefix,
                    const std::string& cmd,
                    const std::string& dir = "",
637
                    bool quiet = false) {
638 639

  SubprocessSet subprocs;
640
  Subprocess* subproc = subprocs.Add(cmd, dir);
641

642 643 644 645 646 647 648 649
  if(!subproc)
    return 2;

  while ((subproc = subprocs.NextFinished()) == NULL) {
    subprocs.DoWork();
  }

  bool success = subproc->Finish() == ExitSuccess;
650
  int exit_code = subproc->ExitCode();
651

Peter Kuemmel's avatar
Peter Kuemmel committed
652
  std::string output = subproc->GetOutput();
653 654 655
  delete subproc;

  // process the include directives and output everything else
Peter Kuemmel's avatar
Peter Kuemmel committed
656 657 658
  std::stringstream ss(output);
  std::string line;
  std::vector<std::string> includes;
659
  bool isFirstLine = true; // cl prints always first the source filename
Peter Kuemmel's avatar
Peter Kuemmel committed
660
  while (std::getline(ss, line)) {
661
    if (startsWith(line, prefix)) {
Peter Kuemmel's avatar
Peter Kuemmel committed
662
      std::string inc = trimLeadingSpace(line.substr(prefix.size()).c_str());
663 664 665
      if (inc[inc.size() - 1] == '\r') // blech, stupid \r\n
        inc = inc.substr(0, inc.size() - 1);
      includes.push_back(inc);
666
    } else {
Peter Kuemmel's avatar
Peter Kuemmel committed
667
      if (!isFirstLine || !startsWith(line, srcfilename)) {
668
        if (!quiet) {
669 670
          fprintf(stdout, "%s\n", line.c_str());
        }
671 672 673 674 675 676
      } else {
        isFirstLine = false;
      }
    }
  }

677
  if (!success) {
678
    return exit_code;
679
  }
680 681 682 683 684 685

  // don't update .d until/unless we succeed compilation
  outputDepFile(dfile, objfile, includes);

  return 0;
}
686 687 688 689 690 691 692 693 694 695


int main() {

  // Use the Win32 api instead of argc/argv so we can avoid interpreting the
  // rest of command line after the .d and .obj. Custom parsing seemed
  // preferable to the ugliness you get into in trying to re-escape quotes for
  // subprocesses, so by avoiding argc/argv, the subprocess is called with
  // the same command line verbatim.

Peter Kuemmel's avatar
Peter Kuemmel committed
696
  std::string lang, srcfile, dfile, objfile, prefix, cl, binpath, rest;
697 698 699
  parseCommandLine(GetCommandLine(), lang, srcfile, dfile, objfile,
                                     prefix, cl, binpath, rest);

Peter Kuemmel's avatar
Peter Kuemmel committed
700
  // needed to suppress filename output of msvc tools
Peter Kuemmel's avatar
Peter Kuemmel committed
701
  std::string srcfilename;
Peter Kuemmel's avatar
Peter Kuemmel committed
702
  std::string::size_type pos = srcfile.rfind("\\");
Peter Kuemmel's avatar
Peter Kuemmel committed
703
  if (pos != std::string::npos) {
Peter Kuemmel's avatar
Peter Kuemmel committed
704 705
    srcfilename = srcfile.substr(pos + 1);
  }
706

707
  std::string nol = " /nologo ";
Peter Kuemmel's avatar
Peter Kuemmel committed
708 709 710
  std::string show = " /showIncludes ";
  if (lang == "C" || lang == "CXX") {
    return process(srcfilename, dfile, objfile, prefix,
711
                   binpath + nol + show + rest);
Peter Kuemmel's avatar
Peter Kuemmel committed
712
  } else if (lang == "RC") {
713 714
    // "misuse" cl.exe to get headers from .rc files

Peter Kuemmel's avatar
Peter Kuemmel committed
715
    std::string clrest = rest;
Peter Kuemmel's avatar
Peter Kuemmel committed
716 717 718 719 720 721
    // rc: /fo x.dir\x.rc.res  ->  cl: /out:x.dir\x.rc.res.dep.obj
    clrest = replace(clrest, "/fo", "/out:");
    clrest = replace(clrest, objfile, objfile + ".dep.obj ");
    // rc: src\x\x.rc  ->  cl: /Tc src\x\x.rc
    clrest = replace(clrest, srcfile, "/Tc " + srcfile);

722 723 724
    cl = "\"" + cl + "\" /P /DRC_INVOKED ";

    // call cl in object dir so the .i is generated there
Peter Kuemmel's avatar
Peter Kuemmel committed
725
    std::string objdir;
726
    std::string::size_type pos = objfile.rfind("\\");
Peter Kuemmel's avatar
Peter Kuemmel committed
727
    if (pos != std::string::npos) {
728 729
      objdir = objfile.substr(0, pos);
    }
Peter Kuemmel's avatar
Peter Kuemmel committed
730 731 732

    // extract dependencies with cl.exe
    process(srcfilename, dfile, objfile,
733
                  prefix, cl + nol + show + clrest, objdir, true);
734

Peter Kuemmel's avatar
Peter Kuemmel committed
735
    // compile rc file with rc.exe
736
    return process(srcfilename, "" , objfile, prefix, binpath + " " + rest);
737 738
  }

Peter Kuemmel's avatar
Peter Kuemmel committed
739 740
  usage("Invalid language specified.");
  return 1;
741
}