| 1 |
/* |
| 2 |
* Copyright (C) 2021 The Android Open Source Project |
| 3 |
* |
| 4 |
* Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 |
* you may not use this file except in compliance with the License. |
| 6 |
* You may obtain a copy of the License at |
| 7 |
* |
| 8 |
* http://www.apache.org/licenses/LICENSE-2.0 |
| 9 |
* |
| 10 |
* Unless required by applicable law or agreed to in writing, software |
| 11 |
* distributed under the License is distributed on an "AS IS" BASIS, |
| 12 |
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 |
* See the License for the specific language governing permissions and |
| 14 |
* limitations under the License. |
| 15 |
*/ |
| 16 |
|
| 17 |
#include <stdint.h> |
| 18 |
#ifdef XP_WIN |
| 19 |
# include <windows.h> |
| 20 |
#else |
| 21 |
# include <time.h> |
| 22 |
# include <unistd.h> |
| 23 |
#endif |
| 24 |
|
| 25 |
#include "mozilla/Flow.h" |
| 26 |
|
| 27 |
// Some infrastructure that we use for computing a per process UUID |
| 28 |
|
| 29 |
// FNV-1a hasher |
| 30 |
// We use this to construct a randomish UUID by hashing the PID and the |
| 31 |
// current time. |
| 32 |
// |
| 33 |
// It's probably not the best choice of hasher but it works for Perfetto |
| 34 |
// so it's good enough for us. |
| 35 |
struct Hasher { |
| 36 |
static const uint64_t kOffsetBasis = 14695981039346656037ULL; |
| 37 |
static const uint64_t kPrime = 1099511628211ULL; |
| 38 |
|
| 39 |
uint64_t hash = kOffsetBasis; |
| 40 |
|
| 41 |
void Update(const void* data, size_t size) { |
| 42 |
const uint8_t* ptr = static_cast<const uint8_t*>(data); |
| 43 |
for (size_t i = 0; i < size; ++i) { |
| 44 |
hash ^= ptr[i]; |
| 45 |
hash *= kPrime; |
| 46 |
} |
| 47 |
} |
| 48 |
void Update(uint64_t value) { Update(&value, sizeof(value)); } |
| 49 |
void Update(uint32_t value) { Update(&value, sizeof(value)); } |
| 50 |
|
| 51 |
uint64_t Get() const { return hash; } |
| 52 |
}; |
| 53 |
|
| 54 |
static uint64_t CurrentTime() { |
| 55 |
#ifdef XP_WIN |
| 56 |
return GetTickCount64(); |
| 57 |
#else |
| 58 |
timespec ts; |
| 59 |
clock_gettime(CLOCK_MONOTONIC, &ts); |
| 60 |
return ts.tv_sec * 1000 + ts.tv_nsec / 1000000; |
| 61 |
#endif |
| 62 |
} |
| 63 |
|
| 64 |
static uint64_t CurrentPID() { |
| 65 |
#ifdef XP_WIN |
| 66 |
return GetCurrentProcessId(); |
| 67 |
#else |
| 68 |
return getpid(); |
| 69 |
#endif |
| 70 |
} |
| 71 |
|
| 72 |
// This is inspired by the perfetto code in TrackRegistry::ComputeProcessUuid |
| 73 |
uint64_t ComputeProcessUUID() { |
| 74 |
auto pid = CurrentPID(); |
| 75 |
auto time = CurrentTime(); |
| 76 |
Hasher hasher; |
| 77 |
hasher.Update(pid); |
| 78 |
hasher.Update(time); |
| 79 |
return hasher.Get(); |
| 80 |
} |
| 81 |
|
| 82 |
MFBT_DATA uint64_t gProcessUUID; |
| 83 |
|
| 84 |
MFBT_API void Flow::Init() { gProcessUUID = ComputeProcessUUID(); } |