• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2011 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 "base/debug/debug_on_start_win.h"
6 
7 #include <windows.h>
8 
9 #include "base/base_switches.h"
10 #include "base/basictypes.h"
11 #include "base/debug/debugger.h"
12 
13 namespace base {
14 namespace debug {
15 
16 // Minimalist implementation to try to find a command line argument. We can use
17 // kernel32 exported functions but not the CRT functions because we're too early
18 // in the process startup.
19 // The code is not that bright and will find things like ---argument or
20 // /-/argument.
21 // Note: command_line is non-destructively modified.
FindArgument(wchar_t * command_line,const char * argument_c)22 bool DebugOnStart::FindArgument(wchar_t* command_line, const char* argument_c) {
23   wchar_t argument[50] = {};
24   for (int i = 0; argument_c[i]; ++i)
25     argument[i] = argument_c[i];
26 
27   int argument_len = lstrlen(argument);
28   int command_line_len = lstrlen(command_line);
29   while (command_line_len > argument_len) {
30     wchar_t first_char = command_line[0];
31     wchar_t last_char = command_line[argument_len+1];
32     // Try to find an argument.
33     if ((first_char == L'-' || first_char == L'/') &&
34         (last_char == L' ' || last_char == 0 || last_char == L'=')) {
35       command_line[argument_len+1] = 0;
36       // Skip the - or /
37       if (lstrcmpi(command_line+1, argument) == 0) {
38         // Found it.
39         command_line[argument_len+1] = last_char;
40         return true;
41       }
42       // Fix back.
43       command_line[argument_len+1] = last_char;
44     }
45     // Continue searching.
46     ++command_line;
47     --command_line_len;
48   }
49   return false;
50 }
51 
52 // static
Init()53 int __cdecl DebugOnStart::Init() {
54   // Try to find the argument.
55   if (FindArgument(GetCommandLine(), switches::kDebugOnStart)) {
56     // We can do 2 things here:
57     // - Ask for a debugger to attach to us. This involve reading the registry
58     //   key and creating the process.
59     // - Do a int3.
60 
61     // It will fails if we run in a sandbox. That is expected.
62     base::debug::SpawnDebuggerOnProcess(GetCurrentProcessId());
63 
64     // Wait for a debugger to come take us.
65     base::debug::WaitForDebugger(60, false);
66   } else if (FindArgument(GetCommandLine(), switches::kWaitForDebugger)) {
67     // Wait for a debugger to come take us.
68     base::debug::WaitForDebugger(60, true);
69   }
70   return 0;
71 }
72 
73 }  // namespace debug
74 }  // namespace base
75