Move functions for controlling Caps Lock to CapsLockDelegate from SystemTrayDelegate.
[chromium-blink-merge.git] / base / process_util_win.cc
blob8765e50c3b1e154f41f432c9f3ff1417aec24b0e
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 // 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;
72 void OnNoMemory() {
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.
77 __debugbreak();
78 _exit(1);
81 class TimerExpiredTask : public win::ObjectWatcher::Delegate {
82 public:
83 explicit TimerExpiredTask(ProcessHandle process);
84 ~TimerExpiredTask();
86 void TimedOut();
88 // MessageLoop::Watcher -----------------------------------------------------
89 virtual void OnObjectSignaled(HANDLE object);
91 private:
92 void KillProcess();
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() {
107 TimedOut();
108 DCHECK(!process_) << "Make sure to close the handle.";
111 void TimerExpiredTask::TimedOut() {
112 if (process_)
113 KillProcess();
116 void TimerExpiredTask::OnObjectSignaled(HANDLE object) {
117 CloseHandle(process_);
118 process_ = NULL;
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_);
135 } // namespace
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)
142 return;
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)
146 return;
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.
150 AllocConsole();
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),
175 &instance)) {
176 NOTREACHED();
178 return instance;
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,
186 FALSE, pid);
188 if (result == NULL)
189 return false;
191 *handle = result;
192 return true;
195 bool OpenPrivilegedProcessHandle(ProcessId pid, ProcessHandle* handle) {
196 ProcessHandle result = OpenProcess(PROCESS_DUP_HANDLE |
197 PROCESS_TERMINATE |
198 PROCESS_QUERY_INFORMATION |
199 PROCESS_VM_READ |
200 SYNCHRONIZE,
201 FALSE, pid);
203 if (result == NULL)
204 return false;
206 *handle = result;
207 return true;
210 bool OpenProcessHandleWithAccess(ProcessId pid,
211 uint32 access_flags,
212 ProcessHandle* handle) {
213 ProcessHandle result = OpenProcess(access_flags, FALSE, pid);
215 if (result == NULL)
216 return false;
218 *handle = result;
219 return true;
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,
232 false, 0)) {
233 DWORD id = GetProcessId(process_with_query_rights);
234 CloseHandle(process_with_query_rights);
235 return id;
238 // We're screwed.
239 NOTREACHED();
240 return 0;
243 bool GetProcessIntegrityLevel(ProcessHandle process, IntegrityLevel *level) {
244 if (!level)
245 return false;
247 if (win::GetVersion() < base::win::VERSION_VISTA)
248 return false;
250 HANDLE process_token;
251 if (!OpenProcessToken(process, TOKEN_QUERY | TOKEN_QUERY_SOURCE,
252 &process_token))
253 return false;
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)
261 return false;
263 scoped_array<char> token_label_bytes(new char[token_info_length]);
264 if (!token_label_bytes.get())
265 return false;
267 TOKEN_MANDATORY_LABEL* token_label =
268 reinterpret_cast<TOKEN_MANDATORY_LABEL*>(token_label_bytes.get());
269 if (!token_label)
270 return false;
272 if (!GetTokenInformation(process_token, TokenIntegrityLevel, token_label,
273 token_info_length, &token_info_length))
274 return false;
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;
286 } else {
287 NOTREACHED();
288 return false;
291 return true;
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;
304 DWORD flags = 0;
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))
322 return false;
324 BOOL launched =
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);
331 if (!launched)
332 return false;
333 } else {
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())) {
338 return false;
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);
347 return false;
350 ResumeThread(process_info.thread_handle());
353 if (options.wait)
354 WaitForSingleObject(process_info.process_handle(), INFINITE);
356 // If the caller wants the process handle, we won't close it.
357 if (process_handle)
358 *process_handle = process_info.TakeProcessHandle();
360 return true;
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(
374 job_object,
375 JobObjectExtendedLimitInformation,
376 &limit_info,
377 sizeof(limit_info));
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
386 process_id);
387 if (!process) {
388 DLOG(ERROR) << "Unable to open process " << process_id << " : "
389 << GetLastError();
390 return false;
392 bool ret = KillProcess(process, exit_code, wait);
393 CloseHandle(process);
394 return ret;
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";
410 return false;
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";
420 return false;
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],
438 NULL, NULL,
439 TRUE, // Handles are inherited.
440 0, NULL, NULL, &start_info, proc_info.Receive())) {
441 NOTREACHED() << "Failed to start process";
442 return false;
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];
453 for (;;) {
454 DWORD bytes_read = 0;
455 BOOL success = ReadFile(out_read, buffer, kBufferSize, &bytes_read, NULL);
456 if (!success || bytes_read == 0)
457 break;
458 output->append(buffer, bytes_read);
461 // Let's wait for the process to finish.
462 WaitForSingleObject(proc_info.process_handle(), INFINITE);
464 return true;
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();
476 return result;
479 TerminationStatus GetTerminationStatus(ProcessHandle handle, int* exit_code) {
480 DWORD tmp_exit_code = 0;
482 if (!::GetExitCodeProcess(handle, &tmp_exit_code)) {
483 NOTREACHED();
484 if (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
497 // code.
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) {
503 if (exit_code)
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.
511 NOTREACHED();
513 return TERMINATION_STATUS_ABNORMAL_TERMINATION;
516 if (exit_code)
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;
527 default:
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);
537 return success;
540 bool WaitForExitCodeWithTimeout(ProcessHandle handle, int* exit_code,
541 base::TimeDelta timeout) {
542 if (::WaitForSingleObject(handle, timeout.InMilliseconds()) != WAIT_OBJECT_0)
543 return false;
544 DWORD temp_code; // Don't clobber out-parameters in case of failure.
545 if (!::GetExitCodeProcess(handle, &temp_code))
546 return false;
548 *exit_code = temp_code;
549 return true;
552 ProcessIterator::ProcessIterator(const ProcessFilter* filter)
553 : started_iteration_(false),
554 filter_(filter) {
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() {
579 // Case insensitive.
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;
588 bool result = true;
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,
596 FALSE,
597 entry->th32ProcessID);
598 DWORD wait_result = WaitForSingleObject(process, remaining_wait);
599 CloseHandle(process);
600 result = result && (wait_result == WAIT_OBJECT_0);
603 return result;
606 bool WaitForSingleProcess(ProcessHandle handle, base::TimeDelta wait) {
607 int exit_code;
608 if (!WaitForExitCodeWithTimeout(handle, &exit_code, wait))
609 return false;
610 return exit_code == 0;
613 bool CleanupProcesses(const FilePath::StringType& executable_name,
614 base::TimeDelta wait,
615 int exit_code,
616 const ProcessFilter* filter) {
617 bool exited_cleanly = WaitForProcessesToExit(executable_name, wait, filter);
618 if (!exited_cleanly)
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);
629 return;
632 MessageLoop::current()->PostDelayedTask(
633 FROM_HERE,
634 base::Bind(&TimerExpiredTask::TimedOut,
635 base::Owned(new TimerExpiredTask(process))),
636 base::TimeDelta::FromMilliseconds(kWaitInterval));
639 ///////////////////////////////////////////////////////////////////////////////
640 // ProcesMetrics
642 ProcessMetrics::ProcessMetrics(ProcessHandle process)
643 : process_(process),
644 processor_count_(base::SysInfo::NumberOfProcessors()),
645 last_time_(0),
646 last_system_time_(0) {
649 // static
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;
661 return 0;
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;
670 return 0;
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;
679 return 0;
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;
688 return 0;
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;
698 if (private_bytes &&
699 GetProcessMemoryInfo(process_,
700 reinterpret_cast<PROCESS_MEMORY_COUNTERS*>(&pmcx),
701 sizeof(pmcx))) {
702 *private_bytes = pmcx.PrivateUsage;
705 if (shared_bytes) {
706 WorkingSetKBytes ws_usage;
707 if (!GetWorkingSetKBytes(&ws_usage))
708 return false;
710 *shared_bytes = ws_usage.shared * 1024;
713 return true;
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)) ==
723 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;
731 } else {
732 NOTREACHED();
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) {
740 usage->image = 0;
741 usage->mapped = 0;
742 usage->priv = 0;
743 return;
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;
757 DCHECK(ws_usage);
758 memset(ws_usage, 0, sizeof(*ws_usage));
760 DWORD number_of_entries = 4096; // Just a guess.
761 PSAPI_WORKING_SET_INFORMATION* buffer = NULL;
762 int retries = 5;
763 for (;;) {
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));
772 if (!new_buffer) {
773 free(buffer);
774 return false;
776 buffer = new_buffer;
778 // Call the function once to get number of items
779 if (QueryWorkingSet(process_, buffer, buffer_size))
780 break; // Success
782 if (GetLastError() != ERROR_BAD_LENGTH) {
783 free(buffer);
784 return false;
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.
795 return false;
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.
802 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) {
806 ws_shareable++;
807 if (buffer->WorkingSetInfo[i].ShareCount > 1)
808 ws_shared++;
809 } else {
810 ws_private++;
814 ws_usage->priv = ws_private * PAGESIZE_KB;
815 ws_usage->shareable = ws_shareable * PAGESIZE_KB;
816 ws_usage->shared = ws_shared * PAGESIZE_KB;
817 free(buffer);
818 return true;
821 static uint64 FileTimeToUTC(const FILETIME& ftime) {
822 LARGE_INTEGER li;
823 li.LowPart = ftime.dwLowDateTime;
824 li.HighPart = ftime.dwHighDateTime;
825 return li.QuadPart;
828 double ProcessMetrics::GetCPUUsage() {
829 FILETIME now;
830 FILETIME creation_time;
831 FILETIME exit_time;
832 FILETIME kernel_time;
833 FILETIME user_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.
842 return 0;
844 int64 system_time = (FileTimeToUTC(kernel_time) + FileTimeToUTC(user_time)) /
845 processor_count_;
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;
851 last_time_ = time;
852 return 0;
855 int64 system_time_delta = system_time - last_system_time_;
856 int64 time_delta = time - last_time_;
857 DCHECK_NE(0U, time_delta);
858 if (time_delta == 0)
859 return 0;
861 // We add time_delta / 2 so the result is rounded.
862 int cpu = static_cast<int>((system_time_delta * 100 + time_delta / 2) /
863 time_delta);
865 last_system_time_ = system_time;
866 last_time_ = time;
868 return cpu;
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};
881 UINT_PTR scan = 0;
882 while (scan < kTopAddress) {
883 MEMORY_BASIC_INFORMATION info;
884 if (!::VirtualQueryEx(process_, reinterpret_cast<void*>(scan),
885 &info, sizeof(info)))
886 return false;
887 if (info.State == MEM_FREE) {
888 accumulated += info.RegionSize;
889 UINT_PTR end = scan + info.RegionSize;
890 if (info.RegionSize > largest.RegionSize)
891 largest = info;
893 scan += info.RegionSize;
895 free->largest = largest.RegionSize / kMegabyte;
896 free->largest_ptr = largest.BaseAddress;
897 free->total = accumulated / kMegabyte;
898 return true;
901 bool EnableLowFragmentationHeap() {
902 HMODULE kernel32 = GetModuleHandle(L"kernel32.dll");
903 HeapSetFn heap_set = reinterpret_cast<HeapSetFn>(GetProcAddress(
904 kernel32,
905 "HeapSetInformation"));
907 // On Windows 2000, the function is not exported. This is not a reason to
908 // fail.
909 if (!heap_set)
910 return true;
912 unsigned number_heaps = GetProcessHeaps(0, NULL);
913 if (!number_heaps)
914 return false;
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());
921 if (!number_heaps)
922 return false;
924 for (unsigned i = 0; i < number_heaps; ++i) {
925 ULONG lfh_flag = 2;
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.
928 heap_set(heaps[i],
929 HeapCompatibilityInformation,
930 &lfh_flag,
931 sizeof(lfh_flag));
933 return true;
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();
950 return true;
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,
962 DWORD cb);
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);
970 if (psapi_dll)
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);
977 return FALSE;
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.";
991 return 0;
993 return (info.CommitTotal * system_info.dwPageSize) / 1024;
996 } // namespace base