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.
5 #include "base/process_util.h"
15 #include "base/bind.h"
16 #include "base/bind_helpers.h"
17 #include "base/command_line.h"
18 #include "base/debug/stack_trace.h"
19 #include "base/logging.h"
20 #include "base/memory/scoped_ptr.h"
21 #include "base/message_loop.h"
22 #include "base/metrics/histogram.h"
23 #include "base/sys_info.h"
24 #include "base/win/object_watcher.h"
25 #include "base/win/scoped_handle.h"
26 #include "base/win/scoped_process_information.h"
27 #include "base/win/windows_version.h"
29 // userenv.dll is required for CreateEnvironmentBlock().
30 #pragma comment(lib, "userenv.lib")
36 // System pagesize. This value remains constant on x86/64 architectures.
37 const int PAGESIZE_KB
= 4;
39 // Exit codes with special meanings on Windows.
40 const DWORD kNormalTerminationExitCode
= 0;
41 const DWORD kDebuggerInactiveExitCode
= 0xC0000354;
42 const DWORD kKeyboardInterruptExitCode
= 0xC000013A;
43 const DWORD kDebuggerTerminatedExitCode
= 0x40010004;
45 // Maximum amount of time (in milliseconds) to wait for the process to exit.
46 static const int kWaitInterval
= 2000;
48 // This exit code is used by the Windows task manager when it kills a
49 // process. It's value is obviously not that unique, and it's
50 // surprising to me that the task manager uses this value, but it
51 // seems to be common practice on Windows to test for it as an
52 // indication that the task manager has killed something if the
54 const DWORD kProcessKilledExitCode
= 1;
56 // HeapSetInformation function pointer.
57 typedef BOOL (WINAPI
* HeapSetFn
)(HANDLE
, HEAP_INFORMATION_CLASS
, PVOID
, SIZE_T
);
59 // Previous unhandled filter. Will be called if not NULL when we intercept an
60 // exception. Only used in unit tests.
61 LPTOP_LEVEL_EXCEPTION_FILTER g_previous_filter
= NULL
;
63 // Prints the exception call stack.
64 // This is the unit tests exception filter.
65 long WINAPI
StackDumpExceptionFilter(EXCEPTION_POINTERS
* info
) {
66 debug::StackTrace(info
).PrintBacktrace();
67 if (g_previous_filter
)
68 return g_previous_filter(info
);
69 return EXCEPTION_CONTINUE_SEARCH
;
73 // Kill the process. This is important for security, since WebKit doesn't
74 // NULL-check many memory allocations. If a malloc fails, returns NULL, and
75 // the buffer is then used, it provides a handy mapping of memory starting at
76 // address 0 for an attacker to utilize.
81 class TimerExpiredTask
: public win::ObjectWatcher::Delegate
{
83 explicit TimerExpiredTask(ProcessHandle process
);
88 // MessageLoop::Watcher -----------------------------------------------------
89 virtual void OnObjectSignaled(HANDLE object
);
94 // The process that we are watching.
95 ProcessHandle process_
;
97 win::ObjectWatcher watcher_
;
99 DISALLOW_COPY_AND_ASSIGN(TimerExpiredTask
);
102 TimerExpiredTask::TimerExpiredTask(ProcessHandle process
) : process_(process
) {
103 watcher_
.StartWatching(process_
, this);
106 TimerExpiredTask::~TimerExpiredTask() {
108 DCHECK(!process_
) << "Make sure to close the handle.";
111 void TimerExpiredTask::TimedOut() {
116 void TimerExpiredTask::OnObjectSignaled(HANDLE object
) {
117 CloseHandle(process_
);
121 void TimerExpiredTask::KillProcess() {
122 // Stop watching the process handle since we're killing it.
123 watcher_
.StopWatching();
125 // OK, time to get frisky. We don't actually care when the process
126 // terminates. We just care that it eventually terminates, and that's what
127 // TerminateProcess should do for us. Don't check for the result code since
128 // it fails quite often. This should be investigated eventually.
129 base::KillProcess(process_
, kProcessKilledExitCode
, false);
131 // Now, just cleanup as if the process exited normally.
132 OnObjectSignaled(process_
);
137 void RouteStdioToConsole() {
138 if (!AttachConsole(ATTACH_PARENT_PROCESS
)) {
139 unsigned int result
= GetLastError();
140 // Was probably already attached.
141 if (result
== ERROR_ACCESS_DENIED
)
143 // Don't bother creating a new console for each child process if the
144 // parent process is invalid (eg: crashed).
145 if (result
== ERROR_GEN_FAILURE
)
147 // Make a new console if attaching to parent fails with any other error.
148 // It should be ERROR_INVALID_HANDLE at this point, which means the browser
149 // was likely not started from a console.
153 if (freopen("CONOUT$", "w", stdout
))
154 setvbuf(stdout
, NULL
, _IONBF
, 0);
155 if (freopen("CONOUT$", "w", stderr
))
156 setvbuf(stderr
, NULL
, _IONBF
, 0);
158 // Fix all cout, wcout, cin, wcin, cerr, wcerr, clog and wclog.
159 std::ios::sync_with_stdio();
162 ProcessId
GetCurrentProcId() {
163 return ::GetCurrentProcessId();
166 ProcessHandle
GetCurrentProcessHandle() {
167 return ::GetCurrentProcess();
170 HMODULE
GetModuleFromAddress(void* address
) {
171 HMODULE instance
= NULL
;
172 if (!::GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
|
173 GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT
,
174 static_cast<char*>(address
),
181 bool OpenProcessHandle(ProcessId pid
, ProcessHandle
* handle
) {
182 // We try to limit privileges granted to the handle. If you need this
183 // for test code, consider using OpenPrivilegedProcessHandle instead of
184 // adding more privileges here.
185 ProcessHandle result
= OpenProcess(PROCESS_DUP_HANDLE
| PROCESS_TERMINATE
,
195 bool OpenPrivilegedProcessHandle(ProcessId pid
, ProcessHandle
* handle
) {
196 ProcessHandle result
= OpenProcess(PROCESS_DUP_HANDLE
|
198 PROCESS_QUERY_INFORMATION
|
210 bool OpenProcessHandleWithAccess(ProcessId pid
,
212 ProcessHandle
* handle
) {
213 ProcessHandle result
= OpenProcess(access_flags
, FALSE
, pid
);
222 void CloseProcessHandle(ProcessHandle process
) {
223 CloseHandle(process
);
226 ProcessId
GetProcId(ProcessHandle process
) {
227 // Get a handle to |process| that has PROCESS_QUERY_INFORMATION rights.
228 HANDLE current_process
= GetCurrentProcess();
229 HANDLE process_with_query_rights
;
230 if (DuplicateHandle(current_process
, process
, current_process
,
231 &process_with_query_rights
, PROCESS_QUERY_INFORMATION
,
233 DWORD id
= GetProcessId(process_with_query_rights
);
234 CloseHandle(process_with_query_rights
);
243 bool GetProcessIntegrityLevel(ProcessHandle process
, IntegrityLevel
*level
) {
247 if (win::GetVersion() < base::win::VERSION_VISTA
)
250 HANDLE process_token
;
251 if (!OpenProcessToken(process
, TOKEN_QUERY
| TOKEN_QUERY_SOURCE
,
255 win::ScopedHandle
scoped_process_token(process_token
);
257 DWORD token_info_length
= 0;
258 if (GetTokenInformation(process_token
, TokenIntegrityLevel
, NULL
, 0,
259 &token_info_length
) ||
260 GetLastError() != ERROR_INSUFFICIENT_BUFFER
)
263 scoped_array
<char> token_label_bytes(new char[token_info_length
]);
264 if (!token_label_bytes
.get())
267 TOKEN_MANDATORY_LABEL
* token_label
=
268 reinterpret_cast<TOKEN_MANDATORY_LABEL
*>(token_label_bytes
.get());
272 if (!GetTokenInformation(process_token
, TokenIntegrityLevel
, token_label
,
273 token_info_length
, &token_info_length
))
276 DWORD integrity_level
= *GetSidSubAuthority(token_label
->Label
.Sid
,
277 (DWORD
)(UCHAR
)(*GetSidSubAuthorityCount(token_label
->Label
.Sid
)-1));
279 if (integrity_level
< SECURITY_MANDATORY_MEDIUM_RID
) {
280 *level
= LOW_INTEGRITY
;
281 } else if (integrity_level
>= SECURITY_MANDATORY_MEDIUM_RID
&&
282 integrity_level
< SECURITY_MANDATORY_HIGH_RID
) {
283 *level
= MEDIUM_INTEGRITY
;
284 } else if (integrity_level
>= SECURITY_MANDATORY_HIGH_RID
) {
285 *level
= HIGH_INTEGRITY
;
294 bool LaunchProcess(const string16
& cmdline
,
295 const LaunchOptions
& options
,
296 ProcessHandle
* process_handle
) {
297 STARTUPINFO startup_info
= {};
298 startup_info
.cb
= sizeof(startup_info
);
299 if (options
.empty_desktop_name
)
300 startup_info
.lpDesktop
= L
"";
301 startup_info
.dwFlags
= STARTF_USESHOWWINDOW
;
302 startup_info
.wShowWindow
= options
.start_hidden
? SW_HIDE
: SW_SHOW
;
306 if (options
.job_handle
) {
307 flags
|= CREATE_SUSPENDED
;
309 // If this code is run under a debugger, the launched process is
310 // automatically associated with a job object created by the debugger.
311 // The CREATE_BREAKAWAY_FROM_JOB flag is used to prevent this.
312 flags
|= CREATE_BREAKAWAY_FROM_JOB
;
315 base::win::ScopedProcessInformation process_info
;
317 if (options
.as_user
) {
318 flags
|= CREATE_UNICODE_ENVIRONMENT
;
319 void* enviroment_block
= NULL
;
321 if (!CreateEnvironmentBlock(&enviroment_block
, options
.as_user
, FALSE
))
325 CreateProcessAsUser(options
.as_user
, NULL
,
326 const_cast<wchar_t*>(cmdline
.c_str()),
327 NULL
, NULL
, options
.inherit_handles
, flags
,
328 enviroment_block
, NULL
, &startup_info
,
329 process_info
.Receive());
330 DestroyEnvironmentBlock(enviroment_block
);
334 if (!CreateProcess(NULL
,
335 const_cast<wchar_t*>(cmdline
.c_str()), NULL
, NULL
,
336 options
.inherit_handles
, flags
, NULL
, NULL
,
337 &startup_info
, process_info
.Receive())) {
342 if (options
.job_handle
) {
343 if (0 == AssignProcessToJobObject(options
.job_handle
,
344 process_info
.process_handle())) {
345 DLOG(ERROR
) << "Could not AssignProcessToObject.";
346 KillProcess(process_info
.process_handle(), kProcessKilledExitCode
, true);
350 ResumeThread(process_info
.thread_handle());
354 WaitForSingleObject(process_info
.process_handle(), INFINITE
);
356 // If the caller wants the process handle, we won't close it.
358 *process_handle
= process_info
.TakeProcessHandle();
363 bool LaunchProcess(const CommandLine
& cmdline
,
364 const LaunchOptions
& options
,
365 ProcessHandle
* process_handle
) {
366 return LaunchProcess(cmdline
.GetCommandLineString(), options
, process_handle
);
369 bool SetJobObjectAsKillOnJobClose(HANDLE job_object
) {
370 JOBOBJECT_EXTENDED_LIMIT_INFORMATION limit_info
= {0};
371 limit_info
.BasicLimitInformation
.LimitFlags
=
372 JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
;
373 return 0 != SetInformationJobObject(
375 JobObjectExtendedLimitInformation
,
380 // Attempts to kill the process identified by the given process
381 // entry structure, giving it the specified exit code.
382 // Returns true if this is successful, false otherwise.
383 bool KillProcessById(ProcessId process_id
, int exit_code
, bool wait
) {
384 HANDLE process
= OpenProcess(PROCESS_TERMINATE
| SYNCHRONIZE
,
385 FALSE
, // Don't inherit handle
388 DLOG(ERROR
) << "Unable to open process " << process_id
<< " : "
392 bool ret
= KillProcess(process
, exit_code
, wait
);
393 CloseHandle(process
);
397 bool GetAppOutput(const CommandLine
& cl
, std::string
* output
) {
398 HANDLE out_read
= NULL
;
399 HANDLE out_write
= NULL
;
401 SECURITY_ATTRIBUTES sa_attr
;
402 // Set the bInheritHandle flag so pipe handles are inherited.
403 sa_attr
.nLength
= sizeof(SECURITY_ATTRIBUTES
);
404 sa_attr
.bInheritHandle
= TRUE
;
405 sa_attr
.lpSecurityDescriptor
= NULL
;
407 // Create the pipe for the child process's STDOUT.
408 if (!CreatePipe(&out_read
, &out_write
, &sa_attr
, 0)) {
409 NOTREACHED() << "Failed to create pipe";
413 // Ensure we don't leak the handles.
414 win::ScopedHandle
scoped_out_read(out_read
);
415 win::ScopedHandle
scoped_out_write(out_write
);
417 // Ensure the read handle to the pipe for STDOUT is not inherited.
418 if (!SetHandleInformation(out_read
, HANDLE_FLAG_INHERIT
, 0)) {
419 NOTREACHED() << "Failed to disabled pipe inheritance";
423 FilePath::StringType
writable_command_line_string(cl
.GetCommandLineString());
425 base::win::ScopedProcessInformation proc_info
;
426 STARTUPINFO start_info
= { 0 };
428 start_info
.cb
= sizeof(STARTUPINFO
);
429 start_info
.hStdOutput
= out_write
;
430 // Keep the normal stdin and stderr.
431 start_info
.hStdInput
= GetStdHandle(STD_INPUT_HANDLE
);
432 start_info
.hStdError
= GetStdHandle(STD_ERROR_HANDLE
);
433 start_info
.dwFlags
|= STARTF_USESTDHANDLES
;
435 // Create the child process.
436 if (!CreateProcess(NULL
,
437 &writable_command_line_string
[0],
439 TRUE
, // Handles are inherited.
440 0, NULL
, NULL
, &start_info
, proc_info
.Receive())) {
441 NOTREACHED() << "Failed to start process";
445 // Close our writing end of pipe now. Otherwise later read would not be able
446 // to detect end of child's output.
447 scoped_out_write
.Close();
449 // Read output from the child process's pipe for STDOUT
450 const int kBufferSize
= 1024;
451 char buffer
[kBufferSize
];
454 DWORD bytes_read
= 0;
455 BOOL success
= ReadFile(out_read
, buffer
, kBufferSize
, &bytes_read
, NULL
);
456 if (!success
|| bytes_read
== 0)
458 output
->append(buffer
, bytes_read
);
461 // Let's wait for the process to finish.
462 WaitForSingleObject(proc_info
.process_handle(), INFINITE
);
467 bool KillProcess(ProcessHandle process
, int exit_code
, bool wait
) {
468 bool result
= (TerminateProcess(process
, exit_code
) != FALSE
);
469 if (result
&& wait
) {
470 // The process may not end immediately due to pending I/O
471 if (WAIT_OBJECT_0
!= WaitForSingleObject(process
, 60 * 1000))
472 DLOG(ERROR
) << "Error waiting for process exit: " << GetLastError();
473 } else if (!result
) {
474 DLOG(ERROR
) << "Unable to terminate process: " << GetLastError();
479 TerminationStatus
GetTerminationStatus(ProcessHandle handle
, int* exit_code
) {
480 DWORD tmp_exit_code
= 0;
482 if (!::GetExitCodeProcess(handle
, &tmp_exit_code
)) {
485 // This really is a random number. We haven't received any
486 // information about the exit code, presumably because this
487 // process doesn't have permission to get the exit code, or
488 // because of some other cause for GetExitCodeProcess to fail
489 // (MSDN docs don't give the possible failure error codes for
490 // this function, so it could be anything). But we don't want
491 // to leave exit_code uninitialized, since that could cause
492 // random interpretations of the exit code. So we assume it
493 // terminated "normally" in this case.
494 *exit_code
= kNormalTerminationExitCode
;
496 // Assume the child has exited normally if we can't get the exit
498 return TERMINATION_STATUS_NORMAL_TERMINATION
;
500 if (tmp_exit_code
== STILL_ACTIVE
) {
501 DWORD wait_result
= WaitForSingleObject(handle
, 0);
502 if (wait_result
== WAIT_TIMEOUT
) {
504 *exit_code
= wait_result
;
505 return TERMINATION_STATUS_STILL_RUNNING
;
508 DCHECK_EQ(WAIT_OBJECT_0
, wait_result
);
510 // Strange, the process used 0x103 (STILL_ACTIVE) as exit code.
513 return TERMINATION_STATUS_ABNORMAL_TERMINATION
;
517 *exit_code
= tmp_exit_code
;
519 switch (tmp_exit_code
) {
520 case kNormalTerminationExitCode
:
521 return TERMINATION_STATUS_NORMAL_TERMINATION
;
522 case kDebuggerInactiveExitCode
: // STATUS_DEBUGGER_INACTIVE.
523 case kKeyboardInterruptExitCode
: // Control-C/end session.
524 case kDebuggerTerminatedExitCode
: // Debugger terminated process.
525 case kProcessKilledExitCode
: // Task manager kill.
526 return TERMINATION_STATUS_PROCESS_WAS_KILLED
;
528 // All other exit codes indicate crashes.
529 return TERMINATION_STATUS_PROCESS_CRASHED
;
533 bool WaitForExitCode(ProcessHandle handle
, int* exit_code
) {
534 bool success
= WaitForExitCodeWithTimeout(
535 handle
, exit_code
, base::TimeDelta::FromMilliseconds(INFINITE
));
536 CloseProcessHandle(handle
);
540 bool WaitForExitCodeWithTimeout(ProcessHandle handle
, int* exit_code
,
541 base::TimeDelta timeout
) {
542 if (::WaitForSingleObject(handle
, timeout
.InMilliseconds()) != WAIT_OBJECT_0
)
544 DWORD temp_code
; // Don't clobber out-parameters in case of failure.
545 if (!::GetExitCodeProcess(handle
, &temp_code
))
548 *exit_code
= temp_code
;
552 ProcessIterator::ProcessIterator(const ProcessFilter
* filter
)
553 : started_iteration_(false),
555 snapshot_
= CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS
, 0);
558 ProcessIterator::~ProcessIterator() {
559 CloseHandle(snapshot_
);
562 bool ProcessIterator::CheckForNextProcess() {
563 InitProcessEntry(&entry_
);
565 if (!started_iteration_
) {
566 started_iteration_
= true;
567 return !!Process32First(snapshot_
, &entry_
);
570 return !!Process32Next(snapshot_
, &entry_
);
573 void ProcessIterator::InitProcessEntry(ProcessEntry
* entry
) {
574 memset(entry
, 0, sizeof(*entry
));
575 entry
->dwSize
= sizeof(*entry
);
578 bool NamedProcessIterator::IncludeEntry() {
580 return _wcsicmp(executable_name_
.c_str(), entry().exe_file()) == 0 &&
581 ProcessIterator::IncludeEntry();
584 bool WaitForProcessesToExit(const FilePath::StringType
& executable_name
,
585 base::TimeDelta wait
,
586 const ProcessFilter
* filter
) {
587 const ProcessEntry
* entry
;
589 DWORD start_time
= GetTickCount();
591 NamedProcessIterator
iter(executable_name
, filter
);
592 while ((entry
= iter
.NextProcessEntry())) {
593 DWORD remaining_wait
= std::max
<int64
>(
594 0, wait
.InMilliseconds() - (GetTickCount() - start_time
));
595 HANDLE process
= OpenProcess(SYNCHRONIZE
,
597 entry
->th32ProcessID
);
598 DWORD wait_result
= WaitForSingleObject(process
, remaining_wait
);
599 CloseHandle(process
);
600 result
= result
&& (wait_result
== WAIT_OBJECT_0
);
606 bool WaitForSingleProcess(ProcessHandle handle
, base::TimeDelta wait
) {
608 if (!WaitForExitCodeWithTimeout(handle
, &exit_code
, wait
))
610 return exit_code
== 0;
613 bool CleanupProcesses(const FilePath::StringType
& executable_name
,
614 base::TimeDelta wait
,
616 const ProcessFilter
* filter
) {
617 bool exited_cleanly
= WaitForProcessesToExit(executable_name
, wait
, filter
);
619 KillProcesses(executable_name
, exit_code
, filter
);
620 return exited_cleanly
;
623 void EnsureProcessTerminated(ProcessHandle process
) {
624 DCHECK(process
!= GetCurrentProcess());
626 // If already signaled, then we are done!
627 if (WaitForSingleObject(process
, 0) == WAIT_OBJECT_0
) {
628 CloseHandle(process
);
632 MessageLoop::current()->PostDelayedTask(
634 base::Bind(&TimerExpiredTask::TimedOut
,
635 base::Owned(new TimerExpiredTask(process
))),
636 base::TimeDelta::FromMilliseconds(kWaitInterval
));
639 ///////////////////////////////////////////////////////////////////////////////
642 ProcessMetrics::ProcessMetrics(ProcessHandle process
)
644 processor_count_(base::SysInfo::NumberOfProcessors()),
646 last_system_time_(0) {
650 ProcessMetrics
* ProcessMetrics::CreateProcessMetrics(ProcessHandle process
) {
651 return new ProcessMetrics(process
);
654 ProcessMetrics::~ProcessMetrics() { }
656 size_t ProcessMetrics::GetPagefileUsage() const {
657 PROCESS_MEMORY_COUNTERS pmc
;
658 if (GetProcessMemoryInfo(process_
, &pmc
, sizeof(pmc
))) {
659 return pmc
.PagefileUsage
;
664 // Returns the peak space allocated for the pagefile, in bytes.
665 size_t ProcessMetrics::GetPeakPagefileUsage() const {
666 PROCESS_MEMORY_COUNTERS pmc
;
667 if (GetProcessMemoryInfo(process_
, &pmc
, sizeof(pmc
))) {
668 return pmc
.PeakPagefileUsage
;
673 // Returns the current working set size, in bytes.
674 size_t ProcessMetrics::GetWorkingSetSize() const {
675 PROCESS_MEMORY_COUNTERS pmc
;
676 if (GetProcessMemoryInfo(process_
, &pmc
, sizeof(pmc
))) {
677 return pmc
.WorkingSetSize
;
682 // Returns the peak working set size, in bytes.
683 size_t ProcessMetrics::GetPeakWorkingSetSize() const {
684 PROCESS_MEMORY_COUNTERS pmc
;
685 if (GetProcessMemoryInfo(process_
, &pmc
, sizeof(pmc
))) {
686 return pmc
.PeakWorkingSetSize
;
691 bool ProcessMetrics::GetMemoryBytes(size_t* private_bytes
,
692 size_t* shared_bytes
) {
693 // PROCESS_MEMORY_COUNTERS_EX is not supported until XP SP2.
694 // GetProcessMemoryInfo() will simply fail on prior OS. So the requested
695 // information is simply not available. Hence, we will return 0 on unsupported
696 // OSes. Unlike most Win32 API, we don't need to initialize the "cb" member.
697 PROCESS_MEMORY_COUNTERS_EX pmcx
;
699 GetProcessMemoryInfo(process_
,
700 reinterpret_cast<PROCESS_MEMORY_COUNTERS
*>(&pmcx
),
702 *private_bytes
= pmcx
.PrivateUsage
;
706 WorkingSetKBytes ws_usage
;
707 if (!GetWorkingSetKBytes(&ws_usage
))
710 *shared_bytes
= ws_usage
.shared
* 1024;
716 void ProcessMetrics::GetCommittedKBytes(CommittedKBytes
* usage
) const {
717 MEMORY_BASIC_INFORMATION mbi
= {0};
718 size_t committed_private
= 0;
719 size_t committed_mapped
= 0;
720 size_t committed_image
= 0;
721 void* base_address
= NULL
;
722 while (VirtualQueryEx(process_
, base_address
, &mbi
, sizeof(mbi
)) ==
724 if (mbi
.State
== MEM_COMMIT
) {
725 if (mbi
.Type
== MEM_PRIVATE
) {
726 committed_private
+= mbi
.RegionSize
;
727 } else if (mbi
.Type
== MEM_MAPPED
) {
728 committed_mapped
+= mbi
.RegionSize
;
729 } else if (mbi
.Type
== MEM_IMAGE
) {
730 committed_image
+= mbi
.RegionSize
;
735 void* new_base
= (static_cast<BYTE
*>(mbi
.BaseAddress
)) + mbi
.RegionSize
;
736 // Avoid infinite loop by weird MEMORY_BASIC_INFORMATION.
737 // If we query 64bit processes in a 32bit process, VirtualQueryEx()
738 // returns such data.
739 if (new_base
<= base_address
) {
745 base_address
= new_base
;
747 usage
->image
= committed_image
/ 1024;
748 usage
->mapped
= committed_mapped
/ 1024;
749 usage
->priv
= committed_private
/ 1024;
752 bool ProcessMetrics::GetWorkingSetKBytes(WorkingSetKBytes
* ws_usage
) const {
753 size_t ws_private
= 0;
754 size_t ws_shareable
= 0;
755 size_t ws_shared
= 0;
758 memset(ws_usage
, 0, sizeof(*ws_usage
));
760 DWORD number_of_entries
= 4096; // Just a guess.
761 PSAPI_WORKING_SET_INFORMATION
* buffer
= NULL
;
764 DWORD buffer_size
= sizeof(PSAPI_WORKING_SET_INFORMATION
) +
765 (number_of_entries
* sizeof(PSAPI_WORKING_SET_BLOCK
));
767 // if we can't expand the buffer, don't leak the previous
768 // contents or pass a NULL pointer to QueryWorkingSet
769 PSAPI_WORKING_SET_INFORMATION
* new_buffer
=
770 reinterpret_cast<PSAPI_WORKING_SET_INFORMATION
*>(
771 realloc(buffer
, buffer_size
));
778 // Call the function once to get number of items
779 if (QueryWorkingSet(process_
, buffer
, buffer_size
))
782 if (GetLastError() != ERROR_BAD_LENGTH
) {
787 number_of_entries
= static_cast<DWORD
>(buffer
->NumberOfEntries
);
789 // Maybe some entries are being added right now. Increase the buffer to
790 // take that into account.
791 number_of_entries
= static_cast<DWORD
>(number_of_entries
* 1.25);
793 if (--retries
== 0) {
794 free(buffer
); // If we're looping, eventually fail.
799 // On windows 2000 the function returns 1 even when the buffer is too small.
800 // The number of entries that we are going to parse is the minimum between the
801 // size we allocated and the real number of entries.
803 std::min(number_of_entries
, static_cast<DWORD
>(buffer
->NumberOfEntries
));
804 for (unsigned int i
= 0; i
< number_of_entries
; i
++) {
805 if (buffer
->WorkingSetInfo
[i
].Shared
) {
807 if (buffer
->WorkingSetInfo
[i
].ShareCount
> 1)
814 ws_usage
->priv
= ws_private
* PAGESIZE_KB
;
815 ws_usage
->shareable
= ws_shareable
* PAGESIZE_KB
;
816 ws_usage
->shared
= ws_shared
* PAGESIZE_KB
;
821 static uint64
FileTimeToUTC(const FILETIME
& ftime
) {
823 li
.LowPart
= ftime
.dwLowDateTime
;
824 li
.HighPart
= ftime
.dwHighDateTime
;
828 double ProcessMetrics::GetCPUUsage() {
830 FILETIME creation_time
;
832 FILETIME kernel_time
;
835 GetSystemTimeAsFileTime(&now
);
837 if (!GetProcessTimes(process_
, &creation_time
, &exit_time
,
838 &kernel_time
, &user_time
)) {
839 // We don't assert here because in some cases (such as in the Task Manager)
840 // we may call this function on a process that has just exited but we have
841 // not yet received the notification.
844 int64 system_time
= (FileTimeToUTC(kernel_time
) + FileTimeToUTC(user_time
)) /
846 int64 time
= FileTimeToUTC(now
);
848 if ((last_system_time_
== 0) || (last_time_
== 0)) {
849 // First call, just set the last values.
850 last_system_time_
= system_time
;
855 int64 system_time_delta
= system_time
- last_system_time_
;
856 int64 time_delta
= time
- last_time_
;
857 DCHECK_NE(0U, time_delta
);
861 // We add time_delta / 2 so the result is rounded.
862 int cpu
= static_cast<int>((system_time_delta
* 100 + time_delta
/ 2) /
865 last_system_time_
= system_time
;
871 bool ProcessMetrics::GetIOCounters(IoCounters
* io_counters
) const {
872 return GetProcessIoCounters(process_
, io_counters
) != FALSE
;
875 bool ProcessMetrics::CalculateFreeMemory(FreeMBytes
* free
) const {
876 const SIZE_T kTopAddress
= 0x7F000000;
877 const SIZE_T kMegabyte
= 1024 * 1024;
878 SIZE_T accumulated
= 0;
880 MEMORY_BASIC_INFORMATION largest
= {0};
882 while (scan
< kTopAddress
) {
883 MEMORY_BASIC_INFORMATION info
;
884 if (!::VirtualQueryEx(process_
, reinterpret_cast<void*>(scan
),
885 &info
, sizeof(info
)))
887 if (info
.State
== MEM_FREE
) {
888 accumulated
+= info
.RegionSize
;
889 UINT_PTR end
= scan
+ info
.RegionSize
;
890 if (info
.RegionSize
> largest
.RegionSize
)
893 scan
+= info
.RegionSize
;
895 free
->largest
= largest
.RegionSize
/ kMegabyte
;
896 free
->largest_ptr
= largest
.BaseAddress
;
897 free
->total
= accumulated
/ kMegabyte
;
901 bool EnableLowFragmentationHeap() {
902 HMODULE kernel32
= GetModuleHandle(L
"kernel32.dll");
903 HeapSetFn heap_set
= reinterpret_cast<HeapSetFn
>(GetProcAddress(
905 "HeapSetInformation"));
907 // On Windows 2000, the function is not exported. This is not a reason to
912 unsigned number_heaps
= GetProcessHeaps(0, NULL
);
916 // Gives us some extra space in the array in case a thread is creating heaps
917 // at the same time we're querying them.
918 static const int MARGIN
= 8;
919 scoped_array
<HANDLE
> heaps(new HANDLE
[number_heaps
+ MARGIN
]);
920 number_heaps
= GetProcessHeaps(number_heaps
+ MARGIN
, heaps
.get());
924 for (unsigned i
= 0; i
< number_heaps
; ++i
) {
926 // Don't bother with the result code. It may fails on heaps that have the
927 // HEAP_NO_SERIALIZE flag. This is expected and not a problem at all.
929 HeapCompatibilityInformation
,
936 void EnableTerminationOnHeapCorruption() {
937 // Ignore the result code. Supported on XP SP3 and Vista.
938 HeapSetInformation(NULL
, HeapEnableTerminationOnCorruption
, NULL
, 0);
941 void EnableTerminationOnOutOfMemory() {
942 std::set_new_handler(&OnNoMemory
);
945 bool EnableInProcessStackDumping() {
946 // Add stack dumping support on exception on windows. Similar to OS_POSIX
947 // signal() handling in process_util_posix.cc.
948 g_previous_filter
= SetUnhandledExceptionFilter(&StackDumpExceptionFilter
);
949 RouteStdioToConsole();
953 void RaiseProcessToHighPriority() {
954 SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS
);
957 // GetPerformanceInfo is not available on WIN2K. So we'll
958 // load it on-the-fly.
959 const wchar_t kPsapiDllName
[] = L
"psapi.dll";
960 typedef BOOL (WINAPI
*GetPerformanceInfoFunction
) (
961 PPERFORMANCE_INFORMATION pPerformanceInformation
,
964 // Beware of races if called concurrently from multiple threads.
965 static BOOL
InternalGetPerformanceInfo(
966 PPERFORMANCE_INFORMATION pPerformanceInformation
, DWORD cb
) {
967 static GetPerformanceInfoFunction GetPerformanceInfo_func
= NULL
;
968 if (!GetPerformanceInfo_func
) {
969 HMODULE psapi_dll
= ::GetModuleHandle(kPsapiDllName
);
971 GetPerformanceInfo_func
= reinterpret_cast<GetPerformanceInfoFunction
>(
972 GetProcAddress(psapi_dll
, "GetPerformanceInfo"));
974 if (!GetPerformanceInfo_func
) {
975 // The function could be loaded!
976 memset(pPerformanceInformation
, 0, cb
);
980 return GetPerformanceInfo_func(pPerformanceInformation
, cb
);
983 size_t GetSystemCommitCharge() {
984 // Get the System Page Size.
985 SYSTEM_INFO system_info
;
986 GetSystemInfo(&system_info
);
988 PERFORMANCE_INFORMATION info
;
989 if (!InternalGetPerformanceInfo(&info
, sizeof(info
))) {
990 DLOG(ERROR
) << "Failed to fetch internal performance info.";
993 return (info
.CommitTotal
* system_info
.dwPageSize
) / 1024;