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