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 // Don't change anything if stdout or stderr already point to a
128 // If we are running under Buildbot or under Cygwin's default
129 // terminal (mintty), stderr and stderr will be pipe handles. In
130 // that case, we don't want to open CONOUT$, because its output
131 // likely does not go anywhere.
133 // We don't use GetStdHandle() to check stdout/stderr here because
134 // it can return dangling IDs of handles that were never inherited
135 // by this process. These IDs could have been reused by the time
136 // this function is called. The CRT checks the validity of
137 // stdout/stderr on startup (before the handle IDs can be reused).
138 // _fileno(stdout) will return -2 (_NO_CONSOLE_FILENO) if stdout was
140 if (_fileno(stdout
) >= 0 || _fileno(stderr
) >= 0)
143 if (!AttachConsole(ATTACH_PARENT_PROCESS
)) {
144 unsigned int result
= GetLastError();
145 // Was probably already attached.
146 if (result
== ERROR_ACCESS_DENIED
)
148 // Don't bother creating a new console for each child process if the
149 // parent process is invalid (eg: crashed).
150 if (result
== ERROR_GEN_FAILURE
)
152 // Make a new console if attaching to parent fails with any other error.
153 // It should be ERROR_INVALID_HANDLE at this point, which means the browser
154 // was likely not started from a console.
158 // Arbitrary byte count to use when buffering output lines. More
159 // means potential waste, less means more risk of interleaved
160 // log-lines in output.
161 enum { kOutputBufferSize
= 64 * 1024 };
163 if (freopen("CONOUT$", "w", stdout
)) {
164 setvbuf(stdout
, NULL
, _IOLBF
, kOutputBufferSize
);
165 // Overwrite FD 1 for the benefit of any code that uses this FD
166 // directly. This is safe because the CRT allocates FDs 0, 1 and
167 // 2 at startup even if they don't have valid underlying Windows
168 // handles. This means we won't be overwriting an FD created by
169 // _open() after startup.
170 _dup2(_fileno(stdout
), 1);
172 if (freopen("CONOUT$", "w", stderr
)) {
173 setvbuf(stderr
, NULL
, _IOLBF
, kOutputBufferSize
);
174 _dup2(_fileno(stderr
), 2);
177 // Fix all cout, wcout, cin, wcin, cerr, wcerr, clog and wclog.
178 std::ios::sync_with_stdio();
181 ProcessId
GetCurrentProcId() {
182 return ::GetCurrentProcessId();
185 ProcessHandle
GetCurrentProcessHandle() {
186 return ::GetCurrentProcess();
189 HMODULE
GetModuleFromAddress(void* address
) {
190 HMODULE instance
= NULL
;
191 if (!::GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
|
192 GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT
,
193 static_cast<char*>(address
),
200 bool OpenProcessHandle(ProcessId pid
, ProcessHandle
* handle
) {
201 // We try to limit privileges granted to the handle. If you need this
202 // for test code, consider using OpenPrivilegedProcessHandle instead of
203 // adding more privileges here.
204 ProcessHandle result
= OpenProcess(PROCESS_TERMINATE
|
205 PROCESS_QUERY_INFORMATION
|
216 bool OpenPrivilegedProcessHandle(ProcessId pid
, ProcessHandle
* handle
) {
217 ProcessHandle result
= OpenProcess(PROCESS_DUP_HANDLE
|
219 PROCESS_QUERY_INFORMATION
|
231 bool OpenProcessHandleWithAccess(ProcessId pid
,
233 ProcessHandle
* handle
) {
234 ProcessHandle result
= OpenProcess(access_flags
, FALSE
, pid
);
243 void CloseProcessHandle(ProcessHandle process
) {
244 CloseHandle(process
);
247 ProcessId
GetProcId(ProcessHandle process
) {
248 // Get a handle to |process| that has PROCESS_QUERY_INFORMATION rights.
249 HANDLE current_process
= GetCurrentProcess();
250 HANDLE process_with_query_rights
;
251 if (DuplicateHandle(current_process
, process
, current_process
,
252 &process_with_query_rights
, PROCESS_QUERY_INFORMATION
,
254 DWORD id
= GetProcessId(process_with_query_rights
);
255 CloseHandle(process_with_query_rights
);
264 bool GetProcessIntegrityLevel(ProcessHandle process
, IntegrityLevel
*level
) {
268 if (win::GetVersion() < base::win::VERSION_VISTA
)
271 HANDLE process_token
;
272 if (!OpenProcessToken(process
, TOKEN_QUERY
| TOKEN_QUERY_SOURCE
,
276 win::ScopedHandle
scoped_process_token(process_token
);
278 DWORD token_info_length
= 0;
279 if (GetTokenInformation(process_token
, TokenIntegrityLevel
, NULL
, 0,
280 &token_info_length
) ||
281 GetLastError() != ERROR_INSUFFICIENT_BUFFER
)
284 scoped_ptr
<char[]> token_label_bytes(new char[token_info_length
]);
285 if (!token_label_bytes
.get())
288 TOKEN_MANDATORY_LABEL
* token_label
=
289 reinterpret_cast<TOKEN_MANDATORY_LABEL
*>(token_label_bytes
.get());
293 if (!GetTokenInformation(process_token
, TokenIntegrityLevel
, token_label
,
294 token_info_length
, &token_info_length
))
297 DWORD integrity_level
= *GetSidSubAuthority(token_label
->Label
.Sid
,
298 (DWORD
)(UCHAR
)(*GetSidSubAuthorityCount(token_label
->Label
.Sid
)-1));
300 if (integrity_level
< SECURITY_MANDATORY_MEDIUM_RID
) {
301 *level
= LOW_INTEGRITY
;
302 } else if (integrity_level
>= SECURITY_MANDATORY_MEDIUM_RID
&&
303 integrity_level
< SECURITY_MANDATORY_HIGH_RID
) {
304 *level
= MEDIUM_INTEGRITY
;
305 } else if (integrity_level
>= SECURITY_MANDATORY_HIGH_RID
) {
306 *level
= HIGH_INTEGRITY
;
315 bool LaunchProcess(const string16
& cmdline
,
316 const LaunchOptions
& options
,
317 ProcessHandle
* process_handle
) {
318 STARTUPINFO startup_info
= {};
319 startup_info
.cb
= sizeof(startup_info
);
320 if (options
.empty_desktop_name
)
321 startup_info
.lpDesktop
= L
"";
322 startup_info
.dwFlags
= STARTF_USESHOWWINDOW
;
323 startup_info
.wShowWindow
= options
.start_hidden
? SW_HIDE
: SW_SHOW
;
325 if (options
.stdin_handle
|| options
.stdout_handle
|| options
.stderr_handle
) {
326 DCHECK(options
.inherit_handles
);
327 DCHECK(options
.stdin_handle
);
328 DCHECK(options
.stdout_handle
);
329 DCHECK(options
.stderr_handle
);
330 startup_info
.dwFlags
|= STARTF_USESTDHANDLES
;
331 startup_info
.hStdInput
= options
.stdin_handle
;
332 startup_info
.hStdOutput
= options
.stdout_handle
;
333 startup_info
.hStdError
= options
.stderr_handle
;
338 if (options
.job_handle
) {
339 flags
|= CREATE_SUSPENDED
;
341 // If this code is run under a debugger, the launched process is
342 // automatically associated with a job object created by the debugger.
343 // The CREATE_BREAKAWAY_FROM_JOB flag is used to prevent this.
344 flags
|= CREATE_BREAKAWAY_FROM_JOB
;
347 if (options
.force_breakaway_from_job_
)
348 flags
|= CREATE_BREAKAWAY_FROM_JOB
;
350 base::win::ScopedProcessInformation process_info
;
352 if (options
.as_user
) {
353 flags
|= CREATE_UNICODE_ENVIRONMENT
;
354 void* enviroment_block
= NULL
;
356 if (!CreateEnvironmentBlock(&enviroment_block
, options
.as_user
, FALSE
)) {
362 CreateProcessAsUser(options
.as_user
, NULL
,
363 const_cast<wchar_t*>(cmdline
.c_str()),
364 NULL
, NULL
, options
.inherit_handles
, flags
,
365 enviroment_block
, NULL
, &startup_info
,
366 process_info
.Receive());
367 DestroyEnvironmentBlock(enviroment_block
);
373 if (!CreateProcess(NULL
,
374 const_cast<wchar_t*>(cmdline
.c_str()), NULL
, NULL
,
375 options
.inherit_handles
, flags
, NULL
, NULL
,
376 &startup_info
, process_info
.Receive())) {
382 if (options
.job_handle
) {
383 if (0 == AssignProcessToJobObject(options
.job_handle
,
384 process_info
.process_handle())) {
385 DLOG(ERROR
) << "Could not AssignProcessToObject.";
386 KillProcess(process_info
.process_handle(), kProcessKilledExitCode
, true);
390 ResumeThread(process_info
.thread_handle());
394 WaitForSingleObject(process_info
.process_handle(), INFINITE
);
396 // If the caller wants the process handle, we won't close it.
398 *process_handle
= process_info
.TakeProcessHandle();
403 bool LaunchProcess(const CommandLine
& cmdline
,
404 const LaunchOptions
& options
,
405 ProcessHandle
* process_handle
) {
406 return LaunchProcess(cmdline
.GetCommandLineString(), options
, process_handle
);
409 bool SetJobObjectAsKillOnJobClose(HANDLE job_object
) {
410 JOBOBJECT_EXTENDED_LIMIT_INFORMATION limit_info
= {0};
411 limit_info
.BasicLimitInformation
.LimitFlags
=
412 JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
;
413 return 0 != SetInformationJobObject(
415 JobObjectExtendedLimitInformation
,
420 // Attempts to kill the process identified by the given process
421 // entry structure, giving it the specified exit code.
422 // Returns true if this is successful, false otherwise.
423 bool KillProcessById(ProcessId process_id
, int exit_code
, bool wait
) {
424 HANDLE process
= OpenProcess(PROCESS_TERMINATE
| SYNCHRONIZE
,
425 FALSE
, // Don't inherit handle
428 DLOG_GETLASTERROR(ERROR
) << "Unable to open process " << process_id
;
431 bool ret
= KillProcess(process
, exit_code
, wait
);
432 CloseHandle(process
);
436 bool GetAppOutput(const CommandLine
& cl
, std::string
* output
) {
437 HANDLE out_read
= NULL
;
438 HANDLE out_write
= NULL
;
440 SECURITY_ATTRIBUTES sa_attr
;
441 // Set the bInheritHandle flag so pipe handles are inherited.
442 sa_attr
.nLength
= sizeof(SECURITY_ATTRIBUTES
);
443 sa_attr
.bInheritHandle
= TRUE
;
444 sa_attr
.lpSecurityDescriptor
= NULL
;
446 // Create the pipe for the child process's STDOUT.
447 if (!CreatePipe(&out_read
, &out_write
, &sa_attr
, 0)) {
448 NOTREACHED() << "Failed to create pipe";
452 // Ensure we don't leak the handles.
453 win::ScopedHandle
scoped_out_read(out_read
);
454 win::ScopedHandle
scoped_out_write(out_write
);
456 // Ensure the read handle to the pipe for STDOUT is not inherited.
457 if (!SetHandleInformation(out_read
, HANDLE_FLAG_INHERIT
, 0)) {
458 NOTREACHED() << "Failed to disabled pipe inheritance";
462 FilePath::StringType
writable_command_line_string(cl
.GetCommandLineString());
464 base::win::ScopedProcessInformation proc_info
;
465 STARTUPINFO start_info
= { 0 };
467 start_info
.cb
= sizeof(STARTUPINFO
);
468 start_info
.hStdOutput
= out_write
;
469 // Keep the normal stdin and stderr.
470 start_info
.hStdInput
= GetStdHandle(STD_INPUT_HANDLE
);
471 start_info
.hStdError
= GetStdHandle(STD_ERROR_HANDLE
);
472 start_info
.dwFlags
|= STARTF_USESTDHANDLES
;
474 // Create the child process.
475 if (!CreateProcess(NULL
,
476 &writable_command_line_string
[0],
478 TRUE
, // Handles are inherited.
479 0, NULL
, NULL
, &start_info
, proc_info
.Receive())) {
480 NOTREACHED() << "Failed to start process";
484 // Close our writing end of pipe now. Otherwise later read would not be able
485 // to detect end of child's output.
486 scoped_out_write
.Close();
488 // Read output from the child process's pipe for STDOUT
489 const int kBufferSize
= 1024;
490 char buffer
[kBufferSize
];
493 DWORD bytes_read
= 0;
494 BOOL success
= ReadFile(out_read
, buffer
, kBufferSize
, &bytes_read
, NULL
);
495 if (!success
|| bytes_read
== 0)
497 output
->append(buffer
, bytes_read
);
500 // Let's wait for the process to finish.
501 WaitForSingleObject(proc_info
.process_handle(), INFINITE
);
506 bool KillProcess(ProcessHandle process
, int exit_code
, bool wait
) {
507 bool result
= (TerminateProcess(process
, exit_code
) != FALSE
);
508 if (result
&& wait
) {
509 // The process may not end immediately due to pending I/O
510 if (WAIT_OBJECT_0
!= WaitForSingleObject(process
, 60 * 1000))
511 DLOG_GETLASTERROR(ERROR
) << "Error waiting for process exit";
512 } else if (!result
) {
513 DLOG_GETLASTERROR(ERROR
) << "Unable to terminate process";
518 TerminationStatus
GetTerminationStatus(ProcessHandle handle
, int* exit_code
) {
519 DWORD tmp_exit_code
= 0;
521 if (!::GetExitCodeProcess(handle
, &tmp_exit_code
)) {
522 DLOG_GETLASTERROR(FATAL
) << "GetExitCodeProcess() failed";
524 // This really is a random number. We haven't received any
525 // information about the exit code, presumably because this
526 // process doesn't have permission to get the exit code, or
527 // because of some other cause for GetExitCodeProcess to fail
528 // (MSDN docs don't give the possible failure error codes for
529 // this function, so it could be anything). But we don't want
530 // to leave exit_code uninitialized, since that could cause
531 // random interpretations of the exit code. So we assume it
532 // terminated "normally" in this case.
533 *exit_code
= kNormalTerminationExitCode
;
535 // Assume the child has exited normally if we can't get the exit
537 return TERMINATION_STATUS_NORMAL_TERMINATION
;
539 if (tmp_exit_code
== STILL_ACTIVE
) {
540 DWORD wait_result
= WaitForSingleObject(handle
, 0);
541 if (wait_result
== WAIT_TIMEOUT
) {
543 *exit_code
= wait_result
;
544 return TERMINATION_STATUS_STILL_RUNNING
;
547 if (wait_result
== WAIT_FAILED
) {
548 DLOG_GETLASTERROR(ERROR
) << "WaitForSingleObject() failed";
550 DCHECK_EQ(WAIT_OBJECT_0
, wait_result
);
552 // Strange, the process used 0x103 (STILL_ACTIVE) as exit code.
556 return TERMINATION_STATUS_ABNORMAL_TERMINATION
;
560 *exit_code
= tmp_exit_code
;
562 switch (tmp_exit_code
) {
563 case kNormalTerminationExitCode
:
564 return TERMINATION_STATUS_NORMAL_TERMINATION
;
565 case kDebuggerInactiveExitCode
: // STATUS_DEBUGGER_INACTIVE.
566 case kKeyboardInterruptExitCode
: // Control-C/end session.
567 case kDebuggerTerminatedExitCode
: // Debugger terminated process.
568 case kProcessKilledExitCode
: // Task manager kill.
569 return TERMINATION_STATUS_PROCESS_WAS_KILLED
;
571 // All other exit codes indicate crashes.
572 return TERMINATION_STATUS_PROCESS_CRASHED
;
576 bool WaitForExitCode(ProcessHandle handle
, int* exit_code
) {
577 bool success
= WaitForExitCodeWithTimeout(
578 handle
, exit_code
, base::TimeDelta::FromMilliseconds(INFINITE
));
579 CloseProcessHandle(handle
);
583 bool WaitForExitCodeWithTimeout(ProcessHandle handle
, int* exit_code
,
584 base::TimeDelta timeout
) {
585 if (::WaitForSingleObject(handle
, timeout
.InMilliseconds()) != WAIT_OBJECT_0
)
587 DWORD temp_code
; // Don't clobber out-parameters in case of failure.
588 if (!::GetExitCodeProcess(handle
, &temp_code
))
591 *exit_code
= temp_code
;
595 ProcessIterator::ProcessIterator(const ProcessFilter
* filter
)
596 : started_iteration_(false),
598 snapshot_
= CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS
, 0);
601 ProcessIterator::~ProcessIterator() {
602 CloseHandle(snapshot_
);
605 bool ProcessIterator::CheckForNextProcess() {
606 InitProcessEntry(&entry_
);
608 if (!started_iteration_
) {
609 started_iteration_
= true;
610 return !!Process32First(snapshot_
, &entry_
);
613 return !!Process32Next(snapshot_
, &entry_
);
616 void ProcessIterator::InitProcessEntry(ProcessEntry
* entry
) {
617 memset(entry
, 0, sizeof(*entry
));
618 entry
->dwSize
= sizeof(*entry
);
621 bool NamedProcessIterator::IncludeEntry() {
623 return _wcsicmp(executable_name_
.c_str(), entry().exe_file()) == 0 &&
624 ProcessIterator::IncludeEntry();
627 bool WaitForProcessesToExit(const FilePath::StringType
& executable_name
,
628 base::TimeDelta wait
,
629 const ProcessFilter
* filter
) {
630 const ProcessEntry
* entry
;
632 DWORD start_time
= GetTickCount();
634 NamedProcessIterator
iter(executable_name
, filter
);
635 while ((entry
= iter
.NextProcessEntry())) {
636 DWORD remaining_wait
= std::max
<int64
>(
637 0, wait
.InMilliseconds() - (GetTickCount() - start_time
));
638 HANDLE process
= OpenProcess(SYNCHRONIZE
,
640 entry
->th32ProcessID
);
641 DWORD wait_result
= WaitForSingleObject(process
, remaining_wait
);
642 CloseHandle(process
);
643 result
= result
&& (wait_result
== WAIT_OBJECT_0
);
649 bool WaitForSingleProcess(ProcessHandle handle
, base::TimeDelta wait
) {
651 if (!WaitForExitCodeWithTimeout(handle
, &exit_code
, wait
))
653 return exit_code
== 0;
656 bool CleanupProcesses(const FilePath::StringType
& executable_name
,
657 base::TimeDelta wait
,
659 const ProcessFilter
* filter
) {
660 bool exited_cleanly
= WaitForProcessesToExit(executable_name
, wait
, filter
);
662 KillProcesses(executable_name
, exit_code
, filter
);
663 return exited_cleanly
;
666 void EnsureProcessTerminated(ProcessHandle process
) {
667 DCHECK(process
!= GetCurrentProcess());
669 // If already signaled, then we are done!
670 if (WaitForSingleObject(process
, 0) == WAIT_OBJECT_0
) {
671 CloseHandle(process
);
675 MessageLoop::current()->PostDelayedTask(
677 base::Bind(&TimerExpiredTask::TimedOut
,
678 base::Owned(new TimerExpiredTask(process
))),
679 base::TimeDelta::FromMilliseconds(kWaitInterval
));
682 ///////////////////////////////////////////////////////////////////////////////
685 ProcessMetrics::ProcessMetrics(ProcessHandle process
)
687 processor_count_(base::SysInfo::NumberOfProcessors()),
689 last_system_time_(0) {
693 ProcessMetrics
* ProcessMetrics::CreateProcessMetrics(ProcessHandle process
) {
694 return new ProcessMetrics(process
);
697 ProcessMetrics::~ProcessMetrics() { }
699 size_t ProcessMetrics::GetPagefileUsage() const {
700 PROCESS_MEMORY_COUNTERS pmc
;
701 if (GetProcessMemoryInfo(process_
, &pmc
, sizeof(pmc
))) {
702 return pmc
.PagefileUsage
;
707 // Returns the peak space allocated for the pagefile, in bytes.
708 size_t ProcessMetrics::GetPeakPagefileUsage() const {
709 PROCESS_MEMORY_COUNTERS pmc
;
710 if (GetProcessMemoryInfo(process_
, &pmc
, sizeof(pmc
))) {
711 return pmc
.PeakPagefileUsage
;
716 // Returns the current working set size, in bytes.
717 size_t ProcessMetrics::GetWorkingSetSize() const {
718 PROCESS_MEMORY_COUNTERS pmc
;
719 if (GetProcessMemoryInfo(process_
, &pmc
, sizeof(pmc
))) {
720 return pmc
.WorkingSetSize
;
725 // Returns the peak working set size, in bytes.
726 size_t ProcessMetrics::GetPeakWorkingSetSize() const {
727 PROCESS_MEMORY_COUNTERS pmc
;
728 if (GetProcessMemoryInfo(process_
, &pmc
, sizeof(pmc
))) {
729 return pmc
.PeakWorkingSetSize
;
734 bool ProcessMetrics::GetMemoryBytes(size_t* private_bytes
,
735 size_t* shared_bytes
) {
736 // PROCESS_MEMORY_COUNTERS_EX is not supported until XP SP2.
737 // GetProcessMemoryInfo() will simply fail on prior OS. So the requested
738 // information is simply not available. Hence, we will return 0 on unsupported
739 // OSes. Unlike most Win32 API, we don't need to initialize the "cb" member.
740 PROCESS_MEMORY_COUNTERS_EX pmcx
;
742 GetProcessMemoryInfo(process_
,
743 reinterpret_cast<PROCESS_MEMORY_COUNTERS
*>(&pmcx
),
745 *private_bytes
= pmcx
.PrivateUsage
;
749 WorkingSetKBytes ws_usage
;
750 if (!GetWorkingSetKBytes(&ws_usage
))
753 *shared_bytes
= ws_usage
.shared
* 1024;
759 void ProcessMetrics::GetCommittedKBytes(CommittedKBytes
* usage
) const {
760 MEMORY_BASIC_INFORMATION mbi
= {0};
761 size_t committed_private
= 0;
762 size_t committed_mapped
= 0;
763 size_t committed_image
= 0;
764 void* base_address
= NULL
;
765 while (VirtualQueryEx(process_
, base_address
, &mbi
, sizeof(mbi
)) ==
767 if (mbi
.State
== MEM_COMMIT
) {
768 if (mbi
.Type
== MEM_PRIVATE
) {
769 committed_private
+= mbi
.RegionSize
;
770 } else if (mbi
.Type
== MEM_MAPPED
) {
771 committed_mapped
+= mbi
.RegionSize
;
772 } else if (mbi
.Type
== MEM_IMAGE
) {
773 committed_image
+= mbi
.RegionSize
;
778 void* new_base
= (static_cast<BYTE
*>(mbi
.BaseAddress
)) + mbi
.RegionSize
;
779 // Avoid infinite loop by weird MEMORY_BASIC_INFORMATION.
780 // If we query 64bit processes in a 32bit process, VirtualQueryEx()
781 // returns such data.
782 if (new_base
<= base_address
) {
788 base_address
= new_base
;
790 usage
->image
= committed_image
/ 1024;
791 usage
->mapped
= committed_mapped
/ 1024;
792 usage
->priv
= committed_private
/ 1024;
795 bool ProcessMetrics::GetWorkingSetKBytes(WorkingSetKBytes
* ws_usage
) const {
796 size_t ws_private
= 0;
797 size_t ws_shareable
= 0;
798 size_t ws_shared
= 0;
801 memset(ws_usage
, 0, sizeof(*ws_usage
));
803 DWORD number_of_entries
= 4096; // Just a guess.
804 PSAPI_WORKING_SET_INFORMATION
* buffer
= NULL
;
807 DWORD buffer_size
= sizeof(PSAPI_WORKING_SET_INFORMATION
) +
808 (number_of_entries
* sizeof(PSAPI_WORKING_SET_BLOCK
));
810 // if we can't expand the buffer, don't leak the previous
811 // contents or pass a NULL pointer to QueryWorkingSet
812 PSAPI_WORKING_SET_INFORMATION
* new_buffer
=
813 reinterpret_cast<PSAPI_WORKING_SET_INFORMATION
*>(
814 realloc(buffer
, buffer_size
));
821 // Call the function once to get number of items
822 if (QueryWorkingSet(process_
, buffer
, buffer_size
))
825 if (GetLastError() != ERROR_BAD_LENGTH
) {
830 number_of_entries
= static_cast<DWORD
>(buffer
->NumberOfEntries
);
832 // Maybe some entries are being added right now. Increase the buffer to
833 // take that into account.
834 number_of_entries
= static_cast<DWORD
>(number_of_entries
* 1.25);
836 if (--retries
== 0) {
837 free(buffer
); // If we're looping, eventually fail.
842 // On windows 2000 the function returns 1 even when the buffer is too small.
843 // The number of entries that we are going to parse is the minimum between the
844 // size we allocated and the real number of entries.
846 std::min(number_of_entries
, static_cast<DWORD
>(buffer
->NumberOfEntries
));
847 for (unsigned int i
= 0; i
< number_of_entries
; i
++) {
848 if (buffer
->WorkingSetInfo
[i
].Shared
) {
850 if (buffer
->WorkingSetInfo
[i
].ShareCount
> 1)
857 ws_usage
->priv
= ws_private
* PAGESIZE_KB
;
858 ws_usage
->shareable
= ws_shareable
* PAGESIZE_KB
;
859 ws_usage
->shared
= ws_shared
* PAGESIZE_KB
;
864 static uint64
FileTimeToUTC(const FILETIME
& ftime
) {
866 li
.LowPart
= ftime
.dwLowDateTime
;
867 li
.HighPart
= ftime
.dwHighDateTime
;
871 double ProcessMetrics::GetCPUUsage() {
873 FILETIME creation_time
;
875 FILETIME kernel_time
;
878 GetSystemTimeAsFileTime(&now
);
880 if (!GetProcessTimes(process_
, &creation_time
, &exit_time
,
881 &kernel_time
, &user_time
)) {
882 // We don't assert here because in some cases (such as in the Task Manager)
883 // we may call this function on a process that has just exited but we have
884 // not yet received the notification.
887 int64 system_time
= (FileTimeToUTC(kernel_time
) + FileTimeToUTC(user_time
)) /
889 int64 time
= FileTimeToUTC(now
);
891 if ((last_system_time_
== 0) || (last_time_
== 0)) {
892 // First call, just set the last values.
893 last_system_time_
= system_time
;
898 int64 system_time_delta
= system_time
- last_system_time_
;
899 int64 time_delta
= time
- last_time_
;
900 DCHECK_NE(0U, time_delta
);
904 // We add time_delta / 2 so the result is rounded.
905 int cpu
= static_cast<int>((system_time_delta
* 100 + time_delta
/ 2) /
908 last_system_time_
= system_time
;
914 bool ProcessMetrics::GetIOCounters(IoCounters
* io_counters
) const {
915 return GetProcessIoCounters(process_
, io_counters
) != FALSE
;
918 bool ProcessMetrics::CalculateFreeMemory(FreeMBytes
* free
) const {
919 const SIZE_T kTopAddress
= 0x7F000000;
920 const SIZE_T kMegabyte
= 1024 * 1024;
921 SIZE_T accumulated
= 0;
923 MEMORY_BASIC_INFORMATION largest
= {0};
925 while (scan
< kTopAddress
) {
926 MEMORY_BASIC_INFORMATION info
;
927 if (!::VirtualQueryEx(process_
, reinterpret_cast<void*>(scan
),
928 &info
, sizeof(info
)))
930 if (info
.State
== MEM_FREE
) {
931 accumulated
+= info
.RegionSize
;
932 if (info
.RegionSize
> largest
.RegionSize
)
935 scan
+= info
.RegionSize
;
937 free
->largest
= largest
.RegionSize
/ kMegabyte
;
938 free
->largest_ptr
= largest
.BaseAddress
;
939 free
->total
= accumulated
/ kMegabyte
;
943 bool EnableLowFragmentationHeap() {
944 HMODULE kernel32
= GetModuleHandle(L
"kernel32.dll");
945 HeapSetFn heap_set
= reinterpret_cast<HeapSetFn
>(GetProcAddress(
947 "HeapSetInformation"));
949 // On Windows 2000, the function is not exported. This is not a reason to
954 unsigned number_heaps
= GetProcessHeaps(0, NULL
);
958 // Gives us some extra space in the array in case a thread is creating heaps
959 // at the same time we're querying them.
960 static const int MARGIN
= 8;
961 scoped_ptr
<HANDLE
[]> heaps(new HANDLE
[number_heaps
+ MARGIN
]);
962 number_heaps
= GetProcessHeaps(number_heaps
+ MARGIN
, heaps
.get());
966 for (unsigned i
= 0; i
< number_heaps
; ++i
) {
968 // Don't bother with the result code. It may fails on heaps that have the
969 // HEAP_NO_SERIALIZE flag. This is expected and not a problem at all.
971 HeapCompatibilityInformation
,
978 void EnableTerminationOnHeapCorruption() {
979 // Ignore the result code. Supported on XP SP3 and Vista.
980 HeapSetInformation(NULL
, HeapEnableTerminationOnCorruption
, NULL
, 0);
983 void EnableTerminationOnOutOfMemory() {
984 std::set_new_handler(&OnNoMemory
);
987 void RaiseProcessToHighPriority() {
988 SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS
);
991 // GetPerformanceInfo is not available on WIN2K. So we'll
992 // load it on-the-fly.
993 const wchar_t kPsapiDllName
[] = L
"psapi.dll";
994 typedef BOOL (WINAPI
*GetPerformanceInfoFunction
) (
995 PPERFORMANCE_INFORMATION pPerformanceInformation
,
998 // Beware of races if called concurrently from multiple threads.
999 static BOOL
InternalGetPerformanceInfo(
1000 PPERFORMANCE_INFORMATION pPerformanceInformation
, DWORD cb
) {
1001 static GetPerformanceInfoFunction GetPerformanceInfo_func
= NULL
;
1002 if (!GetPerformanceInfo_func
) {
1003 HMODULE psapi_dll
= ::GetModuleHandle(kPsapiDllName
);
1005 GetPerformanceInfo_func
= reinterpret_cast<GetPerformanceInfoFunction
>(
1006 GetProcAddress(psapi_dll
, "GetPerformanceInfo"));
1008 if (!GetPerformanceInfo_func
) {
1009 // The function could be loaded!
1010 memset(pPerformanceInformation
, 0, cb
);
1014 return GetPerformanceInfo_func(pPerformanceInformation
, cb
);
1017 size_t GetSystemCommitCharge() {
1018 // Get the System Page Size.
1019 SYSTEM_INFO system_info
;
1020 GetSystemInfo(&system_info
);
1022 PERFORMANCE_INFORMATION info
;
1023 if (!InternalGetPerformanceInfo(&info
, sizeof(info
))) {
1024 DLOG(ERROR
) << "Failed to fetch internal performance info.";
1027 return (info
.CommitTotal
* system_info
.dwPageSize
) / 1024;