1 // Copyright 2015 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. 4 5 #include <stdint.h> 6 7 #include "base/logging.h" 8 #include "base/process/process_handle.h" 9 #include "build/build_config.h" 10 11 namespace base { 12 13 namespace { 14 bool g_have_unique_id = false; 15 uint32_t g_unique_id; 16 17 // The process which set |g_unique_id|. 18 ProcessId g_procid; 19 20 // Mangle IDs so that they are not accidentally used as PIDs, e.g. as an 21 // argument to kill or waitpid. MangleProcessId(ProcessId process_id)22uint32_t MangleProcessId(ProcessId process_id) { 23 // Add a large power of 10 so that the pid is still the pid is still readable 24 // inside the mangled id. 25 return static_cast<uint32_t>(process_id) + 1000000000U; 26 } 27 28 } // namespace 29 GetUniqueIdForProcess()30uint32_t GetUniqueIdForProcess() { 31 if (!g_have_unique_id) { 32 return MangleProcessId(GetCurrentProcId()); 33 } 34 35 // Make sure we are the same process that set |g_procid|. This check may have 36 // false negatives (if a process ID was reused) but should have no false 37 // positives. 38 DCHECK_EQ(GetCurrentProcId(), g_procid); 39 return g_unique_id; 40 } 41 42 #if defined(OS_LINUX) || defined(OS_AIX) 43 InitUniqueIdForProcessInPidNamespace(ProcessId pid_outside_of_namespace)44void InitUniqueIdForProcessInPidNamespace(ProcessId pid_outside_of_namespace) { 45 g_unique_id = MangleProcessId(pid_outside_of_namespace); 46 g_procid = GetCurrentProcId(); 47 g_have_unique_id = true; 48 } 49 50 #endif 51 52 } // namespace base 53