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
);
60 // Kill the process. This is important for security, since WebKit doesn't
61 // NULL-check many memory allocations. If a malloc fails, returns NULL, and
62 // the buffer is then used, it provides a handy mapping of memory starting at
63 // address 0 for an attacker to utilize.
68 class TimerExpiredTask
: public win::ObjectWatcher::Delegate
{
70 explicit TimerExpiredTask(ProcessHandle process
);
75 // MessageLoop::Watcher -----------------------------------------------------
76 virtual void OnObjectSignaled(HANDLE object
);
81 // The process that we are watching.
82 ProcessHandle process_
;
84 win::ObjectWatcher watcher_
;
86 DISALLOW_COPY_AND_ASSIGN(TimerExpiredTask
);
89 TimerExpiredTask::TimerExpiredTask(ProcessHandle process
) : process_(process
) {
90 watcher_
.StartWatching(process_
, this);
93 TimerExpiredTask::~TimerExpiredTask() {
95 DCHECK(!process_
) << "Make sure to close the handle.";
98 void TimerExpiredTask::TimedOut() {
103 void TimerExpiredTask::OnObjectSignaled(HANDLE object
) {
104 CloseHandle(process_
);
108 void TimerExpiredTask::KillProcess() {
109 // Stop watching the process handle since we're killing it.
110 watcher_
.StopWatching();
112 // OK, time to get frisky. We don't actually care when the process
113 // terminates. We just care that it eventually terminates, and that's what
114 // TerminateProcess should do for us. Don't check for the result code since
115 // it fails quite often. This should be investigated eventually.
116 base::KillProcess(process_
, kProcessKilledExitCode
, false);
118 // Now, just cleanup as if the process exited normally.
119 OnObjectSignaled(process_
);
124 void RouteStdioToConsole() {
125 if (!AttachConsole(ATTACH_PARENT_PROCESS
)) {
126 unsigned int result
= GetLastError();
127 // Was probably already attached.
128 if (result
== ERROR_ACCESS_DENIED
)
130 // Don't bother creating a new console for each child process if the
131 // parent process is invalid (eg: crashed).
132 if (result
== ERROR_GEN_FAILURE
)
134 // Make a new console if attaching to parent fails with any other error.
135 // It should be ERROR_INVALID_HANDLE at this point, which means the browser
136 // was likely not started from a console.
140 // Arbitrary byte count to use when buffering output lines. More
141 // means potential waste, less means more risk of interleaved
142 // log-lines in output.
143 enum { kOutputBufferSize
= 64 * 1024 };
145 if (freopen("CONOUT$", "w", stdout
))
146 setvbuf(stdout
, NULL
, _IOLBF
, kOutputBufferSize
);
147 if (freopen("CONOUT$", "w", stderr
))
148 setvbuf(stderr
, NULL
, _IOLBF
, kOutputBufferSize
);
150 // Fix all cout, wcout, cin, wcin, cerr, wcerr, clog and wclog.
151 std::ios::sync_with_stdio();
154 ProcessId
GetCurrentProcId() {
155 return ::GetCurrentProcessId();
158 ProcessHandle
GetCurrentProcessHandle() {
159 return ::GetCurrentProcess();
162 HMODULE
GetModuleFromAddress(void* address
) {
163 HMODULE instance
= NULL
;
164 if (!::GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
|
165 GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT
,
166 static_cast<char*>(address
),
173 bool OpenProcessHandle(ProcessId pid
, ProcessHandle
* handle
) {
174 // We try to limit privileges granted to the handle. If you need this
175 // for test code, consider using OpenPrivilegedProcessHandle instead of
176 // adding more privileges here.
177 ProcessHandle result
= OpenProcess(PROCESS_DUP_HANDLE
| PROCESS_TERMINATE
,
187 bool OpenPrivilegedProcessHandle(ProcessId pid
, ProcessHandle
* handle
) {
188 ProcessHandle result
= OpenProcess(PROCESS_DUP_HANDLE
|
190 PROCESS_QUERY_INFORMATION
|
202 bool OpenProcessHandleWithAccess(ProcessId pid
,
204 ProcessHandle
* handle
) {
205 ProcessHandle result
= OpenProcess(access_flags
, FALSE
, pid
);
214 void CloseProcessHandle(ProcessHandle process
) {
215 CloseHandle(process
);
218 ProcessId
GetProcId(ProcessHandle process
) {
219 // Get a handle to |process| that has PROCESS_QUERY_INFORMATION rights.
220 HANDLE current_process
= GetCurrentProcess();
221 HANDLE process_with_query_rights
;
222 if (DuplicateHandle(current_process
, process
, current_process
,
223 &process_with_query_rights
, PROCESS_QUERY_INFORMATION
,
225 DWORD id
= GetProcessId(process_with_query_rights
);
226 CloseHandle(process_with_query_rights
);
235 bool GetProcessIntegrityLevel(ProcessHandle process
, IntegrityLevel
*level
) {
239 if (win::GetVersion() < base::win::VERSION_VISTA
)
242 HANDLE process_token
;
243 if (!OpenProcessToken(process
, TOKEN_QUERY
| TOKEN_QUERY_SOURCE
,
247 win::ScopedHandle
scoped_process_token(process_token
);
249 DWORD token_info_length
= 0;
250 if (GetTokenInformation(process_token
, TokenIntegrityLevel
, NULL
, 0,
251 &token_info_length
) ||
252 GetLastError() != ERROR_INSUFFICIENT_BUFFER
)
255 scoped_array
<char> token_label_bytes(new char[token_info_length
]);
256 if (!token_label_bytes
.get())
259 TOKEN_MANDATORY_LABEL
* token_label
=
260 reinterpret_cast<TOKEN_MANDATORY_LABEL
*>(token_label_bytes
.get());
264 if (!GetTokenInformation(process_token
, TokenIntegrityLevel
, token_label
,
265 token_info_length
, &token_info_length
))
268 DWORD integrity_level
= *GetSidSubAuthority(token_label
->Label
.Sid
,
269 (DWORD
)(UCHAR
)(*GetSidSubAuthorityCount(token_label
->Label
.Sid
)-1));
271 if (integrity_level
< SECURITY_MANDATORY_MEDIUM_RID
) {
272 *level
= LOW_INTEGRITY
;
273 } else if (integrity_level
>= SECURITY_MANDATORY_MEDIUM_RID
&&
274 integrity_level
< SECURITY_MANDATORY_HIGH_RID
) {
275 *level
= MEDIUM_INTEGRITY
;
276 } else if (integrity_level
>= SECURITY_MANDATORY_HIGH_RID
) {
277 *level
= HIGH_INTEGRITY
;
286 bool LaunchProcess(const string16
& cmdline
,
287 const LaunchOptions
& options
,
288 ProcessHandle
* process_handle
) {
289 STARTUPINFO startup_info
= {};
290 startup_info
.cb
= sizeof(startup_info
);
291 if (options
.empty_desktop_name
)
292 startup_info
.lpDesktop
= L
"";
293 startup_info
.dwFlags
= STARTF_USESHOWWINDOW
;
294 startup_info
.wShowWindow
= options
.start_hidden
? SW_HIDE
: SW_SHOW
;
296 if (options
.stdin_handle
|| options
.stdout_handle
|| options
.stderr_handle
) {
297 DCHECK(options
.inherit_handles
);
298 DCHECK(options
.stdin_handle
);
299 DCHECK(options
.stdout_handle
);
300 DCHECK(options
.stderr_handle
);
301 startup_info
.dwFlags
|= STARTF_USESTDHANDLES
;
302 startup_info
.hStdInput
= options
.stdin_handle
;
303 startup_info
.hStdOutput
= options
.stdout_handle
;
304 startup_info
.hStdError
= options
.stderr_handle
;
309 if (options
.job_handle
) {
310 flags
|= CREATE_SUSPENDED
;
312 // If this code is run under a debugger, the launched process is
313 // automatically associated with a job object created by the debugger.
314 // The CREATE_BREAKAWAY_FROM_JOB flag is used to prevent this.
315 flags
|= CREATE_BREAKAWAY_FROM_JOB
;
318 if (options
.force_breakaway_from_job_
)
319 flags
|= CREATE_BREAKAWAY_FROM_JOB
;
321 base::win::ScopedProcessInformation process_info
;
323 if (options
.as_user
) {
324 flags
|= CREATE_UNICODE_ENVIRONMENT
;
325 void* enviroment_block
= NULL
;
327 if (!CreateEnvironmentBlock(&enviroment_block
, options
.as_user
, FALSE
))
331 CreateProcessAsUser(options
.as_user
, NULL
,
332 const_cast<wchar_t*>(cmdline
.c_str()),
333 NULL
, NULL
, options
.inherit_handles
, flags
,
334 enviroment_block
, NULL
, &startup_info
,
335 process_info
.Receive());
336 DestroyEnvironmentBlock(enviroment_block
);
340 if (!CreateProcess(NULL
,
341 const_cast<wchar_t*>(cmdline
.c_str()), NULL
, NULL
,
342 options
.inherit_handles
, flags
, NULL
, NULL
,
343 &startup_info
, process_info
.Receive())) {
348 if (options
.job_handle
) {
349 if (0 == AssignProcessToJobObject(options
.job_handle
,
350 process_info
.process_handle())) {
351 DLOG(ERROR
) << "Could not AssignProcessToObject.";
352 KillProcess(process_info
.process_handle(), kProcessKilledExitCode
, true);
356 ResumeThread(process_info
.thread_handle());
360 WaitForSingleObject(process_info
.process_handle(), INFINITE
);
362 // If the caller wants the process handle, we won't close it.
364 *process_handle
= process_info
.TakeProcessHandle();
369 bool LaunchProcess(const CommandLine
& cmdline
,
370 const LaunchOptions
& options
,
371 ProcessHandle
* process_handle
) {
372 return LaunchProcess(cmdline
.GetCommandLineString(), options
, process_handle
);
375 bool SetJobObjectAsKillOnJobClose(HANDLE job_object
) {
376 JOBOBJECT_EXTENDED_LIMIT_INFORMATION limit_info
= {0};
377 limit_info
.BasicLimitInformation
.LimitFlags
=
378 JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
;
379 return 0 != SetInformationJobObject(
381 JobObjectExtendedLimitInformation
,
386 // Attempts to kill the process identified by the given process
387 // entry structure, giving it the specified exit code.
388 // Returns true if this is successful, false otherwise.
389 bool KillProcessById(ProcessId process_id
, int exit_code
, bool wait
) {
390 HANDLE process
= OpenProcess(PROCESS_TERMINATE
| SYNCHRONIZE
,
391 FALSE
, // Don't inherit handle
394 DLOG(ERROR
) << "Unable to open process " << process_id
<< " : "
398 bool ret
= KillProcess(process
, exit_code
, wait
);
399 CloseHandle(process
);
403 bool GetAppOutput(const CommandLine
& cl
, std::string
* output
) {
404 HANDLE out_read
= NULL
;
405 HANDLE out_write
= NULL
;
407 SECURITY_ATTRIBUTES sa_attr
;
408 // Set the bInheritHandle flag so pipe handles are inherited.
409 sa_attr
.nLength
= sizeof(SECURITY_ATTRIBUTES
);
410 sa_attr
.bInheritHandle
= TRUE
;
411 sa_attr
.lpSecurityDescriptor
= NULL
;
413 // Create the pipe for the child process's STDOUT.
414 if (!CreatePipe(&out_read
, &out_write
, &sa_attr
, 0)) {
415 NOTREACHED() << "Failed to create pipe";
419 // Ensure we don't leak the handles.
420 win::ScopedHandle
scoped_out_read(out_read
);
421 win::ScopedHandle
scoped_out_write(out_write
);
423 // Ensure the read handle to the pipe for STDOUT is not inherited.
424 if (!SetHandleInformation(out_read
, HANDLE_FLAG_INHERIT
, 0)) {
425 NOTREACHED() << "Failed to disabled pipe inheritance";
429 FilePath::StringType
writable_command_line_string(cl
.GetCommandLineString());
431 base::win::ScopedProcessInformation proc_info
;
432 STARTUPINFO start_info
= { 0 };
434 start_info
.cb
= sizeof(STARTUPINFO
);
435 start_info
.hStdOutput
= out_write
;
436 // Keep the normal stdin and stderr.
437 start_info
.hStdInput
= GetStdHandle(STD_INPUT_HANDLE
);
438 start_info
.hStdError
= GetStdHandle(STD_ERROR_HANDLE
);
439 start_info
.dwFlags
|= STARTF_USESTDHANDLES
;
441 // Create the child process.
442 if (!CreateProcess(NULL
,
443 &writable_command_line_string
[0],
445 TRUE
, // Handles are inherited.
446 0, NULL
, NULL
, &start_info
, proc_info
.Receive())) {
447 NOTREACHED() << "Failed to start process";
451 // Close our writing end of pipe now. Otherwise later read would not be able
452 // to detect end of child's output.
453 scoped_out_write
.Close();
455 // Read output from the child process's pipe for STDOUT
456 const int kBufferSize
= 1024;
457 char buffer
[kBufferSize
];
460 DWORD bytes_read
= 0;
461 BOOL success
= ReadFile(out_read
, buffer
, kBufferSize
, &bytes_read
, NULL
);
462 if (!success
|| bytes_read
== 0)
464 output
->append(buffer
, bytes_read
);
467 // Let's wait for the process to finish.
468 WaitForSingleObject(proc_info
.process_handle(), INFINITE
);
473 bool KillProcess(ProcessHandle process
, int exit_code
, bool wait
) {
474 bool result
= (TerminateProcess(process
, exit_code
) != FALSE
);
475 if (result
&& wait
) {
476 // The process may not end immediately due to pending I/O
477 if (WAIT_OBJECT_0
!= WaitForSingleObject(process
, 60 * 1000))
478 DLOG(ERROR
) << "Error waiting for process exit: " << GetLastError();
479 } else if (!result
) {
480 DLOG(ERROR
) << "Unable to terminate process: " << GetLastError();
485 TerminationStatus
GetTerminationStatus(ProcessHandle handle
, int* exit_code
) {
486 DWORD tmp_exit_code
= 0;
488 if (!::GetExitCodeProcess(handle
, &tmp_exit_code
)) {
491 // This really is a random number. We haven't received any
492 // information about the exit code, presumably because this
493 // process doesn't have permission to get the exit code, or
494 // because of some other cause for GetExitCodeProcess to fail
495 // (MSDN docs don't give the possible failure error codes for
496 // this function, so it could be anything). But we don't want
497 // to leave exit_code uninitialized, since that could cause
498 // random interpretations of the exit code. So we assume it
499 // terminated "normally" in this case.
500 *exit_code
= kNormalTerminationExitCode
;
502 // Assume the child has exited normally if we can't get the exit
504 return TERMINATION_STATUS_NORMAL_TERMINATION
;
506 if (tmp_exit_code
== STILL_ACTIVE
) {
507 DWORD wait_result
= WaitForSingleObject(handle
, 0);
508 if (wait_result
== WAIT_TIMEOUT
) {
510 *exit_code
= wait_result
;
511 return TERMINATION_STATUS_STILL_RUNNING
;
514 DCHECK_EQ(WAIT_OBJECT_0
, wait_result
);
516 // Strange, the process used 0x103 (STILL_ACTIVE) as exit code.
519 return TERMINATION_STATUS_ABNORMAL_TERMINATION
;
523 *exit_code
= tmp_exit_code
;
525 switch (tmp_exit_code
) {
526 case kNormalTerminationExitCode
:
527 return TERMINATION_STATUS_NORMAL_TERMINATION
;
528 case kDebuggerInactiveExitCode
: // STATUS_DEBUGGER_INACTIVE.
529 case kKeyboardInterruptExitCode
: // Control-C/end session.
530 case kDebuggerTerminatedExitCode
: // Debugger terminated process.
531 case kProcessKilledExitCode
: // Task manager kill.
532 return TERMINATION_STATUS_PROCESS_WAS_KILLED
;
534 // All other exit codes indicate crashes.
535 return TERMINATION_STATUS_PROCESS_CRASHED
;
539 bool WaitForExitCode(ProcessHandle handle
, int* exit_code
) {
540 bool success
= WaitForExitCodeWithTimeout(
541 handle
, exit_code
, base::TimeDelta::FromMilliseconds(INFINITE
));
542 CloseProcessHandle(handle
);
546 bool WaitForExitCodeWithTimeout(ProcessHandle handle
, int* exit_code
,
547 base::TimeDelta timeout
) {
548 if (::WaitForSingleObject(handle
, timeout
.InMilliseconds()) != WAIT_OBJECT_0
)
550 DWORD temp_code
; // Don't clobber out-parameters in case of failure.
551 if (!::GetExitCodeProcess(handle
, &temp_code
))
554 *exit_code
= temp_code
;
558 ProcessIterator::ProcessIterator(const ProcessFilter
* filter
)
559 : started_iteration_(false),
561 snapshot_
= CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS
, 0);
564 ProcessIterator::~ProcessIterator() {
565 CloseHandle(snapshot_
);
568 bool ProcessIterator::CheckForNextProcess() {
569 InitProcessEntry(&entry_
);
571 if (!started_iteration_
) {
572 started_iteration_
= true;
573 return !!Process32First(snapshot_
, &entry_
);
576 return !!Process32Next(snapshot_
, &entry_
);
579 void ProcessIterator::InitProcessEntry(ProcessEntry
* entry
) {
580 memset(entry
, 0, sizeof(*entry
));
581 entry
->dwSize
= sizeof(*entry
);
584 bool NamedProcessIterator::IncludeEntry() {
586 return _wcsicmp(executable_name_
.c_str(), entry().exe_file()) == 0 &&
587 ProcessIterator::IncludeEntry();
590 bool WaitForProcessesToExit(const FilePath::StringType
& executable_name
,
591 base::TimeDelta wait
,
592 const ProcessFilter
* filter
) {
593 const ProcessEntry
* entry
;
595 DWORD start_time
= GetTickCount();
597 NamedProcessIterator
iter(executable_name
, filter
);
598 while ((entry
= iter
.NextProcessEntry())) {
599 DWORD remaining_wait
= std::max
<int64
>(
600 0, wait
.InMilliseconds() - (GetTickCount() - start_time
));
601 HANDLE process
= OpenProcess(SYNCHRONIZE
,
603 entry
->th32ProcessID
);
604 DWORD wait_result
= WaitForSingleObject(process
, remaining_wait
);
605 CloseHandle(process
);
606 result
= result
&& (wait_result
== WAIT_OBJECT_0
);
612 bool WaitForSingleProcess(ProcessHandle handle
, base::TimeDelta wait
) {
614 if (!WaitForExitCodeWithTimeout(handle
, &exit_code
, wait
))
616 return exit_code
== 0;
619 bool CleanupProcesses(const FilePath::StringType
& executable_name
,
620 base::TimeDelta wait
,
622 const ProcessFilter
* filter
) {
623 bool exited_cleanly
= WaitForProcessesToExit(executable_name
, wait
, filter
);
625 KillProcesses(executable_name
, exit_code
, filter
);
626 return exited_cleanly
;
629 void EnsureProcessTerminated(ProcessHandle process
) {
630 DCHECK(process
!= GetCurrentProcess());
632 // If already signaled, then we are done!
633 if (WaitForSingleObject(process
, 0) == WAIT_OBJECT_0
) {
634 CloseHandle(process
);
638 MessageLoop::current()->PostDelayedTask(
640 base::Bind(&TimerExpiredTask::TimedOut
,
641 base::Owned(new TimerExpiredTask(process
))),
642 base::TimeDelta::FromMilliseconds(kWaitInterval
));
645 ///////////////////////////////////////////////////////////////////////////////
648 ProcessMetrics::ProcessMetrics(ProcessHandle process
)
650 processor_count_(base::SysInfo::NumberOfProcessors()),
652 last_system_time_(0) {
656 ProcessMetrics
* ProcessMetrics::CreateProcessMetrics(ProcessHandle process
) {
657 return new ProcessMetrics(process
);
660 ProcessMetrics::~ProcessMetrics() { }
662 size_t ProcessMetrics::GetPagefileUsage() const {
663 PROCESS_MEMORY_COUNTERS pmc
;
664 if (GetProcessMemoryInfo(process_
, &pmc
, sizeof(pmc
))) {
665 return pmc
.PagefileUsage
;
670 // Returns the peak space allocated for the pagefile, in bytes.
671 size_t ProcessMetrics::GetPeakPagefileUsage() const {
672 PROCESS_MEMORY_COUNTERS pmc
;
673 if (GetProcessMemoryInfo(process_
, &pmc
, sizeof(pmc
))) {
674 return pmc
.PeakPagefileUsage
;
679 // Returns the current working set size, in bytes.
680 size_t ProcessMetrics::GetWorkingSetSize() const {
681 PROCESS_MEMORY_COUNTERS pmc
;
682 if (GetProcessMemoryInfo(process_
, &pmc
, sizeof(pmc
))) {
683 return pmc
.WorkingSetSize
;
688 // Returns the peak working set size, in bytes.
689 size_t ProcessMetrics::GetPeakWorkingSetSize() const {
690 PROCESS_MEMORY_COUNTERS pmc
;
691 if (GetProcessMemoryInfo(process_
, &pmc
, sizeof(pmc
))) {
692 return pmc
.PeakWorkingSetSize
;
697 bool ProcessMetrics::GetMemoryBytes(size_t* private_bytes
,
698 size_t* shared_bytes
) {
699 // PROCESS_MEMORY_COUNTERS_EX is not supported until XP SP2.
700 // GetProcessMemoryInfo() will simply fail on prior OS. So the requested
701 // information is simply not available. Hence, we will return 0 on unsupported
702 // OSes. Unlike most Win32 API, we don't need to initialize the "cb" member.
703 PROCESS_MEMORY_COUNTERS_EX pmcx
;
705 GetProcessMemoryInfo(process_
,
706 reinterpret_cast<PROCESS_MEMORY_COUNTERS
*>(&pmcx
),
708 *private_bytes
= pmcx
.PrivateUsage
;
712 WorkingSetKBytes ws_usage
;
713 if (!GetWorkingSetKBytes(&ws_usage
))
716 *shared_bytes
= ws_usage
.shared
* 1024;
722 void ProcessMetrics::GetCommittedKBytes(CommittedKBytes
* usage
) const {
723 MEMORY_BASIC_INFORMATION mbi
= {0};
724 size_t committed_private
= 0;
725 size_t committed_mapped
= 0;
726 size_t committed_image
= 0;
727 void* base_address
= NULL
;
728 while (VirtualQueryEx(process_
, base_address
, &mbi
, sizeof(mbi
)) ==
730 if (mbi
.State
== MEM_COMMIT
) {
731 if (mbi
.Type
== MEM_PRIVATE
) {
732 committed_private
+= mbi
.RegionSize
;
733 } else if (mbi
.Type
== MEM_MAPPED
) {
734 committed_mapped
+= mbi
.RegionSize
;
735 } else if (mbi
.Type
== MEM_IMAGE
) {
736 committed_image
+= mbi
.RegionSize
;
741 void* new_base
= (static_cast<BYTE
*>(mbi
.BaseAddress
)) + mbi
.RegionSize
;
742 // Avoid infinite loop by weird MEMORY_BASIC_INFORMATION.
743 // If we query 64bit processes in a 32bit process, VirtualQueryEx()
744 // returns such data.
745 if (new_base
<= base_address
) {
751 base_address
= new_base
;
753 usage
->image
= committed_image
/ 1024;
754 usage
->mapped
= committed_mapped
/ 1024;
755 usage
->priv
= committed_private
/ 1024;
758 bool ProcessMetrics::GetWorkingSetKBytes(WorkingSetKBytes
* ws_usage
) const {
759 size_t ws_private
= 0;
760 size_t ws_shareable
= 0;
761 size_t ws_shared
= 0;
764 memset(ws_usage
, 0, sizeof(*ws_usage
));
766 DWORD number_of_entries
= 4096; // Just a guess.
767 PSAPI_WORKING_SET_INFORMATION
* buffer
= NULL
;
770 DWORD buffer_size
= sizeof(PSAPI_WORKING_SET_INFORMATION
) +
771 (number_of_entries
* sizeof(PSAPI_WORKING_SET_BLOCK
));
773 // if we can't expand the buffer, don't leak the previous
774 // contents or pass a NULL pointer to QueryWorkingSet
775 PSAPI_WORKING_SET_INFORMATION
* new_buffer
=
776 reinterpret_cast<PSAPI_WORKING_SET_INFORMATION
*>(
777 realloc(buffer
, buffer_size
));
784 // Call the function once to get number of items
785 if (QueryWorkingSet(process_
, buffer
, buffer_size
))
788 if (GetLastError() != ERROR_BAD_LENGTH
) {
793 number_of_entries
= static_cast<DWORD
>(buffer
->NumberOfEntries
);
795 // Maybe some entries are being added right now. Increase the buffer to
796 // take that into account.
797 number_of_entries
= static_cast<DWORD
>(number_of_entries
* 1.25);
799 if (--retries
== 0) {
800 free(buffer
); // If we're looping, eventually fail.
805 // On windows 2000 the function returns 1 even when the buffer is too small.
806 // The number of entries that we are going to parse is the minimum between the
807 // size we allocated and the real number of entries.
809 std::min(number_of_entries
, static_cast<DWORD
>(buffer
->NumberOfEntries
));
810 for (unsigned int i
= 0; i
< number_of_entries
; i
++) {
811 if (buffer
->WorkingSetInfo
[i
].Shared
) {
813 if (buffer
->WorkingSetInfo
[i
].ShareCount
> 1)
820 ws_usage
->priv
= ws_private
* PAGESIZE_KB
;
821 ws_usage
->shareable
= ws_shareable
* PAGESIZE_KB
;
822 ws_usage
->shared
= ws_shared
* PAGESIZE_KB
;
827 static uint64
FileTimeToUTC(const FILETIME
& ftime
) {
829 li
.LowPart
= ftime
.dwLowDateTime
;
830 li
.HighPart
= ftime
.dwHighDateTime
;
834 double ProcessMetrics::GetCPUUsage() {
836 FILETIME creation_time
;
838 FILETIME kernel_time
;
841 GetSystemTimeAsFileTime(&now
);
843 if (!GetProcessTimes(process_
, &creation_time
, &exit_time
,
844 &kernel_time
, &user_time
)) {
845 // We don't assert here because in some cases (such as in the Task Manager)
846 // we may call this function on a process that has just exited but we have
847 // not yet received the notification.
850 int64 system_time
= (FileTimeToUTC(kernel_time
) + FileTimeToUTC(user_time
)) /
852 int64 time
= FileTimeToUTC(now
);
854 if ((last_system_time_
== 0) || (last_time_
== 0)) {
855 // First call, just set the last values.
856 last_system_time_
= system_time
;
861 int64 system_time_delta
= system_time
- last_system_time_
;
862 int64 time_delta
= time
- last_time_
;
863 DCHECK_NE(0U, time_delta
);
867 // We add time_delta / 2 so the result is rounded.
868 int cpu
= static_cast<int>((system_time_delta
* 100 + time_delta
/ 2) /
871 last_system_time_
= system_time
;
877 bool ProcessMetrics::GetIOCounters(IoCounters
* io_counters
) const {
878 return GetProcessIoCounters(process_
, io_counters
) != FALSE
;
881 bool ProcessMetrics::CalculateFreeMemory(FreeMBytes
* free
) const {
882 const SIZE_T kTopAddress
= 0x7F000000;
883 const SIZE_T kMegabyte
= 1024 * 1024;
884 SIZE_T accumulated
= 0;
886 MEMORY_BASIC_INFORMATION largest
= {0};
888 while (scan
< kTopAddress
) {
889 MEMORY_BASIC_INFORMATION info
;
890 if (!::VirtualQueryEx(process_
, reinterpret_cast<void*>(scan
),
891 &info
, sizeof(info
)))
893 if (info
.State
== MEM_FREE
) {
894 accumulated
+= info
.RegionSize
;
895 if (info
.RegionSize
> largest
.RegionSize
)
898 scan
+= info
.RegionSize
;
900 free
->largest
= largest
.RegionSize
/ kMegabyte
;
901 free
->largest_ptr
= largest
.BaseAddress
;
902 free
->total
= accumulated
/ kMegabyte
;
906 bool EnableLowFragmentationHeap() {
907 HMODULE kernel32
= GetModuleHandle(L
"kernel32.dll");
908 HeapSetFn heap_set
= reinterpret_cast<HeapSetFn
>(GetProcAddress(
910 "HeapSetInformation"));
912 // On Windows 2000, the function is not exported. This is not a reason to
917 unsigned number_heaps
= GetProcessHeaps(0, NULL
);
921 // Gives us some extra space in the array in case a thread is creating heaps
922 // at the same time we're querying them.
923 static const int MARGIN
= 8;
924 scoped_array
<HANDLE
> heaps(new HANDLE
[number_heaps
+ MARGIN
]);
925 number_heaps
= GetProcessHeaps(number_heaps
+ MARGIN
, heaps
.get());
929 for (unsigned i
= 0; i
< number_heaps
; ++i
) {
931 // Don't bother with the result code. It may fails on heaps that have the
932 // HEAP_NO_SERIALIZE flag. This is expected and not a problem at all.
934 HeapCompatibilityInformation
,
941 void EnableTerminationOnHeapCorruption() {
942 // Ignore the result code. Supported on XP SP3 and Vista.
943 HeapSetInformation(NULL
, HeapEnableTerminationOnCorruption
, NULL
, 0);
946 void EnableTerminationOnOutOfMemory() {
947 std::set_new_handler(&OnNoMemory
);
950 void RaiseProcessToHighPriority() {
951 SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS
);
954 // GetPerformanceInfo is not available on WIN2K. So we'll
955 // load it on-the-fly.
956 const wchar_t kPsapiDllName
[] = L
"psapi.dll";
957 typedef BOOL (WINAPI
*GetPerformanceInfoFunction
) (
958 PPERFORMANCE_INFORMATION pPerformanceInformation
,
961 // Beware of races if called concurrently from multiple threads.
962 static BOOL
InternalGetPerformanceInfo(
963 PPERFORMANCE_INFORMATION pPerformanceInformation
, DWORD cb
) {
964 static GetPerformanceInfoFunction GetPerformanceInfo_func
= NULL
;
965 if (!GetPerformanceInfo_func
) {
966 HMODULE psapi_dll
= ::GetModuleHandle(kPsapiDllName
);
968 GetPerformanceInfo_func
= reinterpret_cast<GetPerformanceInfoFunction
>(
969 GetProcAddress(psapi_dll
, "GetPerformanceInfo"));
971 if (!GetPerformanceInfo_func
) {
972 // The function could be loaded!
973 memset(pPerformanceInformation
, 0, cb
);
977 return GetPerformanceInfo_func(pPerformanceInformation
, cb
);
980 size_t GetSystemCommitCharge() {
981 // Get the System Page Size.
982 SYSTEM_INFO system_info
;
983 GetSystemInfo(&system_info
);
985 PERFORMANCE_INFORMATION info
;
986 if (!InternalGetPerformanceInfo(&info
, sizeof(info
))) {
987 DLOG(ERROR
) << "Failed to fetch internal performance info.";
990 return (info
.CommitTotal
* system_info
.dwPageSize
) / 1024;