1 // Copyright (c) 2010 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/debug/debugger.h"
10 #include "base/basictypes.h"
11 #include "base/logging.h"
18 // Minimalist key reader.
19 // Note: Does not use the CRT.
20 bool RegReadString(HKEY root
, const wchar_t* subkey
,
21 const wchar_t* value_name
, wchar_t* buffer
, int* len
) {
23 DWORD res
= RegOpenKeyEx(root
, subkey
, 0, KEY_READ
, &key
);
24 if (ERROR_SUCCESS
!= res
|| key
== NULL
)
28 DWORD buffer_size
= *len
* sizeof(wchar_t);
29 // We don't support REG_EXPAND_SZ.
30 res
= RegQueryValueEx(key
, value_name
, NULL
, &type
,
31 reinterpret_cast<BYTE
*>(buffer
), &buffer_size
);
32 if (ERROR_SUCCESS
== res
&& buffer_size
!= 0 && type
== REG_SZ
) {
33 // Make sure the buffer is NULL terminated.
35 *len
= lstrlen(buffer
);
43 // Replaces each "%ld" in input per a value. Not efficient but it works.
44 // Note: Does not use the CRT.
45 bool StringReplace(const wchar_t* input
, int value
, wchar_t* output
,
47 memset(output
, 0, output_len
*sizeof(wchar_t));
48 int input_len
= lstrlen(input
);
50 for (int i
= 0; i
< input_len
; ++i
) {
51 int current_output_len
= lstrlen(output
);
53 if (input
[i
] == L
'%' && input
[i
+ 1] == L
'l' && input
[i
+ 2] == L
'd') {
54 // Make sure we have enough place left.
55 if ((current_output_len
+ 12) >= output_len
)
59 wsprintf(output
+current_output_len
, L
"%d", value
);
62 if (current_output_len
>= output_len
)
64 output
[current_output_len
] = input
[i
];
72 // Note: Does not use the CRT.
73 bool SpawnDebuggerOnProcess(unsigned process_id
) {
74 wchar_t reg_value
[1026];
75 int len
= arraysize(reg_value
);
76 if (RegReadString(HKEY_LOCAL_MACHINE
,
77 L
"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug",
78 L
"Debugger", reg_value
, &len
)) {
79 wchar_t command_line
[1026];
80 if (StringReplace(reg_value
, process_id
, command_line
,
81 arraysize(command_line
))) {
82 // We don't mind if the debugger is present because it will simply fail
83 // to attach to this process.
84 STARTUPINFO startup_info
= {0};
85 startup_info
.cb
= sizeof(startup_info
);
86 PROCESS_INFORMATION process_info
= {0};
88 if (CreateProcess(NULL
, command_line
, NULL
, NULL
, FALSE
, 0, NULL
, NULL
,
89 &startup_info
, &process_info
)) {
90 CloseHandle(process_info
.hThread
);
91 WaitForInputIdle(process_info
.hProcess
, 10000);
92 CloseHandle(process_info
.hProcess
);
100 bool BeingDebugged() {
101 return ::IsDebuggerPresent() != 0;
104 void BreakDebugger() {
105 if (IsDebugUISuppressed())