1// Copyright (c) 2012 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.
4
5#include <cstdio>
6#include <cstring>
7
8#include "base/command_line.h"
9#include "base/environment.h"
10#include "base/files/file_util.h"
11#include "base/logging.h"
12#include "base/memory/scoped_ptr.h"
13
14static const char kEvalCommand[] = "--eval-command";
15static const char kCommand[] = "--command";
16static const char kNaClIrt[] = "nacl-irt \"";
17static const char kPass[] = "PASS";
18static const char kAttach[] = "target remote :4014";
19
20int main(int argc, char** argv) {
21  scoped_ptr<base::Environment> env(base::Environment::Create());
22  std::string mock_nacl_gdb_file;
23  env->GetVar("MOCK_NACL_GDB", &mock_nacl_gdb_file);
24  CHECK_GE(argc, 5);
25  // First argument should be --eval-command.
26  CHECK_EQ(strcmp(argv[1], kEvalCommand), 0);
27  // Second argument should start with nacl-irt.
28  CHECK_GE(strlen(argv[2]), strlen(kNaClIrt));
29  CHECK_EQ(strncmp(argv[2], kNaClIrt, strlen(kNaClIrt)), 0);
30  char* irt_file_name = strdup(&argv[2][strlen(kNaClIrt)]);
31  CHECK_GE(strlen(irt_file_name), 1u);
32  // Remove closing quote.
33  irt_file_name[strlen(irt_file_name) - 1] = 0;
34  FILE* irt_file = fopen(irt_file_name, "r");
35  free(irt_file_name);
36  // nacl-irt parameter must be a file name.
37  PCHECK(irt_file);
38  fclose(irt_file);
39  CHECK_EQ(strcmp(argv[3], kEvalCommand), 0);
40  CHECK_EQ(strcmp(argv[4], kAttach), 0);
41  int i = 5;
42  // Skip additional --eval-command parameters.
43  while (i < argc) {
44    if (strcmp(argv[i], kEvalCommand) == 0) {
45      i += 2;
46      continue;
47    }
48    if (strcmp(argv[i], kCommand) == 0) {
49      // Command line shouldn't end with --command switch without value.
50      i += 2;
51      CHECK_LE(i, argc);
52      std::string nacl_gdb_script(argv[i - 1]);
53      base::WriteFile(base::FilePath::FromUTF8Unsafe(nacl_gdb_script),
54                      kPass, strlen(kPass));
55      continue;
56    }
57    // Unknown argument.
58    NOTREACHED() << "Invalid argument " << argv[i];
59  }
60  CHECK_EQ(i, argc);
61  base::WriteFile(base::FilePath::FromUTF8Unsafe(mock_nacl_gdb_file),
62                  kPass, strlen(kPass));
63  return 0;
64}
65