Extract SIGPIPE ignoring code to a common place.
[chromium-blink-merge.git] / base / process_util_win.cc
bloba1a55ea6e4b73abd8a571f263aa66c24c9cf01fd
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 DWORD flags = 0;
298 if (options.job_handle) {
299 flags |= CREATE_SUSPENDED;
301 // If this code is run under a debugger, the launched process is
302 // automatically associated with a job object created by the debugger.
303 // The CREATE_BREAKAWAY_FROM_JOB flag is used to prevent this.
304 flags |= CREATE_BREAKAWAY_FROM_JOB;
307 if (options.force_breakaway_from_job_)
308 flags |= CREATE_BREAKAWAY_FROM_JOB;
310 base::win::ScopedProcessInformation process_info;
312 if (options.as_user) {
313 flags |= CREATE_UNICODE_ENVIRONMENT;
314 void* enviroment_block = NULL;
316 if (!CreateEnvironmentBlock(&enviroment_block, options.as_user, FALSE))
317 return false;
319 BOOL launched =
320 CreateProcessAsUser(options.as_user, NULL,
321 const_cast<wchar_t*>(cmdline.c_str()),
322 NULL, NULL, options.inherit_handles, flags,
323 enviroment_block, NULL, &startup_info,
324 process_info.Receive());
325 DestroyEnvironmentBlock(enviroment_block);
326 if (!launched)
327 return false;
328 } else {
329 if (!CreateProcess(NULL,
330 const_cast<wchar_t*>(cmdline.c_str()), NULL, NULL,
331 options.inherit_handles, flags, NULL, NULL,
332 &startup_info, process_info.Receive())) {
333 return false;
337 if (options.job_handle) {
338 if (0 == AssignProcessToJobObject(options.job_handle,
339 process_info.process_handle())) {
340 DLOG(ERROR) << "Could not AssignProcessToObject.";
341 KillProcess(process_info.process_handle(), kProcessKilledExitCode, true);
342 return false;
345 ResumeThread(process_info.thread_handle());
348 if (options.wait)
349 WaitForSingleObject(process_info.process_handle(), INFINITE);
351 // If the caller wants the process handle, we won't close it.
352 if (process_handle)
353 *process_handle = process_info.TakeProcessHandle();
355 return true;
358 bool LaunchProcess(const CommandLine& cmdline,
359 const LaunchOptions& options,
360 ProcessHandle* process_handle) {
361 return LaunchProcess(cmdline.GetCommandLineString(), options, process_handle);
364 bool SetJobObjectAsKillOnJobClose(HANDLE job_object) {
365 JOBOBJECT_EXTENDED_LIMIT_INFORMATION limit_info = {0};
366 limit_info.BasicLimitInformation.LimitFlags =
367 JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
368 return 0 != SetInformationJobObject(
369 job_object,
370 JobObjectExtendedLimitInformation,
371 &limit_info,
372 sizeof(limit_info));
375 // Attempts to kill the process identified by the given process
376 // entry structure, giving it the specified exit code.
377 // Returns true if this is successful, false otherwise.
378 bool KillProcessById(ProcessId process_id, int exit_code, bool wait) {
379 HANDLE process = OpenProcess(PROCESS_TERMINATE | SYNCHRONIZE,
380 FALSE, // Don't inherit handle
381 process_id);
382 if (!process) {
383 DLOG(ERROR) << "Unable to open process " << process_id << " : "
384 << GetLastError();
385 return false;
387 bool ret = KillProcess(process, exit_code, wait);
388 CloseHandle(process);
389 return ret;
392 bool GetAppOutput(const CommandLine& cl, std::string* output) {
393 HANDLE out_read = NULL;
394 HANDLE out_write = NULL;
396 SECURITY_ATTRIBUTES sa_attr;
397 // Set the bInheritHandle flag so pipe handles are inherited.
398 sa_attr.nLength = sizeof(SECURITY_ATTRIBUTES);
399 sa_attr.bInheritHandle = TRUE;
400 sa_attr.lpSecurityDescriptor = NULL;
402 // Create the pipe for the child process's STDOUT.
403 if (!CreatePipe(&out_read, &out_write, &sa_attr, 0)) {
404 NOTREACHED() << "Failed to create pipe";
405 return false;
408 // Ensure we don't leak the handles.
409 win::ScopedHandle scoped_out_read(out_read);
410 win::ScopedHandle scoped_out_write(out_write);
412 // Ensure the read handle to the pipe for STDOUT is not inherited.
413 if (!SetHandleInformation(out_read, HANDLE_FLAG_INHERIT, 0)) {
414 NOTREACHED() << "Failed to disabled pipe inheritance";
415 return false;
418 FilePath::StringType writable_command_line_string(cl.GetCommandLineString());
420 base::win::ScopedProcessInformation proc_info;
421 STARTUPINFO start_info = { 0 };
423 start_info.cb = sizeof(STARTUPINFO);
424 start_info.hStdOutput = out_write;
425 // Keep the normal stdin and stderr.
426 start_info.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
427 start_info.hStdError = GetStdHandle(STD_ERROR_HANDLE);
428 start_info.dwFlags |= STARTF_USESTDHANDLES;
430 // Create the child process.
431 if (!CreateProcess(NULL,
432 &writable_command_line_string[0],
433 NULL, NULL,
434 TRUE, // Handles are inherited.
435 0, NULL, NULL, &start_info, proc_info.Receive())) {
436 NOTREACHED() << "Failed to start process";
437 return false;
440 // Close our writing end of pipe now. Otherwise later read would not be able
441 // to detect end of child's output.
442 scoped_out_write.Close();
444 // Read output from the child process's pipe for STDOUT
445 const int kBufferSize = 1024;
446 char buffer[kBufferSize];
448 for (;;) {
449 DWORD bytes_read = 0;
450 BOOL success = ReadFile(out_read, buffer, kBufferSize, &bytes_read, NULL);
451 if (!success || bytes_read == 0)
452 break;
453 output->append(buffer, bytes_read);
456 // Let's wait for the process to finish.
457 WaitForSingleObject(proc_info.process_handle(), INFINITE);
459 return true;
462 bool KillProcess(ProcessHandle process, int exit_code, bool wait) {
463 bool result = (TerminateProcess(process, exit_code) != FALSE);
464 if (result && wait) {
465 // The process may not end immediately due to pending I/O
466 if (WAIT_OBJECT_0 != WaitForSingleObject(process, 60 * 1000))
467 DLOG(ERROR) << "Error waiting for process exit: " << GetLastError();
468 } else if (!result) {
469 DLOG(ERROR) << "Unable to terminate process: " << GetLastError();
471 return result;
474 TerminationStatus GetTerminationStatus(ProcessHandle handle, int* exit_code) {
475 DWORD tmp_exit_code = 0;
477 if (!::GetExitCodeProcess(handle, &tmp_exit_code)) {
478 NOTREACHED();
479 if (exit_code) {
480 // This really is a random number. We haven't received any
481 // information about the exit code, presumably because this
482 // process doesn't have permission to get the exit code, or
483 // because of some other cause for GetExitCodeProcess to fail
484 // (MSDN docs don't give the possible failure error codes for
485 // this function, so it could be anything). But we don't want
486 // to leave exit_code uninitialized, since that could cause
487 // random interpretations of the exit code. So we assume it
488 // terminated "normally" in this case.
489 *exit_code = kNormalTerminationExitCode;
491 // Assume the child has exited normally if we can't get the exit
492 // code.
493 return TERMINATION_STATUS_NORMAL_TERMINATION;
495 if (tmp_exit_code == STILL_ACTIVE) {
496 DWORD wait_result = WaitForSingleObject(handle, 0);
497 if (wait_result == WAIT_TIMEOUT) {
498 if (exit_code)
499 *exit_code = wait_result;
500 return TERMINATION_STATUS_STILL_RUNNING;
503 DCHECK_EQ(WAIT_OBJECT_0, wait_result);
505 // Strange, the process used 0x103 (STILL_ACTIVE) as exit code.
506 NOTREACHED();
508 return TERMINATION_STATUS_ABNORMAL_TERMINATION;
511 if (exit_code)
512 *exit_code = tmp_exit_code;
514 switch (tmp_exit_code) {
515 case kNormalTerminationExitCode:
516 return TERMINATION_STATUS_NORMAL_TERMINATION;
517 case kDebuggerInactiveExitCode: // STATUS_DEBUGGER_INACTIVE.
518 case kKeyboardInterruptExitCode: // Control-C/end session.
519 case kDebuggerTerminatedExitCode: // Debugger terminated process.
520 case kProcessKilledExitCode: // Task manager kill.
521 return TERMINATION_STATUS_PROCESS_WAS_KILLED;
522 default:
523 // All other exit codes indicate crashes.
524 return TERMINATION_STATUS_PROCESS_CRASHED;
528 bool WaitForExitCode(ProcessHandle handle, int* exit_code) {
529 bool success = WaitForExitCodeWithTimeout(
530 handle, exit_code, base::TimeDelta::FromMilliseconds(INFINITE));
531 CloseProcessHandle(handle);
532 return success;
535 bool WaitForExitCodeWithTimeout(ProcessHandle handle, int* exit_code,
536 base::TimeDelta timeout) {
537 if (::WaitForSingleObject(handle, timeout.InMilliseconds()) != WAIT_OBJECT_0)
538 return false;
539 DWORD temp_code; // Don't clobber out-parameters in case of failure.
540 if (!::GetExitCodeProcess(handle, &temp_code))
541 return false;
543 *exit_code = temp_code;
544 return true;
547 ProcessIterator::ProcessIterator(const ProcessFilter* filter)
548 : started_iteration_(false),
549 filter_(filter) {
550 snapshot_ = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
553 ProcessIterator::~ProcessIterator() {
554 CloseHandle(snapshot_);
557 bool ProcessIterator::CheckForNextProcess() {
558 InitProcessEntry(&entry_);
560 if (!started_iteration_) {
561 started_iteration_ = true;
562 return !!Process32First(snapshot_, &entry_);
565 return !!Process32Next(snapshot_, &entry_);
568 void ProcessIterator::InitProcessEntry(ProcessEntry* entry) {
569 memset(entry, 0, sizeof(*entry));
570 entry->dwSize = sizeof(*entry);
573 bool NamedProcessIterator::IncludeEntry() {
574 // Case insensitive.
575 return _wcsicmp(executable_name_.c_str(), entry().exe_file()) == 0 &&
576 ProcessIterator::IncludeEntry();
579 bool WaitForProcessesToExit(const FilePath::StringType& executable_name,
580 base::TimeDelta wait,
581 const ProcessFilter* filter) {
582 const ProcessEntry* entry;
583 bool result = true;
584 DWORD start_time = GetTickCount();
586 NamedProcessIterator iter(executable_name, filter);
587 while ((entry = iter.NextProcessEntry())) {
588 DWORD remaining_wait = std::max<int64>(
589 0, wait.InMilliseconds() - (GetTickCount() - start_time));
590 HANDLE process = OpenProcess(SYNCHRONIZE,
591 FALSE,
592 entry->th32ProcessID);
593 DWORD wait_result = WaitForSingleObject(process, remaining_wait);
594 CloseHandle(process);
595 result = result && (wait_result == WAIT_OBJECT_0);
598 return result;
601 bool WaitForSingleProcess(ProcessHandle handle, base::TimeDelta wait) {
602 int exit_code;
603 if (!WaitForExitCodeWithTimeout(handle, &exit_code, wait))
604 return false;
605 return exit_code == 0;
608 bool CleanupProcesses(const FilePath::StringType& executable_name,
609 base::TimeDelta wait,
610 int exit_code,
611 const ProcessFilter* filter) {
612 bool exited_cleanly = WaitForProcessesToExit(executable_name, wait, filter);
613 if (!exited_cleanly)
614 KillProcesses(executable_name, exit_code, filter);
615 return exited_cleanly;
618 void EnsureProcessTerminated(ProcessHandle process) {
619 DCHECK(process != GetCurrentProcess());
621 // If already signaled, then we are done!
622 if (WaitForSingleObject(process, 0) == WAIT_OBJECT_0) {
623 CloseHandle(process);
624 return;
627 MessageLoop::current()->PostDelayedTask(
628 FROM_HERE,
629 base::Bind(&TimerExpiredTask::TimedOut,
630 base::Owned(new TimerExpiredTask(process))),
631 base::TimeDelta::FromMilliseconds(kWaitInterval));
634 ///////////////////////////////////////////////////////////////////////////////
635 // ProcesMetrics
637 ProcessMetrics::ProcessMetrics(ProcessHandle process)
638 : process_(process),
639 processor_count_(base::SysInfo::NumberOfProcessors()),
640 last_time_(0),
641 last_system_time_(0) {
644 // static
645 ProcessMetrics* ProcessMetrics::CreateProcessMetrics(ProcessHandle process) {
646 return new ProcessMetrics(process);
649 ProcessMetrics::~ProcessMetrics() { }
651 size_t ProcessMetrics::GetPagefileUsage() const {
652 PROCESS_MEMORY_COUNTERS pmc;
653 if (GetProcessMemoryInfo(process_, &pmc, sizeof(pmc))) {
654 return pmc.PagefileUsage;
656 return 0;
659 // Returns the peak space allocated for the pagefile, in bytes.
660 size_t ProcessMetrics::GetPeakPagefileUsage() const {
661 PROCESS_MEMORY_COUNTERS pmc;
662 if (GetProcessMemoryInfo(process_, &pmc, sizeof(pmc))) {
663 return pmc.PeakPagefileUsage;
665 return 0;
668 // Returns the current working set size, in bytes.
669 size_t ProcessMetrics::GetWorkingSetSize() const {
670 PROCESS_MEMORY_COUNTERS pmc;
671 if (GetProcessMemoryInfo(process_, &pmc, sizeof(pmc))) {
672 return pmc.WorkingSetSize;
674 return 0;
677 // Returns the peak working set size, in bytes.
678 size_t ProcessMetrics::GetPeakWorkingSetSize() const {
679 PROCESS_MEMORY_COUNTERS pmc;
680 if (GetProcessMemoryInfo(process_, &pmc, sizeof(pmc))) {
681 return pmc.PeakWorkingSetSize;
683 return 0;
686 bool ProcessMetrics::GetMemoryBytes(size_t* private_bytes,
687 size_t* shared_bytes) {
688 // PROCESS_MEMORY_COUNTERS_EX is not supported until XP SP2.
689 // GetProcessMemoryInfo() will simply fail on prior OS. So the requested
690 // information is simply not available. Hence, we will return 0 on unsupported
691 // OSes. Unlike most Win32 API, we don't need to initialize the "cb" member.
692 PROCESS_MEMORY_COUNTERS_EX pmcx;
693 if (private_bytes &&
694 GetProcessMemoryInfo(process_,
695 reinterpret_cast<PROCESS_MEMORY_COUNTERS*>(&pmcx),
696 sizeof(pmcx))) {
697 *private_bytes = pmcx.PrivateUsage;
700 if (shared_bytes) {
701 WorkingSetKBytes ws_usage;
702 if (!GetWorkingSetKBytes(&ws_usage))
703 return false;
705 *shared_bytes = ws_usage.shared * 1024;
708 return true;
711 void ProcessMetrics::GetCommittedKBytes(CommittedKBytes* usage) const {
712 MEMORY_BASIC_INFORMATION mbi = {0};
713 size_t committed_private = 0;
714 size_t committed_mapped = 0;
715 size_t committed_image = 0;
716 void* base_address = NULL;
717 while (VirtualQueryEx(process_, base_address, &mbi, sizeof(mbi)) ==
718 sizeof(mbi)) {
719 if (mbi.State == MEM_COMMIT) {
720 if (mbi.Type == MEM_PRIVATE) {
721 committed_private += mbi.RegionSize;
722 } else if (mbi.Type == MEM_MAPPED) {
723 committed_mapped += mbi.RegionSize;
724 } else if (mbi.Type == MEM_IMAGE) {
725 committed_image += mbi.RegionSize;
726 } else {
727 NOTREACHED();
730 void* new_base = (static_cast<BYTE*>(mbi.BaseAddress)) + mbi.RegionSize;
731 // Avoid infinite loop by weird MEMORY_BASIC_INFORMATION.
732 // If we query 64bit processes in a 32bit process, VirtualQueryEx()
733 // returns such data.
734 if (new_base <= base_address) {
735 usage->image = 0;
736 usage->mapped = 0;
737 usage->priv = 0;
738 return;
740 base_address = new_base;
742 usage->image = committed_image / 1024;
743 usage->mapped = committed_mapped / 1024;
744 usage->priv = committed_private / 1024;
747 bool ProcessMetrics::GetWorkingSetKBytes(WorkingSetKBytes* ws_usage) const {
748 size_t ws_private = 0;
749 size_t ws_shareable = 0;
750 size_t ws_shared = 0;
752 DCHECK(ws_usage);
753 memset(ws_usage, 0, sizeof(*ws_usage));
755 DWORD number_of_entries = 4096; // Just a guess.
756 PSAPI_WORKING_SET_INFORMATION* buffer = NULL;
757 int retries = 5;
758 for (;;) {
759 DWORD buffer_size = sizeof(PSAPI_WORKING_SET_INFORMATION) +
760 (number_of_entries * sizeof(PSAPI_WORKING_SET_BLOCK));
762 // if we can't expand the buffer, don't leak the previous
763 // contents or pass a NULL pointer to QueryWorkingSet
764 PSAPI_WORKING_SET_INFORMATION* new_buffer =
765 reinterpret_cast<PSAPI_WORKING_SET_INFORMATION*>(
766 realloc(buffer, buffer_size));
767 if (!new_buffer) {
768 free(buffer);
769 return false;
771 buffer = new_buffer;
773 // Call the function once to get number of items
774 if (QueryWorkingSet(process_, buffer, buffer_size))
775 break; // Success
777 if (GetLastError() != ERROR_BAD_LENGTH) {
778 free(buffer);
779 return false;
782 number_of_entries = static_cast<DWORD>(buffer->NumberOfEntries);
784 // Maybe some entries are being added right now. Increase the buffer to
785 // take that into account.
786 number_of_entries = static_cast<DWORD>(number_of_entries * 1.25);
788 if (--retries == 0) {
789 free(buffer); // If we're looping, eventually fail.
790 return false;
794 // On windows 2000 the function returns 1 even when the buffer is too small.
795 // The number of entries that we are going to parse is the minimum between the
796 // size we allocated and the real number of entries.
797 number_of_entries =
798 std::min(number_of_entries, static_cast<DWORD>(buffer->NumberOfEntries));
799 for (unsigned int i = 0; i < number_of_entries; i++) {
800 if (buffer->WorkingSetInfo[i].Shared) {
801 ws_shareable++;
802 if (buffer->WorkingSetInfo[i].ShareCount > 1)
803 ws_shared++;
804 } else {
805 ws_private++;
809 ws_usage->priv = ws_private * PAGESIZE_KB;
810 ws_usage->shareable = ws_shareable * PAGESIZE_KB;
811 ws_usage->shared = ws_shared * PAGESIZE_KB;
812 free(buffer);
813 return true;
816 static uint64 FileTimeToUTC(const FILETIME& ftime) {
817 LARGE_INTEGER li;
818 li.LowPart = ftime.dwLowDateTime;
819 li.HighPart = ftime.dwHighDateTime;
820 return li.QuadPart;
823 double ProcessMetrics::GetCPUUsage() {
824 FILETIME now;
825 FILETIME creation_time;
826 FILETIME exit_time;
827 FILETIME kernel_time;
828 FILETIME user_time;
830 GetSystemTimeAsFileTime(&now);
832 if (!GetProcessTimes(process_, &creation_time, &exit_time,
833 &kernel_time, &user_time)) {
834 // We don't assert here because in some cases (such as in the Task Manager)
835 // we may call this function on a process that has just exited but we have
836 // not yet received the notification.
837 return 0;
839 int64 system_time = (FileTimeToUTC(kernel_time) + FileTimeToUTC(user_time)) /
840 processor_count_;
841 int64 time = FileTimeToUTC(now);
843 if ((last_system_time_ == 0) || (last_time_ == 0)) {
844 // First call, just set the last values.
845 last_system_time_ = system_time;
846 last_time_ = time;
847 return 0;
850 int64 system_time_delta = system_time - last_system_time_;
851 int64 time_delta = time - last_time_;
852 DCHECK_NE(0U, time_delta);
853 if (time_delta == 0)
854 return 0;
856 // We add time_delta / 2 so the result is rounded.
857 int cpu = static_cast<int>((system_time_delta * 100 + time_delta / 2) /
858 time_delta);
860 last_system_time_ = system_time;
861 last_time_ = time;
863 return cpu;
866 bool ProcessMetrics::GetIOCounters(IoCounters* io_counters) const {
867 return GetProcessIoCounters(process_, io_counters) != FALSE;
870 bool ProcessMetrics::CalculateFreeMemory(FreeMBytes* free) const {
871 const SIZE_T kTopAddress = 0x7F000000;
872 const SIZE_T kMegabyte = 1024 * 1024;
873 SIZE_T accumulated = 0;
875 MEMORY_BASIC_INFORMATION largest = {0};
876 UINT_PTR scan = 0;
877 while (scan < kTopAddress) {
878 MEMORY_BASIC_INFORMATION info;
879 if (!::VirtualQueryEx(process_, reinterpret_cast<void*>(scan),
880 &info, sizeof(info)))
881 return false;
882 if (info.State == MEM_FREE) {
883 accumulated += info.RegionSize;
884 if (info.RegionSize > largest.RegionSize)
885 largest = info;
887 scan += info.RegionSize;
889 free->largest = largest.RegionSize / kMegabyte;
890 free->largest_ptr = largest.BaseAddress;
891 free->total = accumulated / kMegabyte;
892 return true;
895 bool EnableLowFragmentationHeap() {
896 HMODULE kernel32 = GetModuleHandle(L"kernel32.dll");
897 HeapSetFn heap_set = reinterpret_cast<HeapSetFn>(GetProcAddress(
898 kernel32,
899 "HeapSetInformation"));
901 // On Windows 2000, the function is not exported. This is not a reason to
902 // fail.
903 if (!heap_set)
904 return true;
906 unsigned number_heaps = GetProcessHeaps(0, NULL);
907 if (!number_heaps)
908 return false;
910 // Gives us some extra space in the array in case a thread is creating heaps
911 // at the same time we're querying them.
912 static const int MARGIN = 8;
913 scoped_array<HANDLE> heaps(new HANDLE[number_heaps + MARGIN]);
914 number_heaps = GetProcessHeaps(number_heaps + MARGIN, heaps.get());
915 if (!number_heaps)
916 return false;
918 for (unsigned i = 0; i < number_heaps; ++i) {
919 ULONG lfh_flag = 2;
920 // Don't bother with the result code. It may fails on heaps that have the
921 // HEAP_NO_SERIALIZE flag. This is expected and not a problem at all.
922 heap_set(heaps[i],
923 HeapCompatibilityInformation,
924 &lfh_flag,
925 sizeof(lfh_flag));
927 return true;
930 void EnableTerminationOnHeapCorruption() {
931 // Ignore the result code. Supported on XP SP3 and Vista.
932 HeapSetInformation(NULL, HeapEnableTerminationOnCorruption, NULL, 0);
935 void EnableTerminationOnOutOfMemory() {
936 std::set_new_handler(&OnNoMemory);
939 void RaiseProcessToHighPriority() {
940 SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);
943 // GetPerformanceInfo is not available on WIN2K. So we'll
944 // load it on-the-fly.
945 const wchar_t kPsapiDllName[] = L"psapi.dll";
946 typedef BOOL (WINAPI *GetPerformanceInfoFunction) (
947 PPERFORMANCE_INFORMATION pPerformanceInformation,
948 DWORD cb);
950 // Beware of races if called concurrently from multiple threads.
951 static BOOL InternalGetPerformanceInfo(
952 PPERFORMANCE_INFORMATION pPerformanceInformation, DWORD cb) {
953 static GetPerformanceInfoFunction GetPerformanceInfo_func = NULL;
954 if (!GetPerformanceInfo_func) {
955 HMODULE psapi_dll = ::GetModuleHandle(kPsapiDllName);
956 if (psapi_dll)
957 GetPerformanceInfo_func = reinterpret_cast<GetPerformanceInfoFunction>(
958 GetProcAddress(psapi_dll, "GetPerformanceInfo"));
960 if (!GetPerformanceInfo_func) {
961 // The function could be loaded!
962 memset(pPerformanceInformation, 0, cb);
963 return FALSE;
966 return GetPerformanceInfo_func(pPerformanceInformation, cb);
969 size_t GetSystemCommitCharge() {
970 // Get the System Page Size.
971 SYSTEM_INFO system_info;
972 GetSystemInfo(&system_info);
974 PERFORMANCE_INFORMATION info;
975 if (!InternalGetPerformanceInfo(&info, sizeof(info))) {
976 DLOG(ERROR) << "Failed to fetch internal performance info.";
977 return 0;
979 return (info.CommitTotal * system_info.dwPageSize) / 1024;
982 } // namespace base