| 6 |
| 7 | #include <algorithm> |
| 8 | #include <limits> |
| 9 | #include <utility> |
| 10 |
| 11 | #include "base/atomic_sequence_num.h" |
| 12 | #include "base/bits.h" |
| 13 | #include "base/debug/stack_trace.h" |
| 14 | #include "base/files/file.h" |
| 15 | #include "base/files/file_path.h" |
| 16 | #include "base/files/memory_mapped_file.h" |
| 17 | #include "base/logging.h" |
| 18 | #include "base/memory/ptr_util.h" |
| 19 | #include "base/metrics/field_trial.h" |
| 20 | #include "base/metrics/histogram_macros.h" |
| 21 | #include "base/pending_task.h" |
| 22 | #include "base/pickle.h" |
| 23 | #include "base/process/process.h" |
| 24 | #include "base/process/process_handle.h" |
| 25 | #include "base/stl_util.h" |
| 26 | #include "base/strings/string_util.h" |
| 27 | #include "base/strings/utf_string_conversions.h" |
| 28 | #include "base/threading/platform_thread.h" |
| 29 | #include "build/build_config.h" |
| 30 |
| 31 | namespace base { |
| 32 | namespace debug { |
| 33 |
| 34 | namespace { |
| 35 |
| 36 | // The minimum depth a stack should support. |
| 37 | const int kMinStackDepth = 2; |
| 38 |
| 39 | // The amount of memory set aside for holding arbitrary user data (key/value |
| 40 | // pairs) globally or associated with ActivityData entries. |
| 41 | const size_t kUserDataSize = 1 << 10; // 1 KiB |
| 42 | const size_t kProcessDataSize = 4 << 10; // 4 KiB |
| 43 | const size_t kMaxUserDataNameLength = |
| 44 | static_cast<size_t>(std::numeric_limits<uint8_t>::max()); |
| 45 |
| 46 | // A constant used to indicate that module information is changing. |
| 47 | const uint32_t kModuleInformationChanging = 0x80000000; |
| 48 |
| 49 | // The key used to record process information. |
| 50 | const char kProcessPhaseDataKey[] = "process-phase"; |
| 51 |
| 52 | // An atomically incrementing number, used to check for recreations of objects |
| 53 | // in the same memory space. |
| 54 | AtomicSequenceNumber g_next_id; |
| 55 |
| 56 | // Gets the next non-zero identifier. It is only unique within a process. |
| 57 | uint32_t GetNextDataId() { |
| 58 | uint32_t id; |
| 59 | while ((id = g_next_id.GetNext()) == 0) { |
| 60 | } |
| 61 | return id; |
| 62 | } |
| 63 |
| 64 | // Gets the current process-id, either from the GlobalActivityTracker if it |
| 65 | // exists (where the PID can be defined for testing) or from the system if |
| 66 | // there isn't such. |
| 67 | int64_t GetProcessId() { |
| 68 | GlobalActivityTracker* global = GlobalActivityTracker::Get(); |
| 69 | if (global) |
| 70 | return global->process_id(); |
| 71 | return GetCurrentProcId(); |
| 72 | } |
| 73 |
| 74 | // Finds and reuses a specific allocation or creates a new one. |
| 75 | PersistentMemoryAllocator::Reference AllocateFrom( |
| 76 | PersistentMemoryAllocator* allocator, |
| 77 | uint32_t from_type, |
| 78 | size_t size, |
| 79 | uint32_t to_type) { |
| 80 | PersistentMemoryAllocator::Iterator iter(allocator); |
| 81 | PersistentMemoryAllocator::Reference ref; |
| 82 | while ((ref = iter.GetNextOfType(from_type)) != 0) { |
| 83 | DCHECK_LE(size, allocator->GetAllocSize(ref)); |
| 84 | // This can fail if a another thread has just taken it. It is assumed that |
| 85 | // the memory is cleared during the "free" operation. |
| 86 | if (allocator->ChangeType(ref, to_type, from_type, /*clear=*/false)) |
| 87 | return ref; |
| 88 | } |
| 89 |
| 90 | return allocator->Allocate(size, to_type); |
| 91 | } |
| 92 |
| 93 | // Determines the previous aligned index. |
| 94 | size_t RoundDownToAlignment(size_t index, size_t alignment) { |
| 95 | return bits::AlignDown(index, alignment); |
| 96 | } |
| 97 |
| 98 | // Determines the next aligned index. |
| 99 | size_t RoundUpToAlignment(size_t index, size_t alignment) { |
| 100 | return bits::Align(index, alignment); |
| 101 | } |
| 102 |
| 103 | // Converts "tick" timing into wall time. |
| 104 | Time WallTimeFromTickTime(int64_t ticks_start, int64_t ticks, Time time_start) { |
| 105 | return time_start + TimeDelta::FromInternalValue(ticks - ticks_start); |
| 106 | } |
| 107 |
| 108 | } // namespace |
| 109 |
| 110 | union ThreadRef { |
| 111 | int64_t as_id; |
| 112 | #if defined(OS_WIN) |
| 113 | // On Windows, the handle itself is often a pseudo-handle with a common |
| 114 | // value meaning "this thread" and so the thread-id is used. The former |
| 115 | // can be converted to a thread-id with a system call. |
| 116 | PlatformThreadId as_tid; |
| 117 | #elif defined(OS_POSIX) || defined(OS_FUCHSIA) |
| 118 | // On Posix and Fuchsia, the handle is always a unique identifier so no |
| 119 | // conversion needs to be done. However, its value is officially opaque so |
| 120 | // there is no one correct way to convert it to a numerical identifier. |
| 121 | PlatformThreadHandle::Handle as_handle; |
| 122 | #endif |
| 123 | }; |
| 124 |
| 125 | OwningProcess::OwningProcess() = default; |
| 126 | OwningProcess::~OwningProcess() = default; |
| 127 |
| 128 | void OwningProcess::Release_Initialize(int64_t pid) { |
| 129 | uint32_t old_id = data_id.load(std::memory_order_acquire); |
| 130 | DCHECK_EQ(0U, old_id); |
| 131 | process_id = pid != 0 ? pid : GetProcessId(); |
| 132 | create_stamp = Time::Now().ToInternalValue(); |
| 133 | data_id.store(GetNextDataId(), std::memory_order_release); |
| 134 | } |
| 135 |
| 136 | void OwningProcess::SetOwningProcessIdForTesting(int64_t pid, int64_t stamp) { |
| 137 | DCHECK_NE(0U, data_id); |
| 138 | process_id = pid; |
| 139 | create_stamp = stamp; |
| 140 | } |
| 141 |
| 142 | // static |
| 143 | bool OwningProcess::GetOwningProcessId(const void* memory, |
| 144 | int64_t* out_id, |
| 145 | int64_t* out_stamp) { |
| 146 | const OwningProcess* info = reinterpret_cast<const OwningProcess*>(memory); |
| 147 | uint32_t id = info->data_id.load(std::memory_order_acquire); |
| 148 | if (id == 0) |
| 149 | return false; |
| 150 |
| 151 | *out_id = info->process_id; |
| 152 | *out_stamp = info->create_stamp; |
| 153 | return id == info->data_id.load(std::memory_order_seq_cst); |
| 154 | } |
| 155 |
| 156 | // It doesn't matter what is contained in this (though it will be all zeros) |
| 157 | // as only the address of it is important. |
| 158 | const ActivityData kNullActivityData = {}; |
| 159 |
| 160 | ActivityData ActivityData::ForThread(const PlatformThreadHandle& handle) { |
| 161 | ThreadRef thread_ref; |
| 162 | thread_ref.as_id = 0; // Zero the union in case other is smaller. |
| 163 | #if defined(OS_WIN) |
| 164 | thread_ref.as_tid = ::GetThreadId(handle.platform_handle()); |
| 165 | #elif defined(OS_POSIX) |
| 166 | thread_ref.as_handle = handle.platform_handle(); |
| 167 | #endif |
| 168 | return ForThread(thread_ref.as_id); |
| 169 | } |
| 170 |
| 171 | ActivityTrackerMemoryAllocator::ActivityTrackerMemoryAllocator( |
| 172 | PersistentMemoryAllocator* allocator, |
| 173 | uint32_t object_type, |
| 174 | uint32_t object_free_type, |
| 175 | size_t object_size, |
| 176 | size_t cache_size, |
| 177 | bool make_iterable) |
| 178 | : allocator_(allocator), |
| 179 | object_type_(object_type), |
| 180 | object_free_type_(object_free_type), |
| 181 | object_size_(object_size), |
| 182 | cache_size_(cache_size), |
| 183 | make_iterable_(make_iterable), |
| 184 | iterator_(allocator), |
| 185 | cache_values_(new Reference[cache_size]), |
| 186 | cache_used_(0) { |
| 187 | DCHECK(allocator); |
| 188 | } |
| 189 |
| 190 | ActivityTrackerMemoryAllocator::~ActivityTrackerMemoryAllocator() = default; |
| 191 |
| 192 | ActivityTrackerMemoryAllocator::Reference |
| 193 | ActivityTrackerMemoryAllocator::GetObjectReference() { |
| 194 | // First see if there is a cached value that can be returned. This is much |
| 195 | // faster than searching the memory system for free blocks. |
| 196 | while (cache_used_ > 0) { |
| 197 | Reference cached = cache_values_[--cache_used_]; |
| 198 | // Change the type of the cached object to the proper type and return it. |
| 199 | // If the type-change fails that means another thread has taken this from |
| 200 | // under us (via the search below) so ignore it and keep trying. Don't |
| 201 | // clear the memory because that was done when the type was made "free". |
| 202 | if (allocator_->ChangeType(cached, object_type_, object_free_type_, false)) |
| 203 | return cached; |
| 204 | } |
| 205 |
| 206 | // Fetch the next "free" object from persistent memory. Rather than restart |
| 207 | // the iterator at the head each time and likely waste time going again |
| 208 | // through objects that aren't relevant, the iterator continues from where |
| 209 | // it last left off and is only reset when the end is reached. If the |
| 210 | // returned reference matches |last|, then it has wrapped without finding |
| 211 | // anything. |
| 212 | const Reference last = iterator_.GetLast(); |
| 213 | while (true) { |
| 214 | uint32_t type; |
| 215 | Reference found = iterator_.GetNext(&type); |
| 216 | if (found && type == object_free_type_) { |
| 217 | // Found a free object. Change it to the proper type and return it. If |
| 218 | // the type-change fails that means another thread has taken this from |
| 219 | // under us so ignore it and keep trying. |
| 220 | if (allocator_->ChangeType(found, object_type_, object_free_type_, false)) |
| 221 | return found; |
| 222 | } |
| 223 | if (found == last) { |
| 224 | // Wrapped. No desired object was found. |
| 225 | break; |
| 226 | } |
| 227 | if (!found) { |
| 228 | // Reached end; start over at the beginning. |
| 229 | iterator_.Reset(); |
| 230 | } |
| 231 | } |
| 232 |
| 233 | // No free block was found so instead allocate a new one. |
| 234 | Reference allocated = allocator_->Allocate(object_size_, object_type_); |
| 235 | if (allocated && make_iterable_) |
| 236 | allocator_->MakeIterable(allocated); |
| 237 | return allocated; |
| 238 | } |
| 239 |
| 240 | void ActivityTrackerMemoryAllocator::ReleaseObjectReference(Reference ref) { |
| 241 | // Mark object as free. |
| 242 | bool success = allocator_->ChangeType(ref, object_free_type_, object_type_, |
| 243 | /*clear=*/true); |
| 244 | DCHECK(success); |
| 245 |
| 246 | // Add this reference to our "free" cache if there is space. If not, the type |
| 247 | // has still been changed to indicate that it is free so this (or another) |
| 248 | // thread can find it, albeit more slowly, using the iteration method above. |
| 249 | if (cache_used_ < cache_size_) |
| 250 | cache_values_[cache_used_++] = ref; |
| 251 | } |
| 252 |
| 253 | // static |
| 254 | void Activity::FillFrom(Activity* activity, |
| 255 | const void* program_counter, |
| 256 | const void* origin, |
| 257 | Type type, |
| 258 | const ActivityData& data) { |
| 259 | activity->time_internal = base::TimeTicks::Now().ToInternalValue(); |
| 260 | activity->calling_address = reinterpret_cast<uintptr_t>(program_counter); |
| 261 | activity->origin_address = reinterpret_cast<uintptr_t>(origin); |
| 262 | activity->activity_type = type; |
| 263 | activity->data = data; |
| 264 |
| 265 | #if (!defined(OS_NACL) && DCHECK_IS_ON()) || defined(ADDRESS_SANITIZER) |
| 266 | // Create a stacktrace from the current location and get the addresses for |
| 267 | // improved debuggability. |
| 268 | StackTrace stack_trace; |
| 269 | size_t stack_depth; |
| 270 | const void* const* stack_addrs = stack_trace.Addresses(&stack_depth); |
| 271 | // Copy the stack addresses, ignoring the first one (here). |
| 272 | size_t i; |
| 273 | for (i = 1; i < stack_depth && i < kActivityCallStackSize; ++i) { |
| 274 | activity->call_stack[i - 1] = reinterpret_cast<uintptr_t>(stack_addrs[i]); |
| 275 | } |
| 276 | activity->call_stack[i - 1] = 0; |
| 277 | #else |
| 278 | activity->call_stack[0] = 0; |
| 279 | #endif |
| 280 | } |
| 281 |
| 282 | ActivityUserData::TypedValue::TypedValue() = default; |
| 283 | ActivityUserData::TypedValue::TypedValue(const TypedValue& other) = default; |
| 284 | ActivityUserData::TypedValue::~TypedValue() = default; |
| 285 |
| 286 | StringPiece ActivityUserData::TypedValue::Get() const { |
| 287 | DCHECK_EQ(RAW_VALUE, type_); |
| 288 | return long_value_; |
| 289 | } |
| 290 |
| 291 | StringPiece ActivityUserData::TypedValue::GetString() const { |
| 292 | DCHECK_EQ(STRING_VALUE, type_); |
| 293 | return long_value_; |
| 294 | } |
| 295 |
| 296 | bool ActivityUserData::TypedValue::GetBool() const { |
| 297 | DCHECK_EQ(BOOL_VALUE, type_); |
| 298 | return short_value_ != 0; |
| 299 | } |
| 300 |
| 301 | char ActivityUserData::TypedValue::GetChar() const { |
| 302 | DCHECK_EQ(CHAR_VALUE, type_); |
| 303 | return static_cast<char>(short_value_); |
| 304 | } |
| 305 |
| 306 | int64_t ActivityUserData::TypedValue::GetInt() const { |
| 307 | DCHECK_EQ(SIGNED_VALUE, type_); |
| 308 | return static_cast<int64_t>(short_value_); |
| 309 | } |
| 310 |
| 311 | uint64_t ActivityUserData::TypedValue::GetUint() const { |
| 312 | DCHECK_EQ(UNSIGNED_VALUE, type_); |
| 313 | return static_cast<uint64_t>(short_value_); |
| 314 | } |
| 315 |
| 316 | StringPiece ActivityUserData::TypedValue::GetReference() const { |
| 317 | DCHECK_EQ(RAW_VALUE_REFERENCE, type_); |
| 318 | return ref_value_; |
| 319 | } |
| 320 |
| 321 | StringPiece ActivityUserData::TypedValue::GetStringReference() const { |
| 322 | DCHECK_EQ(STRING_VALUE_REFERENCE, type_); |
| 323 | return ref_value_; |
| 324 | } |
| 325 |
| 326 | // These are required because std::atomic is (currently) not a POD type and |
| 327 | // thus clang requires explicit out-of-line constructors and destructors even |
| 328 | // when they do nothing. |
| 329 | ActivityUserData::ValueInfo::ValueInfo() = default; |
| 330 | ActivityUserData::ValueInfo::ValueInfo(ValueInfo&&) = default; |
| 331 | ActivityUserData::ValueInfo::~ValueInfo() = default; |
| 332 | ActivityUserData::MemoryHeader::MemoryHeader() = default; |
| 333 | ActivityUserData::MemoryHeader::~MemoryHeader() = default; |
| 334 | ActivityUserData::FieldHeader::FieldHeader() = default; |
| 335 | ActivityUserData::FieldHeader::~FieldHeader() = default; |
| 336 |
| 337 | ActivityUserData::ActivityUserData() : ActivityUserData(nullptr, 0, -1) {} |
| 338 |
| 339 | ActivityUserData::ActivityUserData(void* memory, size_t size, int64_t pid) |
| 340 | : memory_(reinterpret_cast<char*>(memory)), |
| 341 | available_(RoundDownToAlignment(size, kMemoryAlignment)), |
| 342 | header_(reinterpret_cast<MemoryHeader*>(memory)), |
| 343 | orig_data_id(0), |
| 344 | orig_process_id(0), |
| 345 | orig_create_stamp(0) { |
| 346 | // It's possible that no user data is being stored. |
| 347 | if (!memory_) |
| 348 | return; |
| 349 |
| 350 | static_assert(0 == sizeof(MemoryHeader) % kMemoryAlignment, "invalid header"); |
| 351 | DCHECK_LT(sizeof(MemoryHeader), available_); |
| 352 | if (header_->owner.data_id.load(std::memory_order_acquire) == 0) |
| 353 | header_->owner.Release_Initialize(pid); |
| 354 | memory_ += sizeof(MemoryHeader); |
| 355 | available_ -= sizeof(MemoryHeader); |
| 356 |
| 357 | // Make a copy of identifying information for later comparison. |
| 358 | *const_cast<uint32_t*>(&orig_data_id) = |
| 359 | header_->owner.data_id.load(std::memory_order_acquire); |
| 360 | *const_cast<int64_t*>(&orig_process_id) = header_->owner.process_id; |
| 361 | *const_cast<int64_t*>(&orig_create_stamp) = header_->owner.create_stamp; |
| 362 |
| 363 | // If there is already data present, load that. This allows the same class |
| 364 | // to be used for analysis through snapshots. |
| 365 | ImportExistingData(); |
| 366 | } |
| 367 |
| 368 | ActivityUserData::~ActivityUserData() = default; |
| 369 |
| 370 | bool ActivityUserData::CreateSnapshot(Snapshot* output_snapshot) const { |
| 371 | DCHECK(output_snapshot); |
| 372 | DCHECK(output_snapshot->empty()); |
| 373 |
| 374 | // Find any new data that may have been added by an active instance of this |
| 375 | // class that is adding records. |
| 376 | ImportExistingData(); |
| 377 |
| 378 | // Add all the values to the snapshot. |
| 379 | for (const auto& entry : values_) { |
| 380 | TypedValue value; |
| 381 | const size_t size = entry.second.size_ptr->load(std::memory_order_acquire); |
| 382 | value.type_ = entry.second.type; |
| 383 | DCHECK_GE(entry.second.extent, size); |
| 384 |
| 385 | switch (entry.second.type) { |
| 386 | case RAW_VALUE: |
| 387 | case STRING_VALUE: |
| 388 | value.long_value_ = |
| 389 | std::string(reinterpret_cast<char*>(entry.second.memory), size); |
| 390 | break; |
| 391 | case RAW_VALUE_REFERENCE: |
| 392 | case STRING_VALUE_REFERENCE: { |
| 393 | ReferenceRecord* ref = |
| 394 | reinterpret_cast<ReferenceRecord*>(entry.second.memory); |
| 395 | value.ref_value_ = StringPiece( |
| 396 | reinterpret_cast<char*>(static_cast<uintptr_t>(ref->address)), |
| 397 | static_cast<size_t>(ref->size)); |
| 398 | } break; |
| 399 | case BOOL_VALUE: |
| 400 | case CHAR_VALUE: |
| 401 | value.short_value_ = |
| 402 | reinterpret_cast<std::atomic<char>*>(entry.second.memory) |
| 403 | ->load(std::memory_order_relaxed); |
| 404 | break; |
| 405 | case SIGNED_VALUE: |
| 406 | case UNSIGNED_VALUE: |
| 407 | value.short_value_ = |
| 408 | reinterpret_cast<std::atomic<uint64_t>*>(entry.second.memory) |
| 409 | ->load(std::memory_order_relaxed); |
| 410 | break; |
| 411 | case END_OF_VALUES: // Included for completeness purposes. |
| 412 | NOTREACHED(); |
| 413 | } |
| 414 | auto inserted = output_snapshot->insert( |
| 415 | std::make_pair(entry.second.name.as_string(), std::move(value))); |
| 416 | DCHECK(inserted.second); // True if inserted, false if existed. |
| 417 | } |
| 418 |
| 419 | // Another import attempt will validate that the underlying memory has not |
| 420 | // been reused for another purpose. Entries added since the first import |
| 421 | // will be ignored here but will be returned if another snapshot is created. |
| 422 | ImportExistingData(); |
| 423 | if (!memory_) { |
| 424 | output_snapshot->clear(); |
| 425 | return false; |
| 426 | } |
| 427 |
| 428 | // Successful snapshot. |
| 429 | return true; |
| 430 | } |
| 431 |
| 432 | const void* ActivityUserData::GetBaseAddress() const { |
| 433 | // The |memory_| pointer advances as elements are written but the |header_| |
| 434 | // value is always at the start of the block so just return that. |
| 435 | return header_; |
| 436 | } |
| 437 |
| 438 | void ActivityUserData::SetOwningProcessIdForTesting(int64_t pid, |
| 439 | int64_t stamp) { |
| 440 | if (!header_) |
| 441 | return; |
| 442 | header_->owner.SetOwningProcessIdForTesting(pid, stamp); |
| 443 | } |
| 444 |
| 445 | // static |
| 446 | bool ActivityUserData::GetOwningProcessId(const void* memory, |
| 447 | int64_t* out_id, |
| 448 | int64_t* out_stamp) { |
| 449 | const MemoryHeader* header = reinterpret_cast<const MemoryHeader*>(memory); |
| 450 | return OwningProcess::GetOwningProcessId(&header->owner, out_id, out_stamp); |
| 451 | } |
| 452 |
| 453 | void* ActivityUserData::Set(StringPiece name, |
| 454 | ValueType type, |
| 455 | const void* memory, |
| 456 | size_t size) { |
| 457 | DCHECK_GE(std::numeric_limits<uint8_t>::max(), name.length()); |
| 458 | size = std::min(std::numeric_limits<uint16_t>::max() - (kMemoryAlignment - 1), |
| 459 | size); |
| 460 |
| 461 | // It's possible that no user data is being stored. |
| 462 | if (!memory_) |
| 463 | return nullptr; |
| 464 |
| 465 | // The storage of a name is limited so use that limit during lookup. |
| 466 | if (name.length() > kMaxUserDataNameLength) |
| 467 | name = StringPiece(name.data(), kMaxUserDataNameLength); |
| 468 |
| 469 | ValueInfo* info; |
| 470 | auto existing = values_.find(name); |
| 471 | if (existing != values_.end()) { |
| 472 | info = &existing->second; |
| 473 | } else { |
| 474 | // The name size is limited to what can be held in a single byte but |
| 475 | // because there are not alignment constraints on strings, it's set tight |
| 476 | // against the header. Its extent (the reserved space, even if it's not |
| 477 | // all used) is calculated so that, when pressed against the header, the |
| 478 | // following field will be aligned properly. |
| 479 | size_t name_size = name.length(); |
| 480 | size_t name_extent = |
| 481 | RoundUpToAlignment(sizeof(FieldHeader) + name_size, kMemoryAlignment) - |
| 482 | sizeof(FieldHeader); |
| 483 | size_t value_extent = RoundUpToAlignment(size, kMemoryAlignment); |
| 484 |
| 485 | // The "base size" is the size of the header and (padded) string key. Stop |
| 486 | // now if there's not room enough for even this. |
| 487 | size_t base_size = sizeof(FieldHeader) + name_extent; |
| 488 | if (base_size > available_) |
| 489 | return nullptr; |
| 490 |
| 491 | // The "full size" is the size for storing the entire value. |
| 492 | size_t full_size = std::min(base_size + value_extent, available_); |
| 493 |
| 494 | // If the value is actually a single byte, see if it can be stuffed at the |
| 495 | // end of the name extent rather than wasting kMemoryAlignment bytes. |
| 496 | if (size == 1 && name_extent > name_size) { |
| 497 | full_size = base_size; |
| 498 | --name_extent; |
| 499 | --base_size; |
| 500 | } |
| 501 |
| 502 | // Truncate the stored size to the amount of available memory. Stop now if |
| 503 | // there's not any room for even part of the value. |
| 504 | if (size != 0) { |
| 505 | size = std::min(full_size - base_size, size); |
| 506 | if (size == 0) |
| 507 | return nullptr; |
| 508 | } |
| 509 |
| 510 | // Allocate a chunk of memory. |
| 511 | FieldHeader* header = reinterpret_cast<FieldHeader*>(memory_); |
| 512 | memory_ += full_size; |
| 513 | available_ -= full_size; |
| 514 |
| 515 | // Datafill the header and name records. Memory must be zeroed. The |type| |
| 516 | // is written last, atomically, to release all the other values. |
| 517 | DCHECK_EQ(END_OF_VALUES, header->type.load(std::memory_order_relaxed)); |
| 518 | DCHECK_EQ(0, header->value_size.load(std::memory_order_relaxed)); |
| 519 | header->name_size = static_cast<uint8_t>(name_size); |
| 520 | header->record_size = full_size; |
| 521 | char* name_memory = reinterpret_cast<char*>(header) + sizeof(FieldHeader); |
| 522 | void* value_memory = |
| 523 | reinterpret_cast<char*>(header) + sizeof(FieldHeader) + name_extent; |
| 524 | memcpy(name_memory, name.data(), name_size); |
| 525 | header->type.store(type, std::memory_order_release); |
| 526 |
| 527 | // Create an entry in |values_| so that this field can be found and changed |
| 528 | // later on without having to allocate new entries. |
| 529 | StringPiece persistent_name(name_memory, name_size); |
| 530 | auto inserted = |
| 531 | values_.insert(std::make_pair(persistent_name, ValueInfo())); |
| 532 | DCHECK(inserted.second); // True if inserted, false if existed. |
| 533 | info = &inserted.first->second; |
| 534 | info->name = persistent_name; |
| 535 | info->memory = value_memory; |
| 536 | info->size_ptr = &header->value_size; |
| 537 | info->extent = full_size - sizeof(FieldHeader) - name_extent; |
| 538 | info->type = type; |
| 539 | } |
| 540 |
| 541 | // Copy the value data to storage. The |size| is written last, atomically, to |
| 542 | // release the copied data. Until then, a parallel reader will just ignore |
| 543 | // records with a zero size. |
| 544 | DCHECK_EQ(type, info->type); |
| 545 | size = std::min(size, info->extent); |
| 546 | info->size_ptr->store(0, std::memory_order_seq_cst); |
| 547 | memcpy(info->memory, memory, size); |
| 548 | info->size_ptr->store(size, std::memory_order_release); |
| 549 |
| 550 | // The address of the stored value is returned so it can be re-used by the |
| 551 | // caller, so long as it's done in an atomic way. |
| 552 | return info->memory; |
| 553 | } |
| 554 |
| 555 | void ActivityUserData::SetReference(StringPiece name, |
| 556 | ValueType type, |
| 557 | const void* memory, |
| 558 | size_t size) { |
| 559 | ReferenceRecord rec; |
| 560 | rec.address = reinterpret_cast<uintptr_t>(memory); |
| 561 | rec.size = size; |
| 562 | Set(name, type, &rec, sizeof(rec)); |
| 563 | } |
| 564 |
| 565 | void ActivityUserData::ImportExistingData() const { |
| 566 | // It's possible that no user data is being stored. |
| 567 | if (!memory_) |
| 568 | return; |
| 569 |
| 570 | while (available_ > sizeof(FieldHeader)) { |
| 571 | FieldHeader* header = reinterpret_cast<FieldHeader*>(memory_); |
| 572 | ValueType type = |
| 573 | static_cast<ValueType>(header->type.load(std::memory_order_acquire)); |
| 574 | if (type == END_OF_VALUES) |
| 575 | return; |
| 576 | if (header->record_size > available_) |
| 577 | return; |
| 578 |
| 579 | size_t value_offset = RoundUpToAlignment( |
| 580 | sizeof(FieldHeader) + header->name_size, kMemoryAlignment); |
| 581 | if (header->record_size == value_offset && |
| 582 | header->value_size.load(std::memory_order_relaxed) == 1) { |
| 583 | value_offset -= 1; |
| 584 | } |
| 585 | if (value_offset + header->value_size > header->record_size) |
| 586 | return; |
| 587 |
| 588 | ValueInfo info; |
| 589 | info.name = StringPiece(memory_ + sizeof(FieldHeader), header->name_size); |
| 590 | info.type = type; |
| 591 | info.memory = memory_ + value_offset; |
| 592 | info.size_ptr = &header->value_size; |
| 593 | info.extent = header->record_size - value_offset; |
| 594 |
| 595 | StringPiece key(info.name); |
| 596 | values_.insert(std::make_pair(key, std::move(info))); |
| 597 |
| 598 | memory_ += header->record_size; |
| 599 | available_ -= header->record_size; |
| 600 | } |
| 601 |
| 602 | // Check if memory has been completely reused. |
| 603 | if (header_->owner.data_id.load(std::memory_order_acquire) != orig_data_id || |
| 604 | header_->owner.process_id != orig_process_id || |
| 605 | header_->owner.create_stamp != orig_create_stamp) { |
| 606 | memory_ = nullptr; |
| 607 | values_.clear(); |
| 608 | } |
| 609 | } |
| 610 |
| 611 | // This information is kept for every thread that is tracked. It is filled |
| 612 | // the very first time the thread is seen. All fields must be of exact sizes |
| 613 | // so there is no issue moving between 32 and 64-bit builds. |
| 614 | struct ThreadActivityTracker::Header { |
| 615 | // Defined in .h for analyzer access. Increment this if structure changes! |
| 616 | static constexpr uint32_t kPersistentTypeId = |
| 617 | GlobalActivityTracker::kTypeIdActivityTracker; |
| 618 |
| 619 | // Expected size for 32/64-bit check. |
| 620 | static constexpr size_t kExpectedInstanceSize = |
| 621 | OwningProcess::kExpectedInstanceSize + Activity::kExpectedInstanceSize + |
| 622 | 72; |
| 623 |
| 624 | // This information uniquely identifies a process. |
| 625 | OwningProcess owner; |
| 626 |
| 627 | // The thread-id (thread_ref.as_id) to which this data belongs. This number |
| 628 | // is not guaranteed to mean anything but combined with the process-id from |
| 629 | // OwningProcess is unique among all active trackers. |
| 630 | ThreadRef thread_ref; |
| 631 |
| 632 | // The start-time and start-ticks when the data was created. Each activity |
| 633 | // record has a |time_internal| value that can be converted to a "wall time" |
| 634 | // with these two values. |
| 635 | int64_t start_time; |
| 636 | int64_t start_ticks; |
| 637 |
| 638 | // The number of Activity slots (spaces that can hold an Activity) that |
| 639 | // immediately follow this structure in memory. |
| 640 | uint32_t stack_slots; |
| 641 |
| 642 | // Some padding to keep everything 64-bit aligned. |
| 643 | uint32_t padding; |
| 644 |
| 645 | // The current depth of the stack. This may be greater than the number of |
| 646 | // slots. If the depth exceeds the number of slots, the newest entries |
| 647 | // won't be recorded. |
| 648 | std::atomic<uint32_t> current_depth; |
| 649 |
| 650 | // A memory location used to indicate if changes have been made to the data |
| 651 | // that would invalidate an in-progress read of its contents. The active |
| 652 | // tracker will increment the value whenever something gets popped from the |
| 653 | // stack. A monitoring tracker can check the value before and after access |
| 654 | // to know, if it's still the same, that the contents didn't change while |
| 655 | // being copied. |
| 656 | std::atomic<uint32_t> data_version; |
| 657 |
| 658 | // The last "exception" activity. This can't be stored on the stack because |
| 659 | // that could get popped as things unwind. |
| 660 | Activity last_exception; |
| 661 |
| 662 | // The name of the thread (up to a maximum length). Dynamic-length names |
| 663 | // are not practical since the memory has to come from the same persistent |
| 664 | // allocator that holds this structure and to which this object has no |
| 665 | // reference. |
| 666 | char thread_name[32]; |
| 667 | }; |
| 668 |
| 669 | ThreadActivityTracker::Snapshot::Snapshot() = default; |
| 670 | ThreadActivityTracker::Snapshot::~Snapshot() = default; |
| 671 |
| 672 | ThreadActivityTracker::ScopedActivity::ScopedActivity( |
| 673 | ThreadActivityTracker* tracker, |
| 674 | const void* program_counter, |
| 675 | const void* origin, |
| 676 | Activity::Type type, |
| 677 | const ActivityData& data) |
| 678 | : tracker_(tracker) { |
| 679 | if (tracker_) |
| 680 | activity_id_ = tracker_->PushActivity(program_counter, origin, type, data); |
| 681 | } |
| 682 |
| 683 | ThreadActivityTracker::ScopedActivity::~ScopedActivity() { |
| 684 | if (tracker_) |
| 685 | tracker_->PopActivity(activity_id_); |
| 686 | } |
| 687 |
| 688 | bool ThreadActivityTracker::ScopedActivity::IsRecorded() { |
| 689 | return tracker_ && tracker_->IsRecorded(activity_id_); |
| 690 | } |
| 691 |
| 692 | void ThreadActivityTracker::ScopedActivity::ChangeTypeAndData( |
| 693 | Activity::Type type, |
| 694 | const ActivityData& data) { |
| 695 | if (tracker_) |
| 696 | tracker_->ChangeActivity(activity_id_, type, data); |
| 697 | } |
| 698 |
| 699 | ThreadActivityTracker::ThreadActivityTracker(void* base, size_t size) |
| 700 | : header_(static_cast<Header*>(base)), |
| 701 | stack_(reinterpret_cast<Activity*>(reinterpret_cast<char*>(base) + |
| 702 | sizeof(Header))), |
| 703 | #if DCHECK_IS_ON() |
| 704 | thread_id_(PlatformThreadRef()), |
| 705 | #endif |
| 706 | stack_slots_( |
| 707 | static_cast<uint32_t>((size - sizeof(Header)) / sizeof(Activity))) { |
| 708 | // Verify the parameters but fail gracefully if they're not valid so that |
| 709 | // production code based on external inputs will not crash. IsValid() will |
| 710 | // return false in this case. |
| 711 | if (!base || |
| 712 | // Ensure there is enough space for the header and at least a few records. |
| 713 | size < sizeof(Header) + kMinStackDepth * sizeof(Activity) || |
| 714 | // Ensure that the |stack_slots_| calculation didn't overflow. |
| 715 | (size - sizeof(Header)) / sizeof(Activity) > |
| 716 | std::numeric_limits<uint32_t>::max()) { |
| 717 | NOTREACHED(); |
| 718 | return; |
| 719 | } |
| 720 |
| 721 | // Ensure that the thread reference doesn't exceed the size of the ID number. |
| 722 | // This won't compile at the global scope because Header is a private struct. |
| 723 | static_assert( |
| 724 | sizeof(header_->thread_ref) == sizeof(header_->thread_ref.as_id), |
| 725 | "PlatformThreadHandle::Handle is too big to hold in 64-bit ID"); |
| 726 |
| 727 | // Ensure that the alignment of Activity.data is properly aligned to a |
| 728 | // 64-bit boundary so there are no interoperability-issues across cpu |
| 729 | // architectures. |
| 730 | static_assert(offsetof(Activity, data) % sizeof(uint64_t) == 0, |
| 731 | "ActivityData.data is not 64-bit aligned"); |
| 732 |
| 733 | // Provided memory should either be completely initialized or all zeros. |
| 734 | if (header_->owner.data_id.load(std::memory_order_relaxed) == 0) { |
| 735 | // This is a new file. Double-check other fields and then initialize. |
| 736 | DCHECK_EQ(0, header_->owner.process_id); |
| 737 | DCHECK_EQ(0, header_->owner.create_stamp); |
| 738 | DCHECK_EQ(0, header_->thread_ref.as_id); |
| 739 | DCHECK_EQ(0, header_->start_time); |
| 740 | DCHECK_EQ(0, header_->start_ticks); |
| 741 | DCHECK_EQ(0U, header_->stack_slots); |
| 742 | DCHECK_EQ(0U, header_->current_depth.load(std::memory_order_relaxed)); |
| 743 | DCHECK_EQ(0U, header_->data_version.load(std::memory_order_relaxed)); |
| 744 | DCHECK_EQ(0, stack_[0].time_internal); |
| 745 | DCHECK_EQ(0U, stack_[0].origin_address); |
| 746 | DCHECK_EQ(0U, stack_[0].call_stack[0]); |
| 747 | DCHECK_EQ(0U, stack_[0].data.task.sequence_id); |
| 748 |
| 749 | #if defined(OS_WIN) |
| 750 | header_->thread_ref.as_tid = PlatformThread::CurrentId(); |
| 751 | #elif defined(OS_POSIX) || defined(OS_FUCHSIA) |
| 752 | header_->thread_ref.as_handle = |
| 753 | PlatformThread::CurrentHandle().platform_handle(); |
| 754 | #endif |
| 755 |
| 756 | header_->start_time = base::Time::Now().ToInternalValue(); |
| 757 | header_->start_ticks = base::TimeTicks::Now().ToInternalValue(); |
| 758 | header_->stack_slots = stack_slots_; |
| 759 | strlcpy(header_->thread_name, PlatformThread::GetName(), |
| 760 | sizeof(header_->thread_name)); |
| 761 |
| 762 | // This is done last so as to guarantee that everything above is "released" |
| 763 | // by the time this value gets written. |
| 764 | header_->owner.Release_Initialize(); |
| 765 |
| 766 | valid_ = true; |
| 767 | DCHECK(IsValid()); |
| 768 | } else { |
| 769 | // This is a file with existing data. Perform basic consistency checks. |
| 770 | valid_ = true; |
| 771 | valid_ = IsValid(); |
| 772 | } |
| 773 | } |
| 774 |
| 775 | ThreadActivityTracker::~ThreadActivityTracker() = default; |
| 776 |
| 777 | ThreadActivityTracker::ActivityId ThreadActivityTracker::PushActivity( |
| 778 | const void* program_counter, |
| 779 | const void* origin, |
| 780 | Activity::Type type, |
| 781 | const ActivityData& data) { |
| 782 | // A thread-checker creates a lock to check the thread-id which means |
| 783 | // re-entry into this code if lock acquisitions are being tracked. |
| 784 | DCHECK(type == Activity::ACT_LOCK_ACQUIRE || CalledOnValidThread()); |
| 785 |
| 786 | // Get the current depth of the stack. No access to other memory guarded |
| 787 | // by this variable is done here so a "relaxed" load is acceptable. |
| 788 | uint32_t depth = header_->current_depth.load(std::memory_order_relaxed); |
| 789 |
| 790 | // Handle the case where the stack depth has exceeded the storage capacity. |
| 791 | // Extra entries will be lost leaving only the base of the stack. |
| 792 | if (depth >= stack_slots_) { |
| 793 | // Since no other threads modify the data, no compare/exchange is needed. |
| 794 | // Since no other memory is being modified, a "relaxed" store is acceptable. |
| 795 | header_->current_depth.store(depth + 1, std::memory_order_relaxed); |
| 796 | return depth; |
| 797 | } |
| 798 |
| 799 | // Get a pointer to the next activity and load it. No atomicity is required |
| 800 | // here because the memory is known only to this thread. It will be made |
| 801 | // known to other threads once the depth is incremented. |
| 802 | Activity::FillFrom(&stack_[depth], program_counter, origin, type, data); |
| 803 |
| 804 | // Save the incremented depth. Because this guards |activity| memory filled |
| 805 | // above that may be read by another thread once the recorded depth changes, |
| 806 | // a "release" store is required. |
| 807 | header_->current_depth.store(depth + 1, std::memory_order_release); |
| 808 |
| 809 | // The current depth is used as the activity ID because it simply identifies |
| 810 | // an entry. Once an entry is pop'd, it's okay to reuse the ID. |
| 811 | return depth; |
| 812 | } |
| 813 |
| 814 | void ThreadActivityTracker::ChangeActivity(ActivityId id, |
| 815 | Activity::Type type, |
| 816 | const ActivityData& data) { |
| 817 | DCHECK(CalledOnValidThread()); |
| 818 | DCHECK(type != Activity::ACT_NULL || &data != &kNullActivityData); |
| 819 | DCHECK_LT(id, header_->current_depth.load(std::memory_order_acquire)); |
| 820 |
| 821 | // Update the information if it is being recorded (i.e. within slot limit). |
| 822 | if (id < stack_slots_) { |
| 823 | Activity* activity = &stack_[id]; |
| 824 |
| 825 | if (type != Activity::ACT_NULL) { |
| 826 | DCHECK_EQ(activity->activity_type & Activity::ACT_CATEGORY_MASK, |
| 827 | type & Activity::ACT_CATEGORY_MASK); |
| 828 | activity->activity_type = type; |
| 829 | } |
| 830 |
| 831 | if (&data != &kNullActivityData) |
| 832 | activity->data = data; |
| 833 | } |
| 834 | } |
| 835 |
| 836 | void ThreadActivityTracker::PopActivity(ActivityId id) { |
| 837 | // Do an atomic decrement of the depth. No changes to stack entries guarded |
| 838 | // by this variable are done here so a "relaxed" operation is acceptable. |
| 839 | // |depth| will receive the value BEFORE it was modified which means the |
| 840 | // return value must also be decremented. The slot will be "free" after |
| 841 | // this call but since only a single thread can access this object, the |
| 842 | // data will remain valid until this method returns or calls outside. |
| 843 | uint32_t depth = |
| 844 | header_->current_depth.fetch_sub(1, std::memory_order_relaxed) - 1; |
| 845 |
| 846 | // Validate that everything is running correctly. |
| 847 | DCHECK_EQ(id, depth); |
| 848 |
| 849 | // A thread-checker creates a lock to check the thread-id which means |
| 850 | // re-entry into this code if lock acquisitions are being tracked. |
| 851 | DCHECK(stack_[depth].activity_type == Activity::ACT_LOCK_ACQUIRE || |
| 852 | CalledOnValidThread()); |
| 853 |
| 854 | // The stack has shrunk meaning that some other thread trying to copy the |
| 855 | // contents for reporting purposes could get bad data. Increment the data |
| 856 | // version so that it con tell that things have changed. This needs to |
| 857 | // happen after the atomic |depth| operation above so a "release" store |
| 858 | // is required. |
| 859 | header_->data_version.fetch_add(1, std::memory_order_release); |
| 860 | } |
| 861 |
| 862 | bool ThreadActivityTracker::IsRecorded(ActivityId id) { |
| 863 | return id < stack_slots_; |
| 864 | } |
| 865 |
| 866 | std::unique_ptr<ActivityUserData> ThreadActivityTracker::GetUserData( |
| 867 | ActivityId id, |
| 868 | ActivityTrackerMemoryAllocator* allocator) { |
| 869 | // Don't allow user data for lock acquisition as recursion may occur. |
| 870 | if (stack_[id].activity_type == Activity::ACT_LOCK_ACQUIRE) { |
| 871 | NOTREACHED(); |
| 872 | return std::make_unique<ActivityUserData>(); |
| 873 | } |
| 874 |
| 875 | // User-data is only stored for activities actually held in the stack. |
| 876 | if (id >= stack_slots_) |
| 877 | return std::make_unique<ActivityUserData>(); |
| 878 |
| 879 | // Create and return a real UserData object. |
| 880 | return CreateUserDataForActivity(&stack_[id], allocator); |
| 881 | } |
| 882 |
| 883 | bool ThreadActivityTracker::HasUserData(ActivityId id) { |
| 884 | // User-data is only stored for activities actually held in the stack. |
| 885 | return (id < stack_slots_ && stack_[id].user_data_ref); |
| 886 | } |
| 887 |
| 888 | void ThreadActivityTracker::ReleaseUserData( |
| 889 | ActivityId id, |
| 890 | ActivityTrackerMemoryAllocator* allocator) { |
| 891 | // User-data is only stored for activities actually held in the stack. |
| 892 | if (id < stack_slots_ && stack_[id].user_data_ref) { |
| 893 | allocator->ReleaseObjectReference(stack_[id].user_data_ref); |
| 894 | stack_[id].user_data_ref = 0; |
| 895 | } |
| 896 | } |
| 897 |
| 898 | void ThreadActivityTracker::RecordExceptionActivity(const void* program_counter, |
| 899 | const void* origin, |
| 900 | Activity::Type type, |
| 901 | const ActivityData& data) { |
| 902 | // A thread-checker creates a lock to check the thread-id which means |
| 903 | // re-entry into this code if lock acquisitions are being tracked. |
| 904 | DCHECK(CalledOnValidThread()); |
| 905 |
| 906 | // Fill the reusable exception activity. |
| 907 | Activity::FillFrom(&header_->last_exception, program_counter, origin, type, |
| 908 | data); |
| 909 |
| 910 | // The data has changed meaning that some other thread trying to copy the |
| 911 | // contents for reporting purposes could get bad data. |
| 912 | header_->data_version.fetch_add(1, std::memory_order_relaxed); |
| 913 | } |
| 914 |
| 915 | bool ThreadActivityTracker::IsValid() const { |
| 916 | if (header_->owner.data_id.load(std::memory_order_acquire) == 0 || |
| 917 | header_->owner.process_id == 0 || header_->thread_ref.as_id == 0 || |
| 918 | header_->start_time == 0 || header_->start_ticks == 0 || |
| 919 | header_->stack_slots != stack_slots_ || |
| 920 | header_->thread_name[sizeof(header_->thread_name) - 1] != '\0') { |
| 921 | return false; |
| 922 | } |
| 923 |
| 924 | return valid_; |
| 925 | } |
| 926 |
| 927 | bool ThreadActivityTracker::CreateSnapshot(Snapshot* output_snapshot) const { |
| 928 | DCHECK(output_snapshot); |
| 929 |
| 930 | // There is no "called on valid thread" check for this method as it can be |
| 931 | // called from other threads or even other processes. It is also the reason |
| 932 | // why atomic operations must be used in certain places above. |
| 933 |
| 934 | // It's possible for the data to change while reading it in such a way that it |
| 935 | // invalidates the read. Make several attempts but don't try forever. |
| 936 | const int kMaxAttempts = 10; |
| 937 | uint32_t depth; |
| 938 |
| 939 | // Stop here if the data isn't valid. |
| 940 | if (!IsValid()) |
| 941 | return false; |
| 942 |
| 943 | // Allocate the maximum size for the stack so it doesn't have to be done |
| 944 | // during the time-sensitive snapshot operation. It is shrunk once the |
| 945 | // actual size is known. |
| 946 | output_snapshot->activity_stack.reserve(stack_slots_); |
| 947 |
| 948 | for (int attempt = 0; attempt < kMaxAttempts; ++attempt) { |
| 949 | // Remember the data IDs to ensure nothing is replaced during the snapshot |
| 950 | // operation. Use "acquire" so that all the non-atomic fields of the |
| 951 | // structure are valid (at least at the current moment in time). |
| 952 | const uint32_t starting_id = |
| 953 | header_->owner.data_id.load(std::memory_order_acquire); |
| 954 | const int64_t starting_create_stamp = header_->owner.create_stamp; |
| 955 | const int64_t starting_process_id = header_->owner.process_id; |
| 956 | const int64_t starting_thread_id = header_->thread_ref.as_id; |
| 957 |
| 958 | // Note the current |data_version| so it's possible to detect at the end |
| 959 | // that nothing has changed since copying the data began. A "cst" operation |
| 960 | // is required to ensure it occurs before everything else. Using "cst" |
| 961 | // memory ordering is relatively expensive but this is only done during |
| 962 | // analysis so doesn't directly affect the worker threads. |
| 963 | const uint32_t pre_version = |
| 964 | header_->data_version.load(std::memory_order_seq_cst); |
| 965 |
| 966 | // Fetching the current depth also "acquires" the contents of the stack. |
| 967 | depth = header_->current_depth.load(std::memory_order_acquire); |
| 968 | uint32_t count = std::min(depth, stack_slots_); |
| 969 | output_snapshot->activity_stack.resize(count); |
| 970 | if (count > 0) { |
| 971 | // Copy the existing contents. Memcpy is used for speed. |
| 972 | memcpy(&output_snapshot->activity_stack[0], stack_, |
| 973 | count * sizeof(Activity)); |
| 974 | } |
| 975 |
| 976 | // Capture the last exception. |
| 977 | memcpy(&output_snapshot->last_exception, &header_->last_exception, |
| 978 | sizeof(Activity)); |
| 979 |
| 980 | // TODO(bcwhite): Snapshot other things here. |
| 981 |
| 982 | // Retry if something changed during the copy. A "cst" operation ensures |
| 983 | // it must happen after all the above operations. |
| 984 | if (header_->data_version.load(std::memory_order_seq_cst) != pre_version) |
| 985 | continue; |
| 986 |
| 987 | // Stack copied. Record it's full depth. |
| 988 | output_snapshot->activity_stack_depth = depth; |
| 989 |
| 990 | // Get the general thread information. |
| 991 | output_snapshot->thread_name = |
| 992 | std::string(header_->thread_name, sizeof(header_->thread_name) - 1); |
| 993 | output_snapshot->create_stamp = header_->owner.create_stamp; |
| 994 | output_snapshot->thread_id = header_->thread_ref.as_id; |
| 995 | output_snapshot->process_id = header_->owner.process_id; |
| 996 |
| 997 | // All characters of the thread-name buffer were copied so as to not break |
| 998 | // if the trailing NUL were missing. Now limit the length if the actual |
| 999 | // name is shorter. |
| 1000 | output_snapshot->thread_name.resize( |
| 1001 | strlen(output_snapshot->thread_name.c_str())); |
| 1002 |
| 1003 | // If the data ID has changed then the tracker has exited and the memory |
| 1004 | // reused by a new one. Try again. |
| 1005 | if (header_->owner.data_id.load(std::memory_order_seq_cst) != starting_id || |
| 1006 | output_snapshot->create_stamp != starting_create_stamp || |
| 1007 | output_snapshot->process_id != starting_process_id || |
| 1008 | output_snapshot->thread_id != starting_thread_id) { |
| 1009 | continue; |
| 1010 | } |
| 1011 |
| 1012 | // Only successful if the data is still valid once everything is done since |
| 1013 | // it's possible for the thread to end somewhere in the middle and all its |
| 1014 | // values become garbage. |
| 1015 | if (!IsValid()) |
| 1016 | return false; |
| 1017 |
| 1018 | // Change all the timestamps in the activities from "ticks" to "wall" time. |
| 1019 | const Time start_time = Time::FromInternalValue(header_->start_time); |
| 1020 | const int64_t start_ticks = header_->start_ticks; |
| 1021 | for (Activity& activity : output_snapshot->activity_stack) { |
| 1022 | activity.time_internal = |
| 1023 | WallTimeFromTickTime(start_ticks, activity.time_internal, start_time) |
| 1024 | .ToInternalValue(); |
| 1025 | } |
| 1026 | output_snapshot->last_exception.time_internal = |
| 1027 | WallTimeFromTickTime(start_ticks, |
| 1028 | output_snapshot->last_exception.time_internal, |
| 1029 | start_time) |
| 1030 | .ToInternalValue(); |
| 1031 |
| 1032 | // Success! |
| 1033 | return true; |
| 1034 | } |
| 1035 |
| 1036 | // Too many attempts. |
| 1037 | return false; |
| 1038 | } |
| 1039 |
| 1040 | const void* ThreadActivityTracker::GetBaseAddress() { |
| 1041 | return header_; |
| 1042 | } |
| 1043 |
| 1044 | uint32_t ThreadActivityTracker::GetDataVersionForTesting() { |
| 1045 | return header_->data_version.load(std::memory_order_relaxed); |
| 1046 | } |
| 1047 |
| 1048 | void ThreadActivityTracker::SetOwningProcessIdForTesting(int64_t pid, |
| 1049 | int64_t stamp) { |
| 1050 | header_->owner.SetOwningProcessIdForTesting(pid, stamp); |
| 1051 | } |
| 1052 |
| 1053 | // static |
| 1054 | bool ThreadActivityTracker::GetOwningProcessId(const void* memory, |
| 1055 | int64_t* out_id, |
| 1056 | int64_t* out_stamp) { |
| 1057 | const Header* header = reinterpret_cast<const Header*>(memory); |
| 1058 | return OwningProcess::GetOwningProcessId(&header->owner, out_id, out_stamp); |
| 1059 | } |
| 1060 |
| 1061 | // static |
| 1062 | size_t ThreadActivityTracker::SizeForStackDepth(int stack_depth) { |
| 1063 | return static_cast<size_t>(stack_depth) * sizeof(Activity) + sizeof(Header); |
| 1064 | } |
| 1065 |
| 1066 | bool ThreadActivityTracker::CalledOnValidThread() { |
| 1067 | #if DCHECK_IS_ON() |
| 1068 | return thread_id_ == PlatformThreadRef(); |
| 1069 | #else |
| 1070 | return true; |
| 1071 | #endif |
| 1072 | } |
| 1073 |
| 1074 | std::unique_ptr<ActivityUserData> |
| 1075 | ThreadActivityTracker::CreateUserDataForActivity( |
| 1076 | Activity* activity, |
| 1077 | ActivityTrackerMemoryAllocator* allocator) { |
| 1078 | DCHECK_EQ(0U, activity->user_data_ref); |
| 1079 |
| 1080 | PersistentMemoryAllocator::Reference ref = allocator->GetObjectReference(); |
| 1081 | void* memory = allocator->GetAsArray<char>(ref, kUserDataSize); |
| 1082 | if (memory) { |
| 1083 | std::unique_ptr<ActivityUserData> user_data = |
| 1084 | std::make_unique<ActivityUserData>(memory, kUserDataSize); |
| 1085 | activity->user_data_ref = ref; |
| 1086 | activity->user_data_id = user_data->id(); |
| 1087 | return user_data; |
| 1088 | } |
| 1089 |
| 1090 | // Return a dummy object that will still accept (but ignore) Set() calls. |
| 1091 | return std::make_unique<ActivityUserData>(); |
| 1092 | } |
| 1093 |
| 1094 | // The instantiation of the GlobalActivityTracker object. |
| 1095 | // The object held here will obviously not be destructed at process exit |
| 1096 | // but that's best since PersistentMemoryAllocator objects (that underlie |
| 1097 | // GlobalActivityTracker objects) are explicitly forbidden from doing anything |
| 1098 | // essential at exit anyway due to the fact that they depend on data managed |
| 1099 | // elsewhere and which could be destructed first. An AtomicWord is used instead |
| 1100 | // of std::atomic because the latter can create global ctors and dtors. |
| 1101 | subtle::AtomicWord GlobalActivityTracker::g_tracker_ = 0; |
| 1102 |
| 1103 | GlobalActivityTracker::ModuleInfo::ModuleInfo() = default; |
| 1104 | GlobalActivityTracker::ModuleInfo::ModuleInfo(ModuleInfo&& rhs) = default; |
| 1105 | GlobalActivityTracker::ModuleInfo::ModuleInfo(const ModuleInfo& rhs) = default; |
| 1106 | GlobalActivityTracker::ModuleInfo::~ModuleInfo() = default; |
| 1107 |
| 1108 | GlobalActivityTracker::ModuleInfo& GlobalActivityTracker::ModuleInfo::operator=( |
| 1109 | ModuleInfo&& rhs) = default; |
| 1110 | GlobalActivityTracker::ModuleInfo& GlobalActivityTracker::ModuleInfo::operator=( |
| 1111 | const ModuleInfo& rhs) = default; |
| 1112 |
| 1113 | GlobalActivityTracker::ModuleInfoRecord::ModuleInfoRecord() = default; |
| 1114 | GlobalActivityTracker::ModuleInfoRecord::~ModuleInfoRecord() = default; |
| 1115 |
| 1116 | bool GlobalActivityTracker::ModuleInfoRecord::DecodeTo( |
| 1117 | GlobalActivityTracker::ModuleInfo* info, |
| 1118 | size_t record_size) const { |
| 1119 | // Get the current "changes" indicator, acquiring all the other values. |
| 1120 | uint32_t current_changes = changes.load(std::memory_order_acquire); |
| 1121 |
| 1122 | // Copy out the dynamic information. |
| 1123 | info->is_loaded = loaded != 0; |
| 1124 | info->address = static_cast<uintptr_t>(address); |
| 1125 | info->load_time = load_time; |
| 1126 |
| 1127 | // Check to make sure no information changed while being read. A "seq-cst" |
| 1128 | // operation is expensive but is only done during analysis and it's the only |
| 1129 | // way to ensure this occurs after all the accesses above. If changes did |
| 1130 | // occur then return a "not loaded" result so that |size| and |address| |
| 1131 | // aren't expected to be accurate. |
| 1132 | if ((current_changes & kModuleInformationChanging) != 0 || |
| 1133 | changes.load(std::memory_order_seq_cst) != current_changes) { |
| 1134 | info->is_loaded = false; |
| 1135 | } |
| 1136 |
| 1137 | // Copy out the static information. These never change so don't have to be |
| 1138 | // protected by the atomic |current_changes| operations. |
| 1139 | info->size = static_cast<size_t>(size); |
| 1140 | info->timestamp = timestamp; |
| 1141 | info->age = age; |
| 1142 | memcpy(info->identifier, identifier, sizeof(info->identifier)); |
| 1143 |
| 1144 | if (offsetof(ModuleInfoRecord, pickle) + pickle_size > record_size) |
| 1145 | return false; |
| 1146 | Pickle pickler(pickle, pickle_size); |
| 1147 | PickleIterator iter(pickler); |
| 1148 | return iter.ReadString(&info->file) && iter.ReadString(&info->debug_file); |
| 1149 | } |
| 1150 |
| 1151 | GlobalActivityTracker::ModuleInfoRecord* |
| 1152 | GlobalActivityTracker::ModuleInfoRecord::CreateFrom( |
| 1153 | const GlobalActivityTracker::ModuleInfo& info, |
| 1154 | PersistentMemoryAllocator* allocator) { |
| 1155 | Pickle pickler; |
| 1156 | pickler.WriteString(info.file); |
| 1157 | pickler.WriteString(info.debug_file); |
| 1158 | size_t required_size = offsetof(ModuleInfoRecord, pickle) + pickler.size(); |
| 1159 | ModuleInfoRecord* record = allocator->New<ModuleInfoRecord>(required_size); |
| 1160 | if (!record) |
| 1161 | return nullptr; |
| 1162 |
| 1163 | // These fields never changes and are done before the record is made |
| 1164 | // iterable so no thread protection is necessary. |
| 1165 | record->size = info.size; |
| 1166 | record->timestamp = info.timestamp; |
| 1167 | record->age = info.age; |
| 1168 | memcpy(record->identifier, info.identifier, sizeof(identifier)); |
| 1169 | memcpy(record->pickle, pickler.data(), pickler.size()); |
| 1170 | record->pickle_size = pickler.size(); |
| 1171 | record->changes.store(0, std::memory_order_relaxed); |
| 1172 |
| 1173 | // Initialize the owner info. |
| 1174 | record->owner.Release_Initialize(); |
| 1175 |
| 1176 | // Now set those fields that can change. |
| 1177 | bool success = record->UpdateFrom(info); |
| 1178 | DCHECK(success); |
| 1179 | return record; |
| 1180 | } |
| 1181 |
| 1182 | bool GlobalActivityTracker::ModuleInfoRecord::UpdateFrom( |
| 1183 | const GlobalActivityTracker::ModuleInfo& info) { |
| 1184 | // Updates can occur after the record is made visible so make changes atomic. |
| 1185 | // A "strong" exchange ensures no false failures. |
| 1186 | uint32_t old_changes = changes.load(std::memory_order_relaxed); |
| 1187 | uint32_t new_changes = old_changes | kModuleInformationChanging; |
| 1188 | if ((old_changes & kModuleInformationChanging) != 0 || |
| 1189 | !changes.compare_exchange_strong(old_changes, new_changes, |
| 1190 | std::memory_order_acquire, |
| 1191 | std::memory_order_acquire)) { |
| 1192 | NOTREACHED() << "Multiple sources are updating module information."; |
| 1193 | return false; |
| 1194 | } |
| 1195 |
| 1196 | loaded = info.is_loaded ? 1 : 0; |
| 1197 | address = info.address; |
| 1198 | load_time = Time::Now().ToInternalValue(); |
| 1199 |
| 1200 | bool success = changes.compare_exchange_strong(new_changes, old_changes + 1, |
| 1201 | std::memory_order_release, |
| 1202 | std::memory_order_relaxed); |
| 1203 | DCHECK(success); |
| 1204 | return true; |
| 1205 | } |
| 1206 |
| 1207 | GlobalActivityTracker::ScopedThreadActivity::ScopedThreadActivity( |
| 1208 | const void* program_counter, |
| 1209 | const void* origin, |
| 1210 | Activity::Type type, |
| 1211 | const ActivityData& data, |
| 1212 | bool lock_allowed) |
| 1213 | : ThreadActivityTracker::ScopedActivity(GetOrCreateTracker(lock_allowed), |
| 1214 | program_counter, |
| 1215 | origin, |
| 1216 | type, |
| 1217 | data) {} |
| 1218 |
| 1219 | GlobalActivityTracker::ScopedThreadActivity::~ScopedThreadActivity() { |
| 1220 | if (tracker_ && tracker_->HasUserData(activity_id_)) { |
| 1221 | GlobalActivityTracker* global = GlobalActivityTracker::Get(); |
| 1222 | AutoLock lock(global->user_data_allocator_lock_); |
| 1223 | tracker_->ReleaseUserData(activity_id_, &global->user_data_allocator_); |
| 1224 | } |
| 1225 | } |
| 1226 |
| 1227 | ActivityUserData& GlobalActivityTracker::ScopedThreadActivity::user_data() { |
| 1228 | if (!user_data_) { |
| 1229 | if (tracker_) { |
| 1230 | GlobalActivityTracker* global = GlobalActivityTracker::Get(); |
| 1231 | AutoLock lock(global->user_data_allocator_lock_); |
| 1232 | user_data_ = |
| 1233 | tracker_->GetUserData(activity_id_, &global->user_data_allocator_); |
| 1234 | } else { |
| 1235 | user_data_ = std::make_unique<ActivityUserData>(); |
| 1236 | } |
| 1237 | } |
| 1238 | return *user_data_; |
| 1239 | } |
| 1240 |
| 1241 | GlobalActivityTracker::ThreadSafeUserData::ThreadSafeUserData(void* memory, |
| 1242 | size_t size, |
| 1243 | int64_t pid) |
| 1244 | : ActivityUserData(memory, size, pid) {} |
| 1245 |
| 1246 | GlobalActivityTracker::ThreadSafeUserData::~ThreadSafeUserData() = default; |
| 1247 |
| 1248 | void* GlobalActivityTracker::ThreadSafeUserData::Set(StringPiece name, |
| 1249 | ValueType type, |
| 1250 | const void* memory, |
| 1251 | size_t size) { |
| 1252 | AutoLock lock(data_lock_); |
| 1253 | return ActivityUserData::Set(name, type, memory, size); |
| 1254 | } |
| 1255 |
| 1256 | GlobalActivityTracker::ManagedActivityTracker::ManagedActivityTracker( |
| 1257 | PersistentMemoryAllocator::Reference mem_reference, |
| 1258 | void* base, |
| 1259 | size_t size) |
| 1260 | : ThreadActivityTracker(base, size), |
| 1261 | mem_reference_(mem_reference), |
| 1262 | mem_base_(base) {} |
| 1263 |
| 1264 | GlobalActivityTracker::ManagedActivityTracker::~ManagedActivityTracker() { |
| 1265 | // The global |g_tracker_| must point to the owner of this class since all |
| 1266 | // objects of this type must be destructed before |g_tracker_| can be changed |
| 1267 | // (something that only occurs in tests). |
| 1268 | DCHECK(g_tracker_); |
| 1269 | GlobalActivityTracker::Get()->ReturnTrackerMemory(this); |
| 1270 | } |
| 1271 |
| 1272 | void GlobalActivityTracker::CreateWithAllocator( |
| 1273 | std::unique_ptr<PersistentMemoryAllocator> allocator, |
| 1274 | int stack_depth, |
| 1275 | int64_t process_id) { |
| 1276 | // There's no need to do anything with the result. It is self-managing. |
| 1277 | GlobalActivityTracker* global_tracker = |
| 1278 | new GlobalActivityTracker(std::move(allocator), stack_depth, process_id); |
| 1279 | // Create a tracker for this thread since it is known. |
| 1280 | global_tracker->CreateTrackerForCurrentThread(); |
| 1281 | } |
| 1282 |
| 1283 | #if !defined(OS_NACL) |
| 1284 | // static |
| 1285 | bool GlobalActivityTracker::CreateWithFile(const FilePath& file_path, |
| 1286 | size_t size, |
| 1287 | uint64_t id, |
| 1288 | StringPiece name, |
| 1289 | int stack_depth) { |
| 1290 | DCHECK(!file_path.empty()); |
| 1291 | DCHECK_GE(static_cast<uint64_t>(std::numeric_limits<int64_t>::max()), size); |
| 1292 |
| 1293 | // Create and map the file into memory and make it globally available. |
| 1294 | std::unique_ptr<MemoryMappedFile> mapped_file(new MemoryMappedFile()); |
| 1295 | bool success = mapped_file->Initialize( |
| 1296 | File(file_path, File::FLAG_CREATE_ALWAYS | File::FLAG_READ | |
| 1297 | File::FLAG_WRITE | File::FLAG_SHARE_DELETE), |
| 1298 | {0, size}, MemoryMappedFile::READ_WRITE_EXTEND); |
| 1299 | if (!success) |
| 1300 | return false; |
| 1301 | if (!FilePersistentMemoryAllocator::IsFileAcceptable(*mapped_file, false)) |
| 1302 | return false; |
| 1303 | CreateWithAllocator(std::make_unique<FilePersistentMemoryAllocator>( |
| 1304 | std::move(mapped_file), size, id, name, false), |
| 1305 | stack_depth, 0); |
| 1306 | return true; |
| 1307 | } |
| 1308 | #endif // !defined(OS_NACL) |
| 1309 |
| 1310 | // static |
| 1311 | bool GlobalActivityTracker::CreateWithLocalMemory(size_t size, |
| 1312 | uint64_t id, |
| 1313 | StringPiece name, |
| 1314 | int stack_depth, |
| 1315 | int64_t process_id) { |
| 1316 | CreateWithAllocator( |
| 1317 | std::make_unique<LocalPersistentMemoryAllocator>(size, id, name), |
| 1318 | stack_depth, process_id); |
| 1319 | return true; |
| 1320 | } |
| 1321 |
| 1322 | // static |
| 1323 | bool GlobalActivityTracker::CreateWithSharedMemory( |
| 1324 | base::WritableSharedMemoryMapping mapping, |
| 1325 | uint64_t id, |
| 1326 | StringPiece name, |
| 1327 | int stack_depth) { |
| 1328 | if (!mapping.IsValid() || |
| 1329 | !WritableSharedPersistentMemoryAllocator::IsSharedMemoryAcceptable( |
| 1330 | mapping)) { |
| 1331 | return false; |
| 1332 | } |
| 1333 | CreateWithAllocator(std::make_unique<WritableSharedPersistentMemoryAllocator>( |
| 1334 | std::move(mapping), id, name), |
| 1335 | stack_depth, 0); |
| 1336 | return true; |
| 1337 | } |
| 1338 |
| 1339 | // static |
| 1340 | void GlobalActivityTracker::SetForTesting( |
| 1341 | std::unique_ptr<GlobalActivityTracker> tracker) { |
| 1342 | CHECK(!subtle::NoBarrier_Load(&g_tracker_)); |
| 1343 | subtle::Release_Store(&g_tracker_, |
| 1344 | reinterpret_cast<uintptr_t>(tracker.release())); |
| 1345 | } |
| 1346 |
| 1347 | // static |
| 1348 | std::unique_ptr<GlobalActivityTracker> |
| 1349 | GlobalActivityTracker::ReleaseForTesting() { |
| 1350 | GlobalActivityTracker* tracker = Get(); |
| 1351 | if (!tracker) |
| 1352 | return nullptr; |
| 1353 |
| 1354 | // Thread trackers assume that the global tracker is present for some |
| 1355 | // operations so ensure that there aren't any. |
| 1356 | tracker->ReleaseTrackerForCurrentThreadForTesting(); |
| 1357 | DCHECK_EQ(0, tracker->thread_tracker_count_.load(std::memory_order_relaxed)); |
| 1358 |
| 1359 | subtle::Release_Store(&g_tracker_, 0); |
| 1360 | return WrapUnique(tracker); |
| 1361 | } |
| 1362 |
| 1363 | ThreadActivityTracker* GlobalActivityTracker::CreateTrackerForCurrentThread() { |
| 1364 | // It is not safe to use TLS once TLS has been destroyed. |
| 1365 | if (base::ThreadLocalStorage::HasBeenDestroyed()) |
| 1366 | return nullptr; |
| 1367 |
| 1368 | DCHECK(!this_thread_tracker_.Get()); |
| 1369 |
| 1370 | PersistentMemoryAllocator::Reference mem_reference; |
| 1371 |
| 1372 | { |
| 1373 | base::AutoLock autolock(thread_tracker_allocator_lock_); |
| 1374 | mem_reference = thread_tracker_allocator_.GetObjectReference(); |
| 1375 | } |
| 1376 |
| 1377 | if (!mem_reference) { |
| 1378 | // Failure. This shouldn't happen. But be graceful if it does, probably |
| 1379 | // because the underlying allocator wasn't given enough memory to satisfy |
| 1380 | // to all possible requests. |
| 1381 | NOTREACHED(); |
| 1382 |
| 1383 | // Return null, just as if tracking wasn't enabled. |
| 1384 | return nullptr; |
| 1385 | } |
| 1386 |
| 1387 | // Convert the memory block found above into an actual memory address. |
| 1388 | // Doing the conversion as a Header object enacts the 32/64-bit size |
| 1389 | // consistency checks which would not otherwise be done. |
| 1390 | DCHECK(mem_reference); |
| 1391 | void* mem_base; |
| 1392 | mem_base = |
| 1393 | allocator_->GetAsObject<ThreadActivityTracker::Header>(mem_reference); |
| 1394 |
| 1395 | DCHECK(mem_base); |
| 1396 | DCHECK_LE(stack_memory_size_, allocator_->GetAllocSize(mem_reference)); |
| 1397 |
| 1398 | // Create a tracker with the acquired memory and set it as the tracker |
| 1399 | // for this particular thread in thread-local-storage. |
| 1400 | auto tracker = std::make_unique<ManagedActivityTracker>( |
| 1401 | mem_reference, mem_base, stack_memory_size_); |
| 1402 | DCHECK(tracker->IsValid()); |
| 1403 | auto* tracker_raw = tracker.get(); |
| 1404 | this_thread_tracker_.Set(std::move(tracker)); |
| 1405 | thread_tracker_count_.fetch_add(1, std::memory_order_relaxed); |
| 1406 | return tracker_raw; |
| 1407 | } |
| 1408 |
| 1409 | void GlobalActivityTracker::ReleaseTrackerForCurrentThreadForTesting() { |
| 1410 | if (this_thread_tracker_.Get()) |
| 1411 | this_thread_tracker_.Set(nullptr); |
| 1412 | } |
| 1413 |
| 1414 | void GlobalActivityTracker::SetBackgroundTaskRunner( |
| 1415 | const scoped_refptr<SequencedTaskRunner>& runner) { |
| 1416 | AutoLock lock(global_tracker_lock_); |
| 1417 | background_task_runner_ = std::move(runner); |
| 1418 | } |
| 1419 |
| 1420 | void GlobalActivityTracker::SetProcessExitCallback( |
| 1421 | ProcessExitCallback callback) { |
| 1422 | AutoLock lock(global_tracker_lock_); |
| 1423 | process_exit_callback_ = callback; |
| 1424 | } |
| 1425 |
| 1426 | void GlobalActivityTracker::RecordProcessLaunch( |
| 1427 | ProcessId process_id, |
| 1428 | const FilePath::StringType& cmd) { |
| 1429 | const int64_t pid = process_id; |
| 1430 | DCHECK_NE(GetProcessId(), pid); |
| 1431 | DCHECK_NE(0, pid); |
| 1432 |
| 1433 | base::AutoLock lock(global_tracker_lock_); |
| 1434 | if (base::Contains(known_processes_, pid)) { |
| 1435 | // TODO(bcwhite): Measure this in UMA. |
| 1436 | NOTREACHED() << "Process #" << process_id |
| 1437 | << " was previously recorded as \"launched\"" |
| 1438 | << " with no corresponding exit.\n" |
| 1439 | << known_processes_[pid]; |
| 1440 | known_processes_.erase(pid); |
| 1441 | } |
| 1442 |
| 1443 | #if defined(OS_WIN) |
| 1444 | known_processes_.insert(std::make_pair(pid, WideToUTF8(cmd))); |
| 1445 | #else |
| 1446 | known_processes_.insert(std::make_pair(pid, cmd)); |
| 1447 | #endif |
| 1448 | } |
| 1449 |
| 1450 | void GlobalActivityTracker::RecordProcessLaunch( |
| 1451 | ProcessId process_id, |
| 1452 | const FilePath::StringType& exe, |
| 1453 | const FilePath::StringType& args) { |
| 1454 | if (exe.find(FILE_PATH_LITERAL(" "))) { |
| 1455 | RecordProcessLaunch(process_id, |
| 1456 | FilePath::StringType(FILE_PATH_LITERAL("\"")) + exe + |
| 1457 | FILE_PATH_LITERAL("\" ") + args); |
| 1458 | } else { |
| 1459 | RecordProcessLaunch(process_id, exe + FILE_PATH_LITERAL(' ') + args); |
| 1460 | } |
| 1461 | } |
| 1462 |
| 1463 | void GlobalActivityTracker::RecordProcessExit(ProcessId process_id, |
| 1464 | int exit_code) { |
| 1465 | const int64_t pid = process_id; |
| 1466 | DCHECK_NE(GetProcessId(), pid); |
| 1467 | DCHECK_NE(0, pid); |
| 1468 |
| 1469 | scoped_refptr<SequencedTaskRunner> task_runner; |
| 1470 | std::string command_line; |
| 1471 | { |
| 1472 | base::AutoLock lock(global_tracker_lock_); |
| 1473 | task_runner = background_task_runner_; |
| 1474 | auto found = known_processes_.find(pid); |
| 1475 | if (found != known_processes_.end()) { |
| 1476 | command_line = std::move(found->second); |
| 1477 | known_processes_.erase(found); |
| 1478 | } else { |
| 1479 | DLOG(ERROR) << "Recording exit of unknown process #" << process_id; |
| 1480 | } |
| 1481 | } |
| 1482 |
| 1483 | // Use the current time to differentiate the process that just exited |
| 1484 | // from any that might be created in the future with the same ID. |
| 1485 | int64_t now_stamp = Time::Now().ToInternalValue(); |
| 1486 |
| 1487 | // The persistent allocator is thread-safe so run the iteration and |
| 1488 | // adjustments on a worker thread if one was provided. |
| 1489 | if (task_runner && !task_runner->RunsTasksInCurrentSequence()) { |
| 1490 | task_runner->PostTask( |
| 1491 | FROM_HERE, |
| 1492 | BindOnce(&GlobalActivityTracker::CleanupAfterProcess, Unretained(this), |
| 1493 | pid, now_stamp, exit_code, std::move(command_line))); |
| 1494 | return; |
| 1495 | } |
| 1496 |
| 1497 | CleanupAfterProcess(pid, now_stamp, exit_code, std::move(command_line)); |
| 1498 | } |
| 1499 |
| 1500 | void GlobalActivityTracker::SetProcessPhase(ProcessPhase phase) { |
| 1501 | process_data().SetInt(kProcessPhaseDataKey, phase); |
| 1502 | } |
| 1503 |
| 1504 | void GlobalActivityTracker::CleanupAfterProcess(int64_t process_id, |
| 1505 | int64_t exit_stamp, |
| 1506 | int exit_code, |
| 1507 | std::string&& command_line) { |
| 1508 | // The process may not have exited cleanly so its necessary to go through |
| 1509 | // all the data structures it may have allocated in the persistent memory |
| 1510 | // segment and mark them as "released". This will allow them to be reused |
| 1511 | // later on. |
| 1512 |
| 1513 | PersistentMemoryAllocator::Iterator iter(allocator_.get()); |
| 1514 | PersistentMemoryAllocator::Reference ref; |
| 1515 |
| 1516 | ProcessExitCallback process_exit_callback; |
| 1517 | { |
| 1518 | AutoLock lock(global_tracker_lock_); |
| 1519 | process_exit_callback = process_exit_callback_; |
| 1520 | } |
| 1521 | if (process_exit_callback) { |
| 1522 | // Find the processes user-data record so the process phase can be passed |
| 1523 | // to the callback. |
| 1524 | ActivityUserData::Snapshot process_data_snapshot; |
| 1525 | while ((ref = iter.GetNextOfType(kTypeIdProcessDataRecord)) != 0) { |
| 1526 | const void* memory = allocator_->GetAsArray<char>( |
| 1527 | ref, kTypeIdProcessDataRecord, PersistentMemoryAllocator::kSizeAny); |
| 1528 | if (!memory) |
| 1529 | continue; |
| 1530 | int64_t found_id; |
| 1531 | int64_t create_stamp; |
| 1532 | if (ActivityUserData::GetOwningProcessId(memory, &found_id, |
| 1533 | &create_stamp)) { |
| 1534 | if (found_id == process_id && create_stamp < exit_stamp) { |
| 1535 | const ActivityUserData process_data(const_cast<void*>(memory), |
| 1536 | allocator_->GetAllocSize(ref)); |
| 1537 | process_data.CreateSnapshot(&process_data_snapshot); |
| 1538 | break; // No need to look for any others. |
| 1539 | } |
| 1540 | } |
| 1541 | } |
| 1542 | iter.Reset(); // So it starts anew when used below. |
| 1543 |
| 1544 | // Record the process's phase at exit so callback doesn't need to go |
| 1545 | // searching based on a private key value. |
| 1546 | ProcessPhase exit_phase = PROCESS_PHASE_UNKNOWN; |
| 1547 | auto phase = process_data_snapshot.find(kProcessPhaseDataKey); |
| 1548 | if (phase != process_data_snapshot.end()) |
| 1549 | exit_phase = static_cast<ProcessPhase>(phase->second.GetInt()); |
| 1550 |
| 1551 | // Perform the callback. |
| 1552 | process_exit_callback.Run(process_id, exit_stamp, exit_code, exit_phase, |
| 1553 | std::move(command_line), |
| 1554 | std::move(process_data_snapshot)); |
| 1555 | } |
| 1556 |
| 1557 | // Find all allocations associated with the exited process and free them. |
| 1558 | uint32_t type; |
| 1559 | while ((ref = iter.GetNext(&type)) != 0) { |
| 1560 | switch (type) { |
| 1561 | case kTypeIdActivityTracker: |
| 1562 | case kTypeIdUserDataRecord: |
| 1563 | case kTypeIdProcessDataRecord: |
| 1564 | case ModuleInfoRecord::kPersistentTypeId: { |
| 1565 | const void* memory = allocator_->GetAsArray<char>( |
| 1566 | ref, type, PersistentMemoryAllocator::kSizeAny); |
| 1567 | if (!memory) |
| 1568 | continue; |
| 1569 | int64_t found_id; |
| 1570 | int64_t create_stamp; |
| 1571 |
| 1572 | // By convention, the OwningProcess structure is always the first |
| 1573 | // field of the structure so there's no need to handle all the |
| 1574 | // cases separately. |
| 1575 | if (OwningProcess::GetOwningProcessId(memory, &found_id, |
| 1576 | &create_stamp)) { |
| 1577 | // Only change the type to be "free" if the process ID matches and |
| 1578 | // the creation time is before the exit time (so PID re-use doesn't |
| 1579 | // cause the erasure of something that is in-use). Memory is cleared |
| 1580 | // here, rather than when it's needed, so as to limit the impact at |
| 1581 | // that critical time. |
| 1582 | if (found_id == process_id && create_stamp < exit_stamp) |
| 1583 | allocator_->ChangeType(ref, ~type, type, /*clear=*/true); |
| 1584 | } |
| 1585 | } break; |
| 1586 | } |
| 1587 | } |
| 1588 | } |
| 1589 |
| 1590 | void GlobalActivityTracker::RecordLogMessage(StringPiece message) { |
| 1591 | // Allocate at least one extra byte so the string is NUL terminated. All |
| 1592 | // memory returned by the allocator is guaranteed to be zeroed. |
| 1593 | PersistentMemoryAllocator::Reference ref = |
| 1594 | allocator_->Allocate(message.size() + 1, kTypeIdGlobalLogMessage); |
| 1595 | char* memory = allocator_->GetAsArray<char>(ref, kTypeIdGlobalLogMessage, |
| 1596 | message.size() + 1); |
| 1597 | if (memory) { |
| 1598 | memcpy(memory, message.data(), message.size()); |
| 1599 | allocator_->MakeIterable(ref); |
| 1600 | } |
| 1601 | } |
| 1602 |
| 1603 | void GlobalActivityTracker::RecordModuleInfo(const ModuleInfo& info) { |
| 1604 | AutoLock lock(modules_lock_); |
| 1605 | auto found = modules_.find(info.file); |
| 1606 | if (found != modules_.end()) { |
| 1607 | ModuleInfoRecord* record = found->second; |
| 1608 | DCHECK(record); |
| 1609 |
| 1610 | // Update the basic state of module information that has been already |
| 1611 | // recorded. It is assumed that the string information (identifier, |
| 1612 | // version, etc.) remain unchanged which means that there's no need |
| 1613 | // to create a new record to accommodate a possibly longer length. |
| 1614 | record->UpdateFrom(info); |
| 1615 | return; |
| 1616 | } |
| 1617 |
| 1618 | ModuleInfoRecord* record = |
| 1619 | ModuleInfoRecord::CreateFrom(info, allocator_.get()); |
| 1620 | if (!record) |
| 1621 | return; |
| 1622 | allocator_->MakeIterable(record); |
| 1623 | modules_.emplace(info.file, record); |
| 1624 | } |
| 1625 |
| 1626 | void GlobalActivityTracker::RecordException(const void* pc, |
| 1627 | const void* origin, |
| 1628 | uint32_t code) { |
| 1629 | RecordExceptionImpl(pc, origin, code); |
| 1630 | } |
| 1631 |
| 1632 | void GlobalActivityTracker::MarkDeleted() { |
| 1633 | allocator_->SetMemoryState(PersistentMemoryAllocator::MEMORY_DELETED); |
| 1634 | } |
| 1635 |
| 1636 | GlobalActivityTracker::GlobalActivityTracker( |
| 1637 | std::unique_ptr<PersistentMemoryAllocator> allocator, |
| 1638 | int stack_depth, |
| 1639 | int64_t process_id) |
| 1640 | : allocator_(std::move(allocator)), |
| 1641 | stack_memory_size_(ThreadActivityTracker::SizeForStackDepth(stack_depth)), |
| 1642 | process_id_(process_id == 0 ? GetCurrentProcId() : process_id), |
| 1643 | thread_tracker_count_(0), |
| 1644 | thread_tracker_allocator_(allocator_.get(), |
| 1645 | kTypeIdActivityTracker, |
| 1646 | kTypeIdActivityTrackerFree, |
| 1647 | stack_memory_size_, |
| 1648 | kCachedThreadMemories, |
| 1649 | /*make_iterable=*/true), |
| 1650 | user_data_allocator_(allocator_.get(), |
| 1651 | kTypeIdUserDataRecord, |
| 1652 | kTypeIdUserDataRecordFree, |
| 1653 | kUserDataSize, |
| 1654 | kCachedUserDataMemories, |
| 1655 | /*make_iterable=*/true), |
| 1656 | process_data_(allocator_->GetAsArray<char>( |
| 1657 | AllocateFrom(allocator_.get(), |
| 1658 | kTypeIdProcessDataRecordFree, |
| 1659 | kProcessDataSize, |
| 1660 | kTypeIdProcessDataRecord), |
| 1661 | kTypeIdProcessDataRecord, |
| 1662 | kProcessDataSize), |
| 1663 | kProcessDataSize, |
| 1664 | process_id_) { |
| 1665 | DCHECK_NE(0, process_id_); |
| 1666 |
| 1667 | // Ensure that there is no other global object and then make this one such. |
| 1668 | DCHECK(!g_tracker_); |
| 1669 | subtle::Release_Store(&g_tracker_, reinterpret_cast<uintptr_t>(this)); |
| 1670 |
| 1671 | // The data records must be iterable in order to be found by an analyzer. |
| 1672 | allocator_->MakeIterable(allocator_->GetAsReference( |
| 1673 | process_data_.GetBaseAddress(), kTypeIdProcessDataRecord)); |
| 1674 |
| 1675 | // Note that this process has launched. |
| 1676 | SetProcessPhase(PROCESS_LAUNCHED); |
| 1677 | } |
| 1678 |
| 1679 | GlobalActivityTracker::~GlobalActivityTracker() { |
| 1680 | DCHECK(Get() == nullptr || Get() == this); |
| 1681 | DCHECK_EQ(0, thread_tracker_count_.load(std::memory_order_relaxed)); |
| 1682 | subtle::Release_Store(&g_tracker_, 0); |
| 1683 | } |
| 1684 |
| 1685 | void GlobalActivityTracker::ReturnTrackerMemory( |
| 1686 | ManagedActivityTracker* tracker) { |
| 1687 | PersistentMemoryAllocator::Reference mem_reference = tracker->mem_reference_; |
| 1688 | void* mem_base = tracker->mem_base_; |
| 1689 | DCHECK(mem_reference); |
| 1690 | DCHECK(mem_base); |
| 1691 |
| 1692 | // Remove the destructed tracker from the set of known ones. |
| 1693 | DCHECK_LE(1, thread_tracker_count_.load(std::memory_order_relaxed)); |
| 1694 | thread_tracker_count_.fetch_sub(1, std::memory_order_relaxed); |
| 1695 |
| 1696 | // Release this memory for re-use at a later time. |
| 1697 | base::AutoLock autolock(thread_tracker_allocator_lock_); |
| 1698 | thread_tracker_allocator_.ReleaseObjectReference(mem_reference); |
| 1699 | } |
| 1700 |
| 1701 | void GlobalActivityTracker::RecordExceptionImpl(const void* pc, |
| 1702 | const void* origin, |
| 1703 | uint32_t code) { |
| 1704 | // Get an existing tracker for this thread. It's not possible to create |
| 1705 | // one at this point because such would involve memory allocations and |
| 1706 | // other potentially complex operations that can cause failures if done |
| 1707 | // within an exception handler. In most cases various operations will |
| 1708 | // have already created the tracker so this shouldn't generally be a |
| 1709 | // problem. |
| 1710 | ThreadActivityTracker* tracker = GetTrackerForCurrentThread(); |
| 1711 | if (!tracker) |
| 1712 | return; |
| 1713 |
| 1714 | tracker->RecordExceptionActivity(pc, origin, Activity::ACT_EXCEPTION, |
| 1715 | ActivityData::ForException(code)); |
| 1716 | } |
| 1717 |
| 1718 | ScopedActivity::ScopedActivity(const void* program_counter, |
| 1719 | uint8_t action, |
| 1720 | uint32_t id, |
| 1721 | int32_t info) |
| 1722 | : GlobalActivityTracker::ScopedThreadActivity( |
| 1723 | program_counter, |
| 1724 | nullptr, |
| 1725 | static_cast<Activity::Type>(Activity::ACT_GENERIC | action), |
| 1726 | ActivityData::ForGeneric(id, info), |
| 1727 | /*lock_allowed=*/true), |
| 1728 | id_(id) { |
| 1729 | // The action must not affect the category bits of the activity type. |
| 1730 | DCHECK_EQ(0, action & Activity::ACT_CATEGORY_MASK); |
| 1731 | } |
| 1732 |
| 1733 | void ScopedActivity::ChangeAction(uint8_t action) { |
| 1734 | DCHECK_EQ(0, action & Activity::ACT_CATEGORY_MASK); |
| 1735 | ChangeTypeAndData(static_cast<Activity::Type>(Activity::ACT_GENERIC | action), |
| 1736 | kNullActivityData); |
| 1737 | } |
| 1738 |
| 1739 | void ScopedActivity::ChangeInfo(int32_t info) { |
| 1740 | ChangeTypeAndData(Activity::ACT_NULL, ActivityData::ForGeneric(id_, info)); |
| 1741 | } |
| 1742 |
| 1743 | void ScopedActivity::ChangeActionAndInfo(uint8_t action, int32_t info) { |
| 1744 | DCHECK_EQ(0, action & Activity::ACT_CATEGORY_MASK); |
| 1745 | ChangeTypeAndData(static_cast<Activity::Type>(Activity::ACT_GENERIC | action), |
| 1746 | ActivityData::ForGeneric(id_, info)); |
| 1747 | } |
| 1748 |
| 1749 | ScopedTaskRunActivity::ScopedTaskRunActivity( |
| 1750 | const void* program_counter, |
| 1751 | const base::PendingTask& task) |
| 1752 | : GlobalActivityTracker::ScopedThreadActivity( |
| 1753 | program_counter, |
| 1754 | task.posted_from.program_counter(), |
| 1755 | Activity::ACT_TASK_RUN, |
| 1756 | ActivityData::ForTask(task.sequence_num), |
| 1757 | /*lock_allowed=*/true) {} |
| 1758 |
| 1759 | ScopedLockAcquireActivity::ScopedLockAcquireActivity( |
| 1760 | const void* program_counter, |
| 1761 | const base::internal::LockImpl* lock) |
| 1762 | : GlobalActivityTracker::ScopedThreadActivity( |
| 1763 | program_counter, |
| 1764 | nullptr, |
| 1765 | Activity::ACT_LOCK_ACQUIRE, |
| 1766 | ActivityData::ForLock(lock), |
| 1767 | /*lock_allowed=*/false) {} |
| 1768 |
| 1769 | ScopedEventWaitActivity::ScopedEventWaitActivity( |
| 1770 | const void* program_counter, |
| 1771 | const base::WaitableEvent* event) |
| 1772 | : GlobalActivityTracker::ScopedThreadActivity( |
| 1773 | program_counter, |
| 1774 | nullptr, |
| 1775 | Activity::ACT_EVENT_WAIT, |
| 1776 | ActivityData::ForEvent(event), |
| 1777 | /*lock_allowed=*/true) {} |
| 1778 |
| 1779 | ScopedThreadJoinActivity::ScopedThreadJoinActivity( |
| 1780 | const void* program_counter, |
| 1781 | const base::PlatformThreadHandle* thread) |
| 1782 | : GlobalActivityTracker::ScopedThreadActivity( |
| 1783 | program_counter, |
| 1784 | nullptr, |
| 1785 | Activity::ACT_THREAD_JOIN, |
| 1786 | ActivityData::ForThread(*thread), |
| 1787 | /*lock_allowed=*/true) {} |
| 1788 |
| 1789 | #if !defined(OS_NACL) && !defined(OS_IOS) |
| 1790 | ScopedProcessWaitActivity::ScopedProcessWaitActivity( |
| 1791 | const void* program_counter, |
| 1792 | const base::Process* process) |
| 1793 | : GlobalActivityTracker::ScopedThreadActivity( |
| 1794 | program_counter, |
| 1795 | nullptr, |
| 1796 | Activity::ACT_PROCESS_WAIT, |
| 1797 | ActivityData::ForProcess(process->Pid()), |
| 1798 | /*lock_allowed=*/true) {} |
| 1799 | #endif |
| 1800 |
| 1801 | } // namespace debug |
| 1802 | } // namespace base |
| 1803 |