Bluetooth: fix header sentry comment style
[chromium-blink-merge.git] / base / process_util_win.cc
blob0dd679b38048ec7f68bcf6d7d12e949b30367a76
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"
7 #include <fcntl.h>
8 #include <io.h>
9 #include <windows.h>
10 #include <userenv.h>
11 #include <psapi.h>
13 #include <ios>
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")
32 namespace base {
34 namespace {
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
53 // process goes away.
54 const DWORD kProcessKilledExitCode = 1;
56 // HeapSetInformation function pointer.
57 typedef BOOL (WINAPI* HeapSetFn)(HANDLE, HEAP_INFORMATION_CLASS, PVOID, SIZE_T);
59 void OnNoMemory() {
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.
64 __debugbreak();
65 _exit(1);
68 class TimerExpiredTask : public win::ObjectWatcher::Delegate {
69 public:
70 explicit TimerExpiredTask(ProcessHandle process);
71 ~TimerExpiredTask();
73 void TimedOut();
75 // MessageLoop::Watcher -----------------------------------------------------
76 virtual void OnObjectSignaled(HANDLE object);
78 private:
79 void KillProcess();
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() {
94 TimedOut();
95 DCHECK(!process_) << "Make sure to close the handle.";
98 void TimerExpiredTask::TimedOut() {
99 if (process_)
100 KillProcess();
103 void TimerExpiredTask::OnObjectSignaled(HANDLE object) {
104 CloseHandle(process_);
105 process_ = NULL;
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_);
122 } // namespace
124 void RouteStdioToConsole() {
125 // Don't change anything if stdout or stderr already point to a
126 // valid stream.
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
139 // invalid.
140 if (_fileno(stdout) >= 0 || _fileno(stderr) >= 0)
141 return;
143 if (!AttachConsole(ATTACH_PARENT_PROCESS)) {
144 unsigned int result = GetLastError();
145 // Was probably already attached.
146 if (result == ERROR_ACCESS_DENIED)
147 return;
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)
151 return;
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.
155 AllocConsole();
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),
194 &instance)) {
195 NOTREACHED();
197 return instance;
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 |
206 SYNCHRONIZE,
207 FALSE, pid);
209 if (result == NULL)
210 return false;
212 *handle = result;
213 return true;
216 bool OpenPrivilegedProcessHandle(ProcessId pid, ProcessHandle* handle) {
217 ProcessHandle result = OpenProcess(PROCESS_DUP_HANDLE |
218 PROCESS_TERMINATE |
219 PROCESS_QUERY_INFORMATION |
220 PROCESS_VM_READ |
221 SYNCHRONIZE,
222 FALSE, pid);
224 if (result == NULL)
225 return false;
227 *handle = result;
228 return true;
231 bool OpenProcessHandleWithAccess(ProcessId pid,
232 uint32 access_flags,
233 ProcessHandle* handle) {
234 ProcessHandle result = OpenProcess(access_flags, FALSE, pid);
236 if (result == NULL)
237 return false;
239 *handle = result;
240 return true;
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,
253 false, 0)) {
254 DWORD id = GetProcessId(process_with_query_rights);
255 CloseHandle(process_with_query_rights);
256 return id;
259 // We're screwed.
260 NOTREACHED();
261 return 0;
264 bool GetProcessIntegrityLevel(ProcessHandle process, IntegrityLevel *level) {
265 if (!level)
266 return false;
268 if (win::GetVersion() < base::win::VERSION_VISTA)
269 return false;
271 HANDLE process_token;
272 if (!OpenProcessToken(process, TOKEN_QUERY | TOKEN_QUERY_SOURCE,
273 &process_token))
274 return false;
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)
282 return false;
284 scoped_ptr<char[]> token_label_bytes(new char[token_info_length]);
285 if (!token_label_bytes.get())
286 return false;
288 TOKEN_MANDATORY_LABEL* token_label =
289 reinterpret_cast<TOKEN_MANDATORY_LABEL*>(token_label_bytes.get());
290 if (!token_label)
291 return false;
293 if (!GetTokenInformation(process_token, TokenIntegrityLevel, token_label,
294 token_info_length, &token_info_length))
295 return false;
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;
307 } else {
308 NOTREACHED();
309 return false;
312 return true;
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;
336 DWORD flags = 0;
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)) {
357 DPLOG(ERROR);
358 return false;
361 BOOL launched =
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);
368 if (!launched) {
369 DPLOG(ERROR);
370 return false;
372 } else {
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())) {
377 DPLOG(ERROR);
378 return false;
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);
387 return false;
390 ResumeThread(process_info.thread_handle());
393 if (options.wait)
394 WaitForSingleObject(process_info.process_handle(), INFINITE);
396 // If the caller wants the process handle, we won't close it.
397 if (process_handle)
398 *process_handle = process_info.TakeProcessHandle();
400 return true;
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(
414 job_object,
415 JobObjectExtendedLimitInformation,
416 &limit_info,
417 sizeof(limit_info));
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
426 process_id);
427 if (!process) {
428 DLOG_GETLASTERROR(ERROR) << "Unable to open process " << process_id;
429 return false;
431 bool ret = KillProcess(process, exit_code, wait);
432 CloseHandle(process);
433 return ret;
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";
449 return false;
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";
459 return false;
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],
477 NULL, NULL,
478 TRUE, // Handles are inherited.
479 0, NULL, NULL, &start_info, proc_info.Receive())) {
480 NOTREACHED() << "Failed to start process";
481 return false;
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];
492 for (;;) {
493 DWORD bytes_read = 0;
494 BOOL success = ReadFile(out_read, buffer, kBufferSize, &bytes_read, NULL);
495 if (!success || bytes_read == 0)
496 break;
497 output->append(buffer, bytes_read);
500 // Let's wait for the process to finish.
501 WaitForSingleObject(proc_info.process_handle(), INFINITE);
503 return true;
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";
515 return result;
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";
523 if (exit_code) {
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
536 // code.
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) {
542 if (exit_code)
543 *exit_code = wait_result;
544 return TERMINATION_STATUS_STILL_RUNNING;
547 if (wait_result == WAIT_FAILED) {
548 DLOG_GETLASTERROR(ERROR) << "WaitForSingleObject() failed";
549 } else {
550 DCHECK_EQ(WAIT_OBJECT_0, wait_result);
552 // Strange, the process used 0x103 (STILL_ACTIVE) as exit code.
553 NOTREACHED();
556 return TERMINATION_STATUS_ABNORMAL_TERMINATION;
559 if (exit_code)
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;
570 default:
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);
580 return success;
583 bool WaitForExitCodeWithTimeout(ProcessHandle handle, int* exit_code,
584 base::TimeDelta timeout) {
585 if (::WaitForSingleObject(handle, timeout.InMilliseconds()) != WAIT_OBJECT_0)
586 return false;
587 DWORD temp_code; // Don't clobber out-parameters in case of failure.
588 if (!::GetExitCodeProcess(handle, &temp_code))
589 return false;
591 *exit_code = temp_code;
592 return true;
595 ProcessIterator::ProcessIterator(const ProcessFilter* filter)
596 : started_iteration_(false),
597 filter_(filter) {
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() {
622 // Case insensitive.
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;
631 bool result = true;
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,
639 FALSE,
640 entry->th32ProcessID);
641 DWORD wait_result = WaitForSingleObject(process, remaining_wait);
642 CloseHandle(process);
643 result = result && (wait_result == WAIT_OBJECT_0);
646 return result;
649 bool WaitForSingleProcess(ProcessHandle handle, base::TimeDelta wait) {
650 int exit_code;
651 if (!WaitForExitCodeWithTimeout(handle, &exit_code, wait))
652 return false;
653 return exit_code == 0;
656 bool CleanupProcesses(const FilePath::StringType& executable_name,
657 base::TimeDelta wait,
658 int exit_code,
659 const ProcessFilter* filter) {
660 bool exited_cleanly = WaitForProcessesToExit(executable_name, wait, filter);
661 if (!exited_cleanly)
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);
672 return;
675 MessageLoop::current()->PostDelayedTask(
676 FROM_HERE,
677 base::Bind(&TimerExpiredTask::TimedOut,
678 base::Owned(new TimerExpiredTask(process))),
679 base::TimeDelta::FromMilliseconds(kWaitInterval));
682 ///////////////////////////////////////////////////////////////////////////////
683 // ProcesMetrics
685 ProcessMetrics::ProcessMetrics(ProcessHandle process)
686 : process_(process),
687 processor_count_(base::SysInfo::NumberOfProcessors()),
688 last_time_(0),
689 last_system_time_(0) {
692 // static
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;
704 return 0;
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;
713 return 0;
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;
722 return 0;
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;
731 return 0;
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;
741 if (private_bytes &&
742 GetProcessMemoryInfo(process_,
743 reinterpret_cast<PROCESS_MEMORY_COUNTERS*>(&pmcx),
744 sizeof(pmcx))) {
745 *private_bytes = pmcx.PrivateUsage;
748 if (shared_bytes) {
749 WorkingSetKBytes ws_usage;
750 if (!GetWorkingSetKBytes(&ws_usage))
751 return false;
753 *shared_bytes = ws_usage.shared * 1024;
756 return true;
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)) ==
766 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;
774 } else {
775 NOTREACHED();
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) {
783 usage->image = 0;
784 usage->mapped = 0;
785 usage->priv = 0;
786 return;
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;
800 DCHECK(ws_usage);
801 memset(ws_usage, 0, sizeof(*ws_usage));
803 DWORD number_of_entries = 4096; // Just a guess.
804 PSAPI_WORKING_SET_INFORMATION* buffer = NULL;
805 int retries = 5;
806 for (;;) {
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));
815 if (!new_buffer) {
816 free(buffer);
817 return false;
819 buffer = new_buffer;
821 // Call the function once to get number of items
822 if (QueryWorkingSet(process_, buffer, buffer_size))
823 break; // Success
825 if (GetLastError() != ERROR_BAD_LENGTH) {
826 free(buffer);
827 return false;
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.
838 return false;
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.
845 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) {
849 ws_shareable++;
850 if (buffer->WorkingSetInfo[i].ShareCount > 1)
851 ws_shared++;
852 } else {
853 ws_private++;
857 ws_usage->priv = ws_private * PAGESIZE_KB;
858 ws_usage->shareable = ws_shareable * PAGESIZE_KB;
859 ws_usage->shared = ws_shared * PAGESIZE_KB;
860 free(buffer);
861 return true;
864 static uint64 FileTimeToUTC(const FILETIME& ftime) {
865 LARGE_INTEGER li;
866 li.LowPart = ftime.dwLowDateTime;
867 li.HighPart = ftime.dwHighDateTime;
868 return li.QuadPart;
871 double ProcessMetrics::GetCPUUsage() {
872 FILETIME now;
873 FILETIME creation_time;
874 FILETIME exit_time;
875 FILETIME kernel_time;
876 FILETIME user_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.
885 return 0;
887 int64 system_time = (FileTimeToUTC(kernel_time) + FileTimeToUTC(user_time)) /
888 processor_count_;
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;
894 last_time_ = time;
895 return 0;
898 int64 system_time_delta = system_time - last_system_time_;
899 int64 time_delta = time - last_time_;
900 DCHECK_NE(0U, time_delta);
901 if (time_delta == 0)
902 return 0;
904 // We add time_delta / 2 so the result is rounded.
905 int cpu = static_cast<int>((system_time_delta * 100 + time_delta / 2) /
906 time_delta);
908 last_system_time_ = system_time;
909 last_time_ = time;
911 return cpu;
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};
924 UINT_PTR scan = 0;
925 while (scan < kTopAddress) {
926 MEMORY_BASIC_INFORMATION info;
927 if (!::VirtualQueryEx(process_, reinterpret_cast<void*>(scan),
928 &info, sizeof(info)))
929 return false;
930 if (info.State == MEM_FREE) {
931 accumulated += info.RegionSize;
932 if (info.RegionSize > largest.RegionSize)
933 largest = info;
935 scan += info.RegionSize;
937 free->largest = largest.RegionSize / kMegabyte;
938 free->largest_ptr = largest.BaseAddress;
939 free->total = accumulated / kMegabyte;
940 return true;
943 bool EnableLowFragmentationHeap() {
944 HMODULE kernel32 = GetModuleHandle(L"kernel32.dll");
945 HeapSetFn heap_set = reinterpret_cast<HeapSetFn>(GetProcAddress(
946 kernel32,
947 "HeapSetInformation"));
949 // On Windows 2000, the function is not exported. This is not a reason to
950 // fail.
951 if (!heap_set)
952 return true;
954 unsigned number_heaps = GetProcessHeaps(0, NULL);
955 if (!number_heaps)
956 return false;
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());
963 if (!number_heaps)
964 return false;
966 for (unsigned i = 0; i < number_heaps; ++i) {
967 ULONG lfh_flag = 2;
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.
970 heap_set(heaps[i],
971 HeapCompatibilityInformation,
972 &lfh_flag,
973 sizeof(lfh_flag));
975 return true;
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,
996 DWORD cb);
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);
1004 if (psapi_dll)
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);
1011 return FALSE;
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.";
1025 return 0;
1027 return (info.CommitTotal * system_info.dwPageSize) / 1024;
1030 } // namespace base