| 6 |
| // about the state of the application for analysis both while it is running |
| 7 | // and after it has terminated unexpectedly. Its primary purpose is to help |
| 8 | // locate reasons the browser becomes unresponsive by providing insight into |
| 9 | // what all the various threads and processes are (or were) doing. |
| 10 |
| 11 | #ifndef BASE_DEBUG_ACTIVITY_TRACKER_H_ |
| 12 | #define BASE_DEBUG_ACTIVITY_TRACKER_H_ |
| 13 |
| 14 | // std::atomic is undesired due to performance issues when used as global |
| 15 | // variables. There are no such instances here. This module uses the |
| 16 | // PersistentMemoryAllocator which also uses std::atomic and is written |
| 17 | // by the same author. |
| 18 | #include <atomic> |
| 19 | #include <map> |
| 20 | #include <memory> |
| 21 | #include <string> |
| 22 | #include <vector> |
| 23 |
| 24 | #include "base/atomicops.h" |
| 25 | #include "base/base_export.h" |
| 26 | #include "base/callback.h" |
| 27 | #include "base/compiler_specific.h" |
| 28 | #include "base/gtest_prod_util.h" |
| 29 | #include "base/location.h" |
| 30 | #include "base/memory/shared_memory_mapping.h" |
| 31 | #include "base/metrics/persistent_memory_allocator.h" |
| 32 | #include "base/process/process_handle.h" |
| 33 | #include "base/sequenced_task_runner.h" |
| 34 | #include "base/strings/string_piece.h" |
| 35 | #include "base/strings/utf_string_conversions.h" |
| 36 | #include "base/threading/platform_thread.h" |
| 37 | #include "base/threading/thread_local.h" |
| 38 |
| 39 | namespace base { |
| 40 |
| 41 | struct PendingTask; |
| 42 |
| 43 | class FilePath; |
| 44 | class Lock; |
| 45 | class PlatformThreadHandle; |
| 46 | class Process; |
| 47 | class WaitableEvent; |
| 48 |
| 49 | namespace debug { |
| 50 |
| 51 | class ThreadActivityTracker; |
| 52 |
| 53 |
| 54 | enum : int { |
| 55 | // The maximum number of call-stack addresses stored per activity. This |
| 56 | // cannot be changed without also changing the version number of the |
| 57 | // structure. See kTypeIdActivityTracker in GlobalActivityTracker. |
| 58 | kActivityCallStackSize = 10, |
| 59 | }; |
| 60 |
| 61 | // A class for keeping all information needed to verify that a structure is |
| 62 | // associated with a given process. |
| 63 | struct OwningProcess { |
| 64 | OwningProcess(); |
| 65 | ~OwningProcess(); |
| 66 |
| 67 | // Initializes structure with the current process id and the current time. |
| 68 | // These can uniquely identify a process. A unique non-zero data_id will be |
| 69 | // set making it possible to tell using atomic reads if the data has changed. |
| 70 | void Release_Initialize(int64_t pid = 0); |
| 71 |
| 72 | // Explicitly sets the process ID. |
| 73 | void SetOwningProcessIdForTesting(int64_t pid, int64_t stamp); |
| 74 |
| 75 | // Gets the associated process ID, in native form, and the creation timestamp |
| 76 | // from memory without loading the entire structure for analysis. This will |
| 77 | // return false if no valid process ID is available. |
| 78 | static bool GetOwningProcessId(const void* memory, |
| 79 | int64_t* out_id, |
| 80 | int64_t* out_stamp); |
| 81 |
| 82 | // SHA1(base::debug::OwningProcess): Increment this if structure changes! |
| 83 | static constexpr uint32_t kPersistentTypeId = 0xB1179672 + 1; |
| 84 |
| 85 | // Expected size for 32/64-bit check by PersistentMemoryAllocator. |
| 86 | static constexpr size_t kExpectedInstanceSize = 24; |
| 87 |
| 88 | std::atomic<uint32_t> data_id; |
| 89 | uint32_t padding; |
| 90 | int64_t process_id; |
| 91 | int64_t create_stamp; |
| 92 | }; |
| 93 |
| 94 | // The data associated with an activity is dependent upon the activity type. |
| 95 | // This union defines all of the various fields. All fields must be explicitly |
| 96 | // sized types to ensure no interoperability problems between 32-bit and |
| 97 | // 64-bit systems. |
| 98 | union ActivityData { |
| 99 | // Expected size for 32/64-bit check. |
| 100 | // TODO(bcwhite): VC2015 doesn't allow statics in unions. Fix when it does. |
| 101 | // static constexpr size_t kExpectedInstanceSize = 8; |
| 102 |
| 103 | // Generic activities don't have any defined structure. |
| 104 | struct { |
| 105 | uint32_t id; // An arbitrary identifier used for association. |
| 106 | int32_t info; // An arbitrary value used for information purposes. |
| 107 | } generic; |
| 108 | struct { |
| 109 | uint64_t sequence_id; // The sequence identifier of the posted task. |
| 110 | } task; |
| 111 | struct { |
| 112 | uint64_t lock_address; // The memory address of the lock object. |
| 113 | } lock; |
| 114 | struct { |
| 115 | uint64_t event_address; // The memory address of the event object. |
| 116 | } event; |
| 117 | struct { |
| 118 | int64_t thread_id; // A unique identifier for a thread within a process. |
| 119 | } thread; |
| 120 | struct { |
| 121 | int64_t process_id; // A unique identifier for a process. |
| 122 | } process; |
| 123 | struct { |
| 124 | uint32_t code; // An "exception code" number. |
| 125 | } exception; |
| 126 |
| 127 | // These methods create an ActivityData object from the appropriate |
| 128 | // parameters. Objects of this type should always be created this way to |
| 129 | // ensure that no fields remain unpopulated should the set of recorded |
| 130 | // fields change. They're defined inline where practical because they |
| 131 | // reduce to loading a small local structure with a few values, roughly |
| 132 | // the same as loading all those values into parameters. |
| 133 |
| 134 | static ActivityData ForGeneric(uint32_t id, int32_t info) { |
| 135 | ActivityData data; |
| 136 | data.generic.id = id; |
| 137 | data.generic.info = info; |
| 138 | return data; |
| 139 | } |
| 140 |
| 141 | static ActivityData ForTask(uint64_t sequence) { |
| 142 | ActivityData data; |
| 143 | data.task.sequence_id = sequence; |
| 144 | return data; |
| 145 | } |
| 146 |
| 147 | static ActivityData ForLock(const void* lock) { |
| 148 | ActivityData data; |
| 149 | data.lock.lock_address = reinterpret_cast<uintptr_t>(lock); |
| 150 | return data; |
| 151 | } |
| 152 |
| 153 | static ActivityData ForEvent(const void* event) { |
| 154 | ActivityData data; |
| 155 | data.event.event_address = reinterpret_cast<uintptr_t>(event); |
| 156 | return data; |
| 157 | } |
| 158 |
| 159 | static ActivityData ForThread(const PlatformThreadHandle& handle); |
| 160 | static ActivityData ForThread(const int64_t id) { |
| 161 | ActivityData data; |
| 162 | data.thread.thread_id = id; |
| 163 | return data; |
| 164 | } |
| 165 |
| 166 | static ActivityData ForProcess(const int64_t id) { |
| 167 | ActivityData data; |
| 168 | data.process.process_id = id; |
| 169 | return data; |
| 170 | } |
| 171 |
| 172 | static ActivityData ForException(const uint32_t code) { |
| 173 | ActivityData data; |
| 174 | data.exception.code = code; |
| 175 | return data; |
| 176 | } |
| 177 | }; |
| 178 |
| 179 | // A "null" activity-data that can be passed to indicate "do not change". |
| 180 | extern const ActivityData kNullActivityData; |
| 181 |
| 182 |
| 183 | // A helper class that is used for managing memory allocations within a |
| 184 | // persistent memory allocator. Instances of this class are NOT thread-safe. |
| 185 | // Use from a single thread or protect access with a lock. |
| 186 | class BASE_EXPORT ActivityTrackerMemoryAllocator { |
| 187 | public: |
| 188 | using Reference = PersistentMemoryAllocator::Reference; |
| 189 |
| 190 | // Creates a instance for allocating objects of a fixed |object_type|, a |
| 191 | // corresponding |object_free| type, and the |object_size|. An internal |
| 192 | // cache of the last |cache_size| released references will be kept for |
| 193 | // quick future fetches. If |make_iterable| then allocated objects will |
| 194 | // be marked "iterable" in the allocator. |
| 195 | ActivityTrackerMemoryAllocator(PersistentMemoryAllocator* allocator, |
| 196 | uint32_t object_type, |
| 197 | uint32_t object_free_type, |
| 198 | size_t object_size, |
| 199 | size_t cache_size, |
| 200 | bool make_iterable); |
| 201 | ~ActivityTrackerMemoryAllocator(); |
| 202 |
| 203 | // Gets a reference to an object of the configured type. This can return |
| 204 | // a null reference if it was not possible to allocate the memory. |
| 205 | Reference GetObjectReference(); |
| 206 |
| 207 | // Returns an object to the "free" pool. |
| 208 | void ReleaseObjectReference(Reference ref); |
| 209 |
| 210 | // Helper function to access an object allocated using this instance. |
| 211 | template <typename T> |
| 212 | T* GetAsObject(Reference ref) { |
| 213 | return allocator_->GetAsObject<T>(ref); |
| 214 | } |
| 215 |
| 216 | // Similar to GetAsObject() but converts references to arrays of objects. |
| 217 | template <typename T> |
| 218 | T* GetAsArray(Reference ref, size_t count) { |
| 219 | return allocator_->GetAsArray<T>(ref, object_type_, count); |
| 220 | } |
| 221 |
| 222 | // The current "used size" of the internal cache, visible for testing. |
| 223 | size_t cache_used() const { return cache_used_; } |
| 224 |
| 225 | private: |
| 226 | PersistentMemoryAllocator* const allocator_; |
| 227 | const uint32_t object_type_; |
| 228 | const uint32_t object_free_type_; |
| 229 | const size_t object_size_; |
| 230 | const size_t cache_size_; |
| 231 | const bool make_iterable_; |
| 232 |
| 233 | // An iterator for going through persistent memory looking for free'd objects. |
| 234 | PersistentMemoryAllocator::Iterator iterator_; |
| 235 |
| 236 | // The cache of released object memories. |
| 237 | std::unique_ptr<Reference[]> cache_values_; |
| 238 | size_t cache_used_; |
| 239 |
| 240 | DISALLOW_COPY_AND_ASSIGN(ActivityTrackerMemoryAllocator); |
| 241 | }; |
| 242 |
| 243 |
| 244 | // This structure is the full contents recorded for every activity pushed |
| 245 | // onto the stack. The |activity_type| indicates what is actually stored in |
| 246 | // the |data| field. All fields must be explicitly sized types to ensure no |
| 247 | // interoperability problems between 32-bit and 64-bit systems. |
| 248 | struct Activity { |
| 249 | // SHA1(base::debug::Activity): Increment this if structure changes! |
| 250 | static constexpr uint32_t kPersistentTypeId = 0x99425159 + 1; |
| 251 | // Expected size for 32/64-bit check. Update this if structure changes! |
| 252 | static constexpr size_t kExpectedInstanceSize = |
| 253 | 48 + 8 * kActivityCallStackSize; |
| 254 |
| 255 | // The type of an activity on the stack. Activities are broken into |
| 256 | // categories with the category ID taking the top 4 bits and the lower |
| 257 | // bits representing an action within that category. This combination |
| 258 | // makes it easy to "switch" based on the type during analysis. |
| 259 | enum Type : uint8_t { |
| 260 | // This "null" constant is used to indicate "do not change" in calls. |
| 261 | ACT_NULL = 0, |
| 262 |
| 263 | // Task activities involve callbacks posted to a thread or thread-pool |
| 264 | // using the PostTask() method or any of its friends. |
| 265 | ACT_TASK = 1 << 4, |
| 266 | ACT_TASK_RUN = ACT_TASK, |
| 267 |
| 268 | // Lock activities involve the acquisition of "mutex" locks. |
| 269 | ACT_LOCK = 2 << 4, |
| 270 | ACT_LOCK_ACQUIRE = ACT_LOCK, |
| 271 | ACT_LOCK_RELEASE, |
| 272 |
| 273 | // Event activities involve operations on a WaitableEvent. |
| 274 | ACT_EVENT = 3 << 4, |
| 275 | ACT_EVENT_WAIT = ACT_EVENT, |
| 276 | ACT_EVENT_SIGNAL, |
| 277 |
| 278 | // Thread activities involve the life management of threads. |
| 279 | ACT_THREAD = 4 << 4, |
| 280 | ACT_THREAD_START = ACT_THREAD, |
| 281 | ACT_THREAD_JOIN, |
| 282 |
| 283 | // Process activities involve the life management of processes. |
| 284 | ACT_PROCESS = 5 << 4, |
| 285 | ACT_PROCESS_START = ACT_PROCESS, |
| 286 | ACT_PROCESS_WAIT, |
| 287 |
| 288 | // Exception activities indicate the occurence of something unexpected. |
| 289 | ACT_EXCEPTION = 14 << 4, |
| 290 |
| 291 | // Generic activities are user defined and can be anything. |
| 292 | ACT_GENERIC = 15 << 4, |
| 293 |
| 294 | // These constants can be used to separate the category and action from |
| 295 | // a combined activity type. |
| 296 | ACT_CATEGORY_MASK = 0xF << 4, |
| 297 | ACT_ACTION_MASK = 0xF |
| 298 | }; |
| 299 |
| 300 | // Internal representation of time. During collection, this is in "ticks" |
| 301 | // but when returned in a snapshot, it is "wall time". |
| 302 | int64_t time_internal; |
| 303 |
| 304 | // The address that pushed the activity onto the stack as a raw number. |
| 305 | uint64_t calling_address; |
| 306 |
| 307 | // The address that is the origin of the activity if it not obvious from |
| 308 | // the call stack. This is useful for things like tasks that are posted |
| 309 | // from a completely different thread though most activities will leave |
| 310 | // it null. |
| 311 | uint64_t origin_address; |
| 312 |
| 313 | // Array of program-counters that make up the top of the call stack. |
| 314 | // Despite the fixed size, this list is always null-terminated. Entries |
| 315 | // after the terminator have no meaning and may or may not also be null. |
| 316 | // The list will be completely empty if call-stack collection is not |
| 317 | // enabled. |
| 318 | uint64_t call_stack[kActivityCallStackSize]; |
| 319 |
| 320 | // Reference to arbitrary user data within the persistent memory segment |
| 321 | // and a unique identifier for it. |
| 322 | uint32_t user_data_ref; |
| 323 | uint32_t user_data_id; |
| 324 |
| 325 | // The (enumerated) type of the activity. This defines what fields of the |
| 326 | // |data| record are valid. |
| 327 | uint8_t activity_type; |
| 328 |
| 329 | // Padding to ensure that the next member begins on a 64-bit boundary |
| 330 | // even on 32-bit builds which ensures inter-operability between CPU |
| 331 | // architectures. New fields can be taken from this space. |
| 332 | uint8_t padding[7]; |
| 333 |
| 334 | // Information specific to the |activity_type|. |
| 335 | ActivityData data; |
| 336 |
| 337 | static void FillFrom(Activity* activity, |
| 338 | const void* program_counter, |
| 339 | const void* origin, |
| 340 | Type type, |
| 341 | const ActivityData& data); |
| 342 | }; |
| 343 |
| 344 | // This class manages arbitrary user data that can be associated with activities |
| 345 | // done by a thread by supporting key/value pairs of any type. This can provide |
| 346 | // additional information during debugging. It is also used to store arbitrary |
| 347 | // global data. All updates must be done from the same thread though other |
| 348 | // threads can read it concurrently if they create new objects using the same |
| 349 | // memory. For a thread-safe version, see ThreadSafeUserData later on. |
| 350 | class BASE_EXPORT ActivityUserData { |
| 351 | public: |
| 352 | // List of known value type. REFERENCE types must immediately follow the non- |
| 353 | // external types. |
| 354 | enum ValueType : uint8_t { |
| 355 | END_OF_VALUES = 0, |
| 356 | RAW_VALUE, |
| 357 | RAW_VALUE_REFERENCE, |
| 358 | STRING_VALUE, |
| 359 | STRING_VALUE_REFERENCE, |
| 360 | CHAR_VALUE, |
| 361 | BOOL_VALUE, |
| 362 | SIGNED_VALUE, |
| 363 | UNSIGNED_VALUE, |
| 364 | }; |
| 365 |
| 366 | class BASE_EXPORT TypedValue { |
| 367 | public: |
| 368 | TypedValue(); |
| 369 | TypedValue(const TypedValue& other); |
| 370 | ~TypedValue(); |
| 371 |
| 372 | ValueType type() const { return type_; } |
| 373 |
| 374 | // These methods return the extracted value in the correct format. |
| 375 | StringPiece Get() const; |
| 376 | StringPiece GetString() const; |
| 377 | bool GetBool() const; |
| 378 | char GetChar() const; |
| 379 | int64_t GetInt() const; |
| 380 | uint64_t GetUint() const; |
| 381 |
| 382 | // These methods return references to process memory as originally provided |
| 383 | // to corresponding Set calls. USE WITH CAUTION! There is no guarantee that |
| 384 | // the referenced memory is assessible or useful. It's possible that: |
| 385 | // - the memory was free'd and reallocated for a different purpose |
| 386 | // - the memory has been released back to the OS |
| 387 | // - the memory belongs to a different process's address space |
| 388 | // Dereferencing the returned StringPiece when the memory is not accessible |
| 389 | // will cause the program to SEGV! |
| 390 | StringPiece GetReference() const; |
| 391 | StringPiece GetStringReference() const; |
| 392 |
| 393 | private: |
| 394 | friend class ActivityUserData; |
| 395 |
| 396 | ValueType type_ = END_OF_VALUES; |
| 397 | uint64_t short_value_; // Used to hold copy of numbers, etc. |
| 398 | std::string long_value_; // Used to hold copy of raw/string data. |
| 399 | StringPiece ref_value_; // Used to hold reference to external data. |
| 400 | }; |
| 401 |
| 402 | using Snapshot = std::map<std::string, TypedValue>; |
| 403 |
| 404 | // Initialize the object either as a "sink" that just accepts and discards |
| 405 | // data or an active one that writes to a given (zeroed) memory block. |
| 406 | ActivityUserData(); |
| 407 | ActivityUserData(void* memory, size_t size, int64_t pid = 0); |
| 408 | virtual ~ActivityUserData(); |
| 409 |
| 410 | // Gets the unique ID number for this user data. If this changes then the |
| 411 | // contents have been overwritten by another thread. The return value is |
| 412 | // always non-zero unless it's actually just a data "sink". |
| 413 | uint32_t id() const { |
| 414 | return header_ ? header_->owner.data_id.load(std::memory_order_relaxed) : 0; |
| 415 | } |
| 416 |
| 417 | // Writes a |value| (as part of a key/value pair) that will be included with |
| 418 | // the activity in any reports. The same |name| can be written multiple times |
| 419 | // with each successive call overwriting the previously stored |value|. For |
| 420 | // raw and string values, the maximum size of successive writes is limited by |
| 421 | // the first call. The length of "name" is limited to 255 characters. |
| 422 | // |
| 423 | // This information is stored on a "best effort" basis. It may be dropped if |
| 424 | // the memory buffer is full or the associated activity is beyond the maximum |
| 425 | // recording depth. |
| 426 | // |
| 427 | // Some methods return pointers to the stored value that can be further |
| 428 | // modified using normal std::atomic operations without having to go through |
| 429 | // this interface, thus avoiding the relatively expensive name lookup. |
| 430 | // ==> Use std::memory_order_relaxed as the "order" parameter to atomic ops. |
| 431 | // Remember that the return value will be nullptr if the value could not |
| 432 | // be stored! |
| 433 | void Set(StringPiece name, const void* memory, size_t size) { |
| 434 | Set(name, RAW_VALUE, memory, size); |
| 435 | } |
| 436 | void SetString(StringPiece name, StringPiece value) { |
| 437 | Set(name, STRING_VALUE, value.data(), value.length()); |
| 438 | } |
| 439 | void SetString(StringPiece name, StringPiece16 value) { |
| 440 | SetString(name, UTF16ToUTF8(value)); |
| 441 | } |
| 442 | std::atomic<bool>* SetBool(StringPiece name, bool value) { |
| 443 | char cvalue = value ? 1 : 0; |
| 444 | void* addr = Set(name, BOOL_VALUE, &cvalue, sizeof(cvalue)); |
| 445 | return reinterpret_cast<std::atomic<bool>*>(addr); |
| 446 | } |
| 447 | std::atomic<char>* SetChar(StringPiece name, char value) { |
| 448 | void* addr = Set(name, CHAR_VALUE, &value, sizeof(value)); |
| 449 | return reinterpret_cast<std::atomic<char>*>(addr); |
| 450 | } |
| 451 | std::atomic<int64_t>* SetInt(StringPiece name, int64_t value) { |
| 452 | void* addr = Set(name, SIGNED_VALUE, &value, sizeof(value)); |
| 453 | return reinterpret_cast<std::atomic<int64_t>*>(addr); |
| 454 | } |
| 455 | std::atomic<uint64_t>* SetUint(StringPiece name, uint64_t value) { |
| 456 | void* addr = Set(name, UNSIGNED_VALUE, &value, sizeof(value)); |
| 457 | return reinterpret_cast<std::atomic<uint64_t>*>(addr); |
| 458 | } |
| 459 |
| 460 | // These function as above but don't actually copy the data into the |
| 461 | // persistent memory. They store unaltered pointers along with a size. These |
| 462 | // can be used in conjuction with a memory dump to find certain large pieces |
| 463 | // of information. |
| 464 | void SetReference(StringPiece name, const void* memory, size_t size) { |
| 465 | SetReference(name, RAW_VALUE_REFERENCE, memory, size); |
| 466 | } |
| 467 | void SetStringReference(StringPiece name, StringPiece value) { |
| 468 | SetReference(name, STRING_VALUE_REFERENCE, value.data(), value.length()); |
| 469 | } |
| 470 |
| 471 | // Creates a snapshot of the key/value pairs contained within. The returned |
| 472 | // data will be fixed, independent of whatever changes afterward. There is |
| 473 | // some protection against concurrent modification. This will return false |
| 474 | // if the data is invalid or if a complete overwrite of the contents is |
| 475 | // detected. |
| 476 | bool CreateSnapshot(Snapshot* output_snapshot) const; |
| 477 |
| 478 | // Gets the base memory address used for storing data. |
| 479 | const void* GetBaseAddress() const; |
| 480 |
| 481 | // Explicitly sets the process ID. |
| 482 | void SetOwningProcessIdForTesting(int64_t pid, int64_t stamp); |
| 483 |
| 484 | // Gets the associated process ID, in native form, and the creation timestamp |
| 485 | // from tracker memory without loading the entire structure for analysis. This |
| 486 | // will return false if no valid process ID is available. |
| 487 | static bool GetOwningProcessId(const void* memory, |
| 488 | int64_t* out_id, |
| 489 | int64_t* out_stamp); |
| 490 |
| 491 | protected: |
| 492 | virtual void* Set(StringPiece name, |
| 493 | ValueType type, |
| 494 | const void* memory, |
| 495 | size_t size); |
| 496 |
| 497 | private: |
| 498 | FRIEND_TEST_ALL_PREFIXES(ActivityTrackerTest, UserDataTest); |
| 499 |
| 500 | enum : size_t { kMemoryAlignment = sizeof(uint64_t) }; |
| 501 |
| 502 | // A structure that defines the structure header in memory. |
| 503 | struct MemoryHeader { |
| 504 | MemoryHeader(); |
| 505 | ~MemoryHeader(); |
| 506 |
| 507 | OwningProcess owner; // Information about the creating process. |
| 508 | }; |
| 509 |
| 510 | // Header to a key/value record held in persistent memory. |
| 511 | struct FieldHeader { |
| 512 | FieldHeader(); |
| 513 | ~FieldHeader(); |
| 514 |
| 515 | std::atomic<uint8_t> type; // Encoded ValueType |
| 516 | uint8_t name_size; // Length of "name" key. |
| 517 | std::atomic<uint16_t> value_size; // Actual size of of the stored value. |
| 518 | uint16_t record_size; // Total storage of name, value, header. |
| 519 | }; |
| 520 |
| 521 | // A structure used to reference data held outside of persistent memory. |
| 522 | struct ReferenceRecord { |
| 523 | uint64_t address; |
| 524 | uint64_t size; |
| 525 | }; |
| 526 |
| 527 | // This record is used to hold known value is a map so that they can be |
| 528 | // found and overwritten later. |
| 529 | struct ValueInfo { |
| 530 | ValueInfo(); |
| 531 | ValueInfo(ValueInfo&&); |
| 532 | ~ValueInfo(); |
| 533 |
| 534 | StringPiece name; // The "key" of the record. |
| 535 | ValueType type; // The type of the value. |
| 536 | void* memory; // Where the "value" is held. |
| 537 | std::atomic<uint16_t>* size_ptr; // Address of the actual size of value. |
| 538 | size_t extent; // The total storage of the value, |
| 539 | }; // typically rounded up for alignment. |
| 540 |
| 541 | void SetReference(StringPiece name, |
| 542 | ValueType type, |
| 543 | const void* memory, |
| 544 | size_t size); |
| 545 |
| 546 | // Loads any data already in the memory segment. This allows for accessing |
| 547 | // records created previously. If this detects that the underlying data has |
| 548 | // gone away (cleared by another thread/process), it will invalidate all the |
| 549 | // data in this object and turn it into simple "sink" with no values to |
| 550 | // return. |
| 551 | void ImportExistingData() const; |
| 552 |
| 553 | // A map of all the values within the memory block, keyed by name for quick |
| 554 | // updates of the values. This is "mutable" because it changes on "const" |
| 555 | // objects even when the actual data values can't change. |
| 556 | mutable std::map<StringPiece, ValueInfo> values_; |
| 557 |
| 558 | // Information about the memory block in which new data can be stored. These |
| 559 | // are "mutable" because they change even on "const" objects that are just |
| 560 | // skipping already set values. |
| 561 | mutable char* memory_; |
| 562 | mutable size_t available_; |
| 563 |
| 564 | // A pointer to the memory header for this instance. |
| 565 | MemoryHeader* const header_; |
| 566 |
| 567 | // These hold values used when initially creating the object. They are |
| 568 | // compared against current header values to check for outside changes. |
| 569 | const uint32_t orig_data_id; |
| 570 | const int64_t orig_process_id; |
| 571 | const int64_t orig_create_stamp; |
| 572 |
| 573 | DISALLOW_COPY_AND_ASSIGN(ActivityUserData); |
| 574 | }; |
| 575 |
| 576 | // This class manages tracking a stack of activities for a single thread in |
| 577 | // a persistent manner, implementing a bounded-size stack in a fixed-size |
| 578 | // memory allocation. In order to support an operational mode where another |
| 579 | // thread is analyzing this data in real-time, atomic operations are used |
| 580 | // where necessary to guarantee a consistent view from the outside. |
| 581 | // |
| 582 | // This class is not generally used directly but instead managed by the |
| 583 | // GlobalActivityTracker instance and updated using Scoped*Activity local |
| 584 | // objects. |
| 585 | class BASE_EXPORT ThreadActivityTracker { |
| 586 | public: |
| 587 | using ActivityId = uint32_t; |
| 588 |
| 589 | // This structure contains all the common information about the thread so |
| 590 | // it doesn't have to be repeated in every entry on the stack. It is defined |
| 591 | // and used completely within the .cc file. |
| 592 | struct Header; |
| 593 |
| 594 | // This structure holds a copy of all the internal data at the moment the |
| 595 | // "snapshot" operation is done. It is disconnected from the live tracker |
| 596 | // so that continued operation of the thread will not cause changes here. |
| 597 | struct BASE_EXPORT Snapshot { |
| 598 | // Explicit constructor/destructor are needed because of complex types |
| 599 | // with non-trivial default constructors and destructors. |
| 600 | Snapshot(); |
| 601 | ~Snapshot(); |
| 602 |
| 603 | // The name of the thread as set when it was created. The name may be |
| 604 | // truncated due to internal length limitations. |
| 605 | std::string thread_name; |
| 606 |
| 607 | // The timestamp at which this process was created. |
| 608 | int64_t create_stamp; |
| 609 |
| 610 | // The process and thread IDs. These values have no meaning other than |
| 611 | // they uniquely identify a running process and a running thread within |
| 612 | // that process. Thread-IDs can be re-used across different processes |
| 613 | // and both can be re-used after the process/thread exits. |
| 614 | int64_t process_id = 0; |
| 615 | int64_t thread_id = 0; |
| 616 |
| 617 | // The current stack of activities that are underway for this thread. It |
| 618 | // is limited in its maximum size with later entries being left off. |
| 619 | std::vector<Activity> activity_stack; |
| 620 |
| 621 | // The current total depth of the activity stack, including those later |
| 622 | // entries not recorded in the |activity_stack| vector. |
| 623 | uint32_t activity_stack_depth = 0; |
| 624 |
| 625 | // The last recorded "exception" activity. |
| 626 | Activity last_exception; |
| 627 | }; |
| 628 |
| 629 | // This is the base class for having the compiler manage an activity on the |
| 630 | // tracker's stack. It does nothing but call methods on the passed |tracker| |
| 631 | // if it is not null, making it safe (and cheap) to create these objects |
| 632 | // even if activity tracking is not enabled. |
| 633 | class BASE_EXPORT ScopedActivity { |
| 634 | public: |
| 635 | ScopedActivity(ThreadActivityTracker* tracker, |
| 636 | const void* program_counter, |
| 637 | const void* origin, |
| 638 | Activity::Type type, |
| 639 | const ActivityData& data); |
| 640 | ~ScopedActivity(); |
| 641 |
| 642 | // Indicates if this activity is actually being recorded. It may not be if |
| 643 | // (a) activity tracking is not enabled globally or |
| 644 | // (b) there was insufficient stack space to hold it. |
| 645 | bool IsRecorded(); |
| 646 |
| 647 | // Changes some basic metadata about the activity. |
| 648 | void ChangeTypeAndData(Activity::Type type, const ActivityData& data); |
| 649 |
| 650 | protected: |
| 651 | // The thread tracker to which this object reports. It can be null if |
| 652 | // activity tracking is not (yet) enabled. |
| 653 | ThreadActivityTracker* const tracker_; |
| 654 |
| 655 | // An identifier that indicates a specific activity on the stack. |
| 656 | ActivityId activity_id_; |
| 657 |
| 658 | private: |
| 659 | DISALLOW_COPY_AND_ASSIGN(ScopedActivity); |
| 660 | }; |
| 661 |
| 662 | // A ThreadActivityTracker runs on top of memory that is managed externally. |
| 663 | // It must be large enough for the internal header and a few Activity |
| 664 | // blocks. See SizeForStackDepth(). |
| 665 | ThreadActivityTracker(void* base, size_t size); |
| 666 | virtual ~ThreadActivityTracker(); |
| 667 |
| 668 | // Indicates that an activity has started from a given |origin| address in |
| 669 | // the code, though it can be null if the creator's address is not known. |
| 670 | // The |type| and |data| describe the activity. |program_counter| should be |
| 671 | // the result of GetProgramCounter() where push is called. Returned is an |
| 672 | // ID that can be used to adjust the pushed activity. |
| 673 | ActivityId PushActivity(const void* program_counter, |
| 674 | const void* origin, |
| 675 | Activity::Type type, |
| 676 | const ActivityData& data); |
| 677 |
| 678 | // An inlined version of the above that gets the program counter where it |
| 679 | // is called. |
| 680 | ALWAYS_INLINE |
| 681 | ActivityId PushActivity(const void* origin, |
| 682 | Activity::Type type, |
| 683 | const ActivityData& data) { |
| 684 | return PushActivity(GetProgramCounter(), origin, type, data); |
| 685 | } |
| 686 |
| 687 | // Changes the activity |type| and |data| of the top-most entry on the stack. |
| 688 | // This is useful if the information has changed and it is desireable to |
| 689 | // track that change without creating a new stack entry. If the type is |
| 690 | // ACT_NULL or the data is kNullActivityData then that value will remain |
| 691 | // unchanged. The type, if changed, must remain in the same category. |
| 692 | // Changing both is not atomic so a snapshot operation could occur between |
| 693 | // the update of |type| and |data| or between update of |data| fields. |
| 694 | void ChangeActivity(ActivityId id, |
| 695 | Activity::Type type, |
| 696 | const ActivityData& data); |
| 697 |
| 698 | // Indicates that an activity has completed. |
| 699 | void PopActivity(ActivityId id); |
| 700 |
| 701 | // Indicates if an activity is actually being recorded. |
| 702 | bool IsRecorded(ActivityId id); |
| 703 |
| 704 | // Sets the user-data information for an activity. |
| 705 | std::unique_ptr<ActivityUserData> GetUserData( |
| 706 | ActivityId id, |
| 707 | ActivityTrackerMemoryAllocator* allocator); |
| 708 |
| 709 | // Returns if there is true use-data associated with a given ActivityId since |
| 710 | // it's possible than any returned object is just a sink. |
| 711 | bool HasUserData(ActivityId id); |
| 712 |
| 713 | // Release the user-data information for an activity. |
| 714 | void ReleaseUserData(ActivityId id, |
| 715 | ActivityTrackerMemoryAllocator* allocator); |
| 716 |
| 717 | // Save an exception. |origin| is the location of the exception. |
| 718 | void RecordExceptionActivity(const void* program_counter, |
| 719 | const void* origin, |
| 720 | Activity::Type type, |
| 721 | const ActivityData& data); |
| 722 |
| 723 | // Returns whether the current data is valid or not. It is not valid if |
| 724 | // corruption has been detected in the header or other data structures. |
| 725 | bool IsValid() const; |
| 726 |
| 727 | // Gets a copy of the tracker contents for analysis. Returns false if a |
| 728 | // snapshot was not possible, perhaps because the data is not valid; the |
| 729 | // contents of |output_snapshot| are undefined in that case. The current |
| 730 | // implementation does not support concurrent snapshot operations. |
| 731 | bool CreateSnapshot(Snapshot* output_snapshot) const; |
| 732 |
| 733 | // Gets the base memory address used for storing data. |
| 734 | const void* GetBaseAddress(); |
| 735 |
| 736 | // Access the "data version" value so tests can determine if an activity |
| 737 | // was pushed and popped in a single call. |
| 738 | uint32_t GetDataVersionForTesting(); |
| 739 |
| 740 | // Explicitly sets the process ID. |
| 741 | void SetOwningProcessIdForTesting(int64_t pid, int64_t stamp); |
| 742 |
| 743 | // Gets the associated process ID, in native form, and the creation timestamp |
| 744 | // from tracker memory without loading the entire structure for analysis. This |
| 745 | // will return false if no valid process ID is available. |
| 746 | static bool GetOwningProcessId(const void* memory, |
| 747 | int64_t* out_id, |
| 748 | int64_t* out_stamp); |
| 749 |
| 750 | // Calculates the memory size required for a given stack depth, including |
| 751 | // the internal header structure for the stack. |
| 752 | static size_t SizeForStackDepth(int stack_depth); |
| 753 |
| 754 | private: |
| 755 | friend class ActivityTrackerTest; |
| 756 |
| 757 | bool CalledOnValidThread(); |
| 758 |
| 759 | std::unique_ptr<ActivityUserData> CreateUserDataForActivity( |
| 760 | Activity* activity, |
| 761 | ActivityTrackerMemoryAllocator* allocator); |
| 762 |
| 763 | Header* const header_; // Pointer to the Header structure. |
| 764 | Activity* const stack_; // The stack of activities. |
| 765 |
| 766 | #if DCHECK_IS_ON() |
| 767 | // The ActivityTracker is thread bound, and will be invoked across all the |
| 768 | // sequences that run on the thread. A ThreadChecker does not work here, as it |
| 769 | // asserts on running in the same sequence each time. |
| 770 | const PlatformThreadRef thread_id_; // The thread this instance is bound to. |
| 771 | #endif |
| 772 | const uint32_t stack_slots_; // The total number of stack slots. |
| 773 |
| 774 | bool valid_ = false; // Tracks whether the data is valid or not. |
| 775 |
| 776 | DISALLOW_COPY_AND_ASSIGN(ThreadActivityTracker); |
| 777 | }; |
| 778 |
| 779 |
| 780 | // The global tracker manages all the individual thread trackers. Memory for |
| 781 | // the thread trackers is taken from a PersistentMemoryAllocator which allows |
| 782 | // for the data to be analyzed by a parallel process or even post-mortem. |
| 783 | class BASE_EXPORT GlobalActivityTracker { |
| 784 | public: |
| 785 | // Type identifiers used when storing in persistent memory so they can be |
| 786 | // identified during extraction; the first 4 bytes of the SHA1 of the name |
| 787 | // is used as a unique integer. A "version number" is added to the base |
| 788 | // so that, if the structure of that object changes, stored older versions |
| 789 | // will be safely ignored. These are public so that an external process |
| 790 | // can recognize records of this type within an allocator. |
| 791 | enum : uint32_t { |
| 792 | kTypeIdActivityTracker = 0x5D7381AF + 4, // SHA1(ActivityTracker) v4 |
| 793 | kTypeIdUserDataRecord = 0x615EDDD7 + 3, // SHA1(UserDataRecord) v3 |
| 794 | kTypeIdGlobalLogMessage = 0x4CF434F9 + 1, // SHA1(GlobalLogMessage) v1 |
| 795 | kTypeIdProcessDataRecord = kTypeIdUserDataRecord + 0x100, |
| 796 |
| 797 | kTypeIdActivityTrackerFree = ~kTypeIdActivityTracker, |
| 798 | kTypeIdUserDataRecordFree = ~kTypeIdUserDataRecord, |
| 799 | kTypeIdProcessDataRecordFree = ~kTypeIdProcessDataRecord, |
| 800 | }; |
| 801 |
| 802 | // An enumeration of common process life stages. All entries are given an |
| 803 | // explicit number so they are known and remain constant; this allows for |
| 804 | // cross-version analysis either locally or on a server. |
| 805 | enum ProcessPhase : int { |
| 806 | // The phases are generic and may have meaning to the tracker. |
| 807 | PROCESS_PHASE_UNKNOWN = 0, |
| 808 | PROCESS_LAUNCHED = 1, |
| 809 | PROCESS_LAUNCH_FAILED = 2, |
| 810 | PROCESS_EXITED_CLEANLY = 10, |
| 811 | PROCESS_EXITED_WITH_CODE = 11, |
| 812 |
| 813 | // Add here whatever is useful for analysis. |
| 814 | PROCESS_SHUTDOWN_STARTED = 100, |
| 815 | PROCESS_MAIN_LOOP_STARTED = 101, |
| 816 | }; |
| 817 |
| 818 | // A callback made when a process exits to allow immediate analysis of its |
| 819 | // data. Note that the system may reuse the |process_id| so when fetching |
| 820 | // records it's important to ensure that what is returned was created before |
| 821 | // the |exit_stamp|. Movement of |process_data| information is allowed. |
| 822 | using ProcessExitCallback = |
| 823 | RepeatingCallback<void(int64_t process_id, |
| 824 | int64_t exit_stamp, |
| 825 | int exit_code, |
| 826 | ProcessPhase exit_phase, |
| 827 | std::string&& command_line, |
| 828 | ActivityUserData::Snapshot&& process_data)>; |
| 829 |
| 830 | // This structure contains information about a loaded module, as shown to |
| 831 | // users of the tracker. |
| 832 | struct BASE_EXPORT ModuleInfo { |
| 833 | ModuleInfo(); |
| 834 | ModuleInfo(ModuleInfo&& rhs); |
| 835 | ModuleInfo(const ModuleInfo& rhs); |
| 836 | ~ModuleInfo(); |
| 837 |
| 838 | ModuleInfo& operator=(ModuleInfo&& rhs); |
| 839 | ModuleInfo& operator=(const ModuleInfo& rhs); |
| 840 |
| 841 | // Information about where and when the module was loaded/unloaded. |
| 842 | bool is_loaded = false; // Was the last operation a load or unload? |
| 843 | uintptr_t address = 0; // Address of the last load operation. |
| 844 | int64_t load_time = 0; // Time of last change; set automatically. |
| 845 |
| 846 | // Information about the module itself. These never change no matter how |
| 847 | // many times a module may be loaded and unloaded. |
| 848 | size_t size = 0; // The size of the loaded module. |
| 849 | uint32_t timestamp = 0; // Opaque "timestamp" for the module. |
| 850 | uint32_t age = 0; // Opaque "age" for the module. |
| 851 | uint8_t identifier[16]; // Opaque identifier (GUID, etc.) for the module. |
| 852 | std::string file; // The full path to the file. (UTF-8) |
| 853 | std::string debug_file; // The full path to the debug file. |
| 854 | }; |
| 855 |
| 856 | // This is a thin wrapper around the thread-tracker's ScopedActivity that |
| 857 | // allows thread-safe access to data values. It is safe to use even if |
| 858 | // activity tracking is not enabled. |
| 859 | class BASE_EXPORT ScopedThreadActivity |
| 860 | : public ThreadActivityTracker::ScopedActivity { |
| 861 | public: |
| 862 | ScopedThreadActivity(const void* program_counter, |
| 863 | const void* origin, |
| 864 | Activity::Type type, |
| 865 | const ActivityData& data, |
| 866 | bool lock_allowed); |
| 867 | ~ScopedThreadActivity(); |
| 868 |
| 869 | // Returns an object for manipulating user data. |
| 870 | ActivityUserData& user_data(); |
| 871 |
| 872 | private: |
| 873 | // Gets (or creates) a tracker for the current thread. If locking is not |
| 874 | // allowed (because a lock is being tracked which would cause recursion) |
| 875 | // then the attempt to create one if none found will be skipped. Once |
| 876 | // the tracker for this thread has been created for other reasons, locks |
| 877 | // will be tracked. The thread-tracker uses locks. |
| 878 | static ThreadActivityTracker* GetOrCreateTracker(bool lock_allowed) { |
| 879 | GlobalActivityTracker* global_tracker = Get(); |
| 880 | if (!global_tracker) |
| 881 | return nullptr; |
| 882 |
| 883 | if (lock_allowed) |
| 884 | return global_tracker->GetOrCreateTrackerForCurrentThread(); |
| 885 | else |
| 886 | return global_tracker->GetTrackerForCurrentThread(); |
| 887 | } |
| 888 |
| 889 | // An object that manages additional user data, created only upon request. |
| 890 | std::unique_ptr<ActivityUserData> user_data_; |
| 891 |
| 892 | DISALLOW_COPY_AND_ASSIGN(ScopedThreadActivity); |
| 893 | }; |
| 894 |
| 895 | ~GlobalActivityTracker(); |
| 896 |
| 897 | // Creates a global tracker using a given persistent-memory |allocator| and |
| 898 | // providing the given |stack_depth| to each thread tracker it manages. The |
| 899 | // created object is activated so tracking will begin immediately upon return. |
| 900 | // The |process_id| can be zero to get it from the OS but is taken for testing |
| 901 | // purposes. |
| 902 | static void CreateWithAllocator( |
| 903 | std::unique_ptr<PersistentMemoryAllocator> allocator, |
| 904 | int stack_depth, |
| 905 | int64_t process_id); |
| 906 |
| 907 | #if !defined(OS_NACL) |
| 908 | // Like above but internally creates an allocator around a disk file with |
| 909 | // the specified |size| at the given |file_path|. Any existing file will be |
| 910 | // overwritten. The |id| and |name| are arbitrary and stored in the allocator |
| 911 | // for reference by whatever process reads it. Returns true if successful. |
| 912 | static bool CreateWithFile(const FilePath& file_path, |
| 913 | size_t size, |
| 914 | uint64_t id, |
| 915 | StringPiece name, |
| 916 | int stack_depth); |
| 917 | #endif // !defined(OS_NACL) |
| 918 |
| 919 | // Like above but internally creates an allocator using local heap memory of |
| 920 | // the specified size. This is used primarily for unit tests. The |process_id| |
| 921 | // can be zero to get it from the OS but is taken for testing purposes. |
| 922 | static bool CreateWithLocalMemory(size_t size, |
| 923 | uint64_t id, |
| 924 | StringPiece name, |
| 925 | int stack_depth, |
| 926 | int64_t process_id); |
| 927 |
| 928 | // Like above but internally creates an allocator using a shared-memory |
| 929 | // segment that is already mapped into the local memory space. |
| 930 | static bool CreateWithSharedMemory(base::WritableSharedMemoryMapping mapping, |
| 931 | uint64_t id, |
| 932 | StringPiece name, |
| 933 | int stack_depth); |
| 934 |
| 935 | // Gets the global activity-tracker or null if none exists. |
| 936 | static GlobalActivityTracker* Get() { |
| 937 | return reinterpret_cast<GlobalActivityTracker*>( |
| 938 | subtle::Acquire_Load(&g_tracker_)); |
| 939 | } |
| 940 |
| 941 | // Sets the global activity-tracker for testing purposes. |
| 942 | static void SetForTesting(std::unique_ptr<GlobalActivityTracker> tracker); |
| 943 |
| 944 | // This access to the persistent allocator is only for testing; it extracts |
| 945 | // the global tracker completely. All tracked threads must exit before |
| 946 | // calling this. Tracking for the current thread will be automatically |
| 947 | // stopped. |
| 948 | static std::unique_ptr<GlobalActivityTracker> ReleaseForTesting(); |
| 949 |
| 950 | // Convenience method for determining if a global tracker is active. |
| 951 | static bool IsEnabled() { return Get() != nullptr; } |
| 952 |
| 953 | // Gets the persistent-memory-allocator in which data is stored. Callers |
| 954 | // can store additional records here to pass more information to the |
| 955 | // analysis process. |
| 956 | PersistentMemoryAllocator* allocator() { return allocator_.get(); } |
| 957 |
| 958 | // Gets the thread's activity-tracker if it exists. This is inline for |
| 959 | // performance reasons and it uses thread-local-storage (TLS) so that there |
| 960 | // is no significant lookup time required to find the one for the calling |
| 961 | // thread. Ownership remains with the global tracker. |
| 962 | ThreadActivityTracker* GetTrackerForCurrentThread() { |
| 963 | // It is not safe to use TLS once TLS has been destroyed. |
| 964 | if (base::ThreadLocalStorage::HasBeenDestroyed()) |
| 965 | return nullptr; |
| 966 |
| 967 | return this_thread_tracker_.Get(); |
| 968 | } |
| 969 |
| 970 | // Gets the thread's activity-tracker or creates one if none exists. This |
| 971 | // is inline for performance reasons. Ownership remains with the global |
| 972 | // tracker. |
| 973 | ThreadActivityTracker* GetOrCreateTrackerForCurrentThread() { |
| 974 | ThreadActivityTracker* tracker = GetTrackerForCurrentThread(); |
| 975 | if (tracker) |
| 976 | return tracker; |
| 977 | return CreateTrackerForCurrentThread(); |
| 978 | } |
| 979 |
| 980 | // Creates an activity-tracker for the current thread. |
| 981 | ThreadActivityTracker* CreateTrackerForCurrentThread(); |
| 982 |
| 983 | // Releases the activity-tracker for the current thread (for testing only). |
| 984 | void ReleaseTrackerForCurrentThreadForTesting(); |
| 985 |
| 986 | // Sets a task-runner that can be used for background work. |
| 987 | void SetBackgroundTaskRunner( |
| 988 | const scoped_refptr<SequencedTaskRunner>& runner); |
| 989 |
| 990 | // Sets an optional callback to be called when a process exits. |
| 991 | void SetProcessExitCallback(ProcessExitCallback callback); |
| 992 |
| 993 | // Manages process lifetimes. These are called by the process that launched |
| 994 | // and reaped the subprocess, not the subprocess itself. If it is expensive |
| 995 | // to generate the parameters, Get() the global tracker and call these |
| 996 | // conditionally rather than using the static versions. |
| 997 | void RecordProcessLaunch(ProcessId process_id, |
| 998 | const FilePath::StringType& cmd); |
| 999 | void RecordProcessLaunch(ProcessId process_id, |
| 1000 | const FilePath::StringType& exe, |
| 1001 | const FilePath::StringType& args); |
| 1002 | void RecordProcessExit(ProcessId process_id, int exit_code); |
| 1003 | static void RecordProcessLaunchIfEnabled(ProcessId process_id, |
| 1004 | const FilePath::StringType& cmd) { |
| 1005 | GlobalActivityTracker* tracker = Get(); |
| 1006 | if (tracker) |
| 1007 | tracker->RecordProcessLaunch(process_id, cmd); |
| 1008 | } |
| 1009 | static void RecordProcessLaunchIfEnabled(ProcessId process_id, |
| 1010 | const FilePath::StringType& exe, |
| 1011 | const FilePath::StringType& args) { |
| 1012 | GlobalActivityTracker* tracker = Get(); |
| 1013 | if (tracker) |
| 1014 | tracker->RecordProcessLaunch(process_id, exe, args); |
| 1015 | } |
| 1016 | static void RecordProcessExitIfEnabled(ProcessId process_id, int exit_code) { |
| 1017 | GlobalActivityTracker* tracker = Get(); |
| 1018 | if (tracker) |
| 1019 | tracker->RecordProcessExit(process_id, exit_code); |
| 1020 | } |
| 1021 |
| 1022 | // Sets the "phase" of the current process, useful for knowing what it was |
| 1023 | // doing when it last reported. |
| 1024 | void SetProcessPhase(ProcessPhase phase); |
| 1025 | static void SetProcessPhaseIfEnabled(ProcessPhase phase) { |
| 1026 | GlobalActivityTracker* tracker = Get(); |
| 1027 | if (tracker) |
| 1028 | tracker->SetProcessPhase(phase); |
| 1029 | } |
| 1030 |
| 1031 | // Records a log message. The current implementation does NOT recycle these |
| 1032 | // only store critical messages such as FATAL ones. |
| 1033 | void RecordLogMessage(StringPiece message); |
| 1034 | static void RecordLogMessageIfEnabled(StringPiece message) { |
| 1035 | GlobalActivityTracker* tracker = Get(); |
| 1036 | if (tracker) |
| 1037 | tracker->RecordLogMessage(message); |
| 1038 | } |
| 1039 |
| 1040 | // Records a module load/unload event. This is safe to call multiple times |
| 1041 | // even with the same information. |
| 1042 | void RecordModuleInfo(const ModuleInfo& info); |
| 1043 | static void RecordModuleInfoIfEnabled(const ModuleInfo& info) { |
| 1044 | GlobalActivityTracker* tracker = Get(); |
| 1045 | if (tracker) |
| 1046 | tracker->RecordModuleInfo(info); |
| 1047 | } |
| 1048 |
| 1049 | // Record exception information for the current thread. |
| 1050 | ALWAYS_INLINE |
| 1051 | void RecordException(const void* origin, uint32_t code) { |
| 1052 | return RecordExceptionImpl(GetProgramCounter(), origin, code); |
| 1053 | } |
| 1054 | void RecordException(const void* pc, const void* origin, uint32_t code); |
| 1055 |
| 1056 | // Marks the tracked data as deleted. |
| 1057 | void MarkDeleted(); |
| 1058 |
| 1059 | // Gets the process ID used for tracking. This is typically the same as what |
| 1060 | // the OS thinks is the current process but can be overridden for testing. |
| 1061 | int64_t process_id() { return process_id_; } |
| 1062 |
| 1063 | // Accesses the process data record for storing arbitrary key/value pairs. |
| 1064 | // Updates to this are thread-safe. |
| 1065 | ActivityUserData& process_data() { return process_data_; } |
| 1066 |
| 1067 | private: |
| 1068 | friend class GlobalActivityAnalyzer; |
| 1069 | friend class ScopedThreadActivity; |
| 1070 | friend class ActivityTrackerTest; |
| 1071 |
| 1072 | enum : int { |
| 1073 | // The maximum number of threads that can be tracked within a process. If |
| 1074 | // more than this number run concurrently, tracking of new ones may cease. |
| 1075 | kMaxThreadCount = 100, |
| 1076 | kCachedThreadMemories = 10, |
| 1077 | kCachedUserDataMemories = 10, |
| 1078 | }; |
| 1079 |
| 1080 | // A wrapper around ActivityUserData that is thread-safe and thus can be used |
| 1081 | // in the global scope without the requirement of being called from only one |
| 1082 | // thread. |
| 1083 | class ThreadSafeUserData : public ActivityUserData { |
| 1084 | public: |
| 1085 | ThreadSafeUserData(void* memory, size_t size, int64_t pid = 0); |
| 1086 | ~ThreadSafeUserData() override; |
| 1087 |
| 1088 | private: |
| 1089 | void* Set(StringPiece name, |
| 1090 | ValueType type, |
| 1091 | const void* memory, |
| 1092 | size_t size) override; |
| 1093 |
| 1094 | Lock data_lock_; |
| 1095 |
| 1096 | DISALLOW_COPY_AND_ASSIGN(ThreadSafeUserData); |
| 1097 | }; |
| 1098 |
| 1099 | // State of a module as stored in persistent memory. This supports a single |
| 1100 | // loading of a module only. If modules are loaded multiple times at |
| 1101 | // different addresses, only the last will be recorded and an unload will |
| 1102 | // not revert to the information of any other addresses. |
| 1103 | struct BASE_EXPORT ModuleInfoRecord { |
| 1104 | // SHA1(ModuleInfoRecord): Increment this if structure changes! |
| 1105 | static constexpr uint32_t kPersistentTypeId = 0x05DB5F41 + 1; |
| 1106 |
| 1107 | // Expected size for 32/64-bit check by PersistentMemoryAllocator. |
| 1108 | static constexpr size_t kExpectedInstanceSize = |
| 1109 | OwningProcess::kExpectedInstanceSize + 56; |
| 1110 |
| 1111 | // The atomic unfortunately makes this a "complex" class on some compilers |
| 1112 | // and thus requires an out-of-line constructor & destructor even though |
| 1113 | // they do nothing. |
| 1114 | ModuleInfoRecord(); |
| 1115 | ~ModuleInfoRecord(); |
| 1116 |
| 1117 | OwningProcess owner; // The process that created this record. |
| 1118 | uint64_t address; // The base address of the module. |
| 1119 | uint64_t load_time; // Time of last load/unload. |
| 1120 | uint64_t size; // The size of the module in bytes. |
| 1121 | uint32_t timestamp; // Opaque timestamp of the module. |
| 1122 | uint32_t age; // Opaque "age" associated with the module. |
| 1123 | uint8_t identifier[16]; // Opaque identifier for the module. |
| 1124 | std::atomic<uint32_t> changes; // Number load/unload actions. |
| 1125 | uint16_t pickle_size; // The size of the following pickle. |
| 1126 | uint8_t loaded; // Flag if module is loaded or not. |
| 1127 | char pickle[1]; // Other strings; may allocate larger. |
| 1128 |
| 1129 | // Decodes/encodes storage structure from more generic info structure. |
| 1130 | bool DecodeTo(GlobalActivityTracker::ModuleInfo* info, |
| 1131 | size_t record_size) const; |
| 1132 | static ModuleInfoRecord* CreateFrom( |
| 1133 | const GlobalActivityTracker::ModuleInfo& info, |
| 1134 | PersistentMemoryAllocator* allocator); |
| 1135 |
| 1136 | // Updates the core information without changing the encoded strings. This |
| 1137 | // is useful when a known module changes state (i.e. new load or unload). |
| 1138 | bool UpdateFrom(const GlobalActivityTracker::ModuleInfo& info); |
| 1139 |
| 1140 | private: |
| 1141 | DISALLOW_COPY_AND_ASSIGN(ModuleInfoRecord); |
| 1142 | }; |
| 1143 |
| 1144 | // A thin wrapper around the main thread-tracker that keeps additional |
| 1145 | // information that the global tracker needs to handle joined threads. |
| 1146 | class ManagedActivityTracker : public ThreadActivityTracker { |
| 1147 | public: |
| 1148 | ManagedActivityTracker(PersistentMemoryAllocator::Reference mem_reference, |
| 1149 | void* base, |
| 1150 | size_t size); |
| 1151 | ~ManagedActivityTracker() override; |
| 1152 |
| 1153 | // The reference into persistent memory from which the thread-tracker's |
| 1154 | // memory was created. |
| 1155 | const PersistentMemoryAllocator::Reference mem_reference_; |
| 1156 |
| 1157 | // The physical address used for the thread-tracker's memory. |
| 1158 | void* const mem_base_; |
| 1159 |
| 1160 | private: |
| 1161 | DISALLOW_COPY_AND_ASSIGN(ManagedActivityTracker); |
| 1162 | }; |
| 1163 |
| 1164 | // Creates a global tracker using a given persistent-memory |allocator| and |
| 1165 | // providing the given |stack_depth| to each thread tracker it manages. The |
| 1166 | // created object is activated so tracking has already started upon return. |
| 1167 | // The |process_id| can be zero to get it from the OS but is taken for testing |
| 1168 | // purposes. |
| 1169 | GlobalActivityTracker(std::unique_ptr<PersistentMemoryAllocator> allocator, |
| 1170 | int stack_depth, |
| 1171 | int64_t process_id); |
| 1172 |
| 1173 | // Returns the memory used by an activity-tracker managed by this class. |
| 1174 | // It is called during the destruction of a ManagedActivityTracker object. |
| 1175 | void ReturnTrackerMemory(ManagedActivityTracker* tracker); |
| 1176 |
| 1177 | // Records exception information. |
| 1178 | void RecordExceptionImpl(const void* pc, const void* origin, uint32_t code); |
| 1179 |
| 1180 | // Releases the activity-tracker associcated with thread. It is called |
| 1181 | // automatically when a thread is joined and thus there is nothing more to |
| 1182 | // be tracked. |value| is a pointer to a ManagedActivityTracker. |
| 1183 | static void OnTLSDestroy(void* value); |
| 1184 |
| 1185 | // Does process-exit work. This can be run on any thread. |
| 1186 | void CleanupAfterProcess(int64_t process_id, |
| 1187 | int64_t exit_stamp, |
| 1188 | int exit_code, |
| 1189 | std::string&& command_line); |
| 1190 |
| 1191 | // The persistent-memory allocator from which the memory for all trackers |
| 1192 | // is taken. |
| 1193 | std::unique_ptr<PersistentMemoryAllocator> allocator_; |
| 1194 |
| 1195 | // The size (in bytes) of memory required by a ThreadActivityTracker to |
| 1196 | // provide the stack-depth requested during construction. |
| 1197 | const size_t stack_memory_size_; |
| 1198 |
| 1199 | // The process-id of the current process. This is kept as a member variable, |
| 1200 | // defined during initialization, for testing purposes. |
| 1201 | const int64_t process_id_; |
| 1202 |
| 1203 | // The activity tracker for the currently executing thread. |
| 1204 | ThreadLocalOwnedPointer<ThreadActivityTracker> this_thread_tracker_; |
| 1205 |
| 1206 | // The number of thread trackers currently active. |
| 1207 | std::atomic<int> thread_tracker_count_; |
| 1208 |
| 1209 | // A caching memory allocator for thread-tracker objects. |
| 1210 | ActivityTrackerMemoryAllocator thread_tracker_allocator_; |
| 1211 | Lock thread_tracker_allocator_lock_; |
| 1212 |
| 1213 | // A caching memory allocator for user data attached to activity data. |
| 1214 | ActivityTrackerMemoryAllocator user_data_allocator_; |
| 1215 | Lock user_data_allocator_lock_; |
| 1216 |
| 1217 | // An object for holding arbitrary key value pairs with thread-safe access. |
| 1218 | ThreadSafeUserData process_data_; |
| 1219 |
| 1220 | // A map of global module information, keyed by module path. |
| 1221 | std::map<const std::string, ModuleInfoRecord*> modules_; |
| 1222 | Lock modules_lock_; |
| 1223 |
| 1224 | // The active global activity tracker. |
| 1225 | static subtle::AtomicWord g_tracker_; |
| 1226 |
| 1227 | // A lock that is used to protect access to the following fields. |
| 1228 | Lock global_tracker_lock_; |
| 1229 |
| 1230 | // The collection of processes being tracked and their command-lines. |
| 1231 | std::map<int64_t, std::string> known_processes_; |
| 1232 |
| 1233 | // A task-runner that can be used for doing background processing. |
| 1234 | scoped_refptr<SequencedTaskRunner> background_task_runner_; |
| 1235 |
| 1236 | // A callback performed when a subprocess exits, including its exit-code |
| 1237 | // and the phase it was in when that occurred. This will be called via |
| 1238 | // the |background_task_runner_| if one is set or whatever thread reaped |
| 1239 | // the process otherwise. |
| 1240 | ProcessExitCallback process_exit_callback_; |
| 1241 |
| 1242 | DISALLOW_COPY_AND_ASSIGN(GlobalActivityTracker); |
| 1243 | }; |
| 1244 |
| 1245 |
| 1246 | // Record entry in to and out of an arbitrary block of code. |
| 1247 | class BASE_EXPORT ScopedActivity |
| 1248 | : public GlobalActivityTracker::ScopedThreadActivity { |
| 1249 | public: |
| 1250 | // Track activity at the specified FROM_HERE location for an arbitrary |
| 1251 | // 4-bit |action|, an arbitrary 32-bit |id|, and 32-bits of arbitrary |
| 1252 | // |info|. None of these values affect operation; they're all purely |
| 1253 | // for association and analysis. To have unique identifiers across a |
| 1254 | // diverse code-base, create the number by taking the first 8 characters |
| 1255 | // of the hash of the activity being tracked. |
| 1256 | // |
| 1257 | // For example: |
| 1258 | // Tracking method: void MayNeverExit(uint32_t foo) {...} |
| 1259 | // echo -n "MayNeverExit" | sha1sum => e44873ccab21e2b71270da24aa1... |
| 1260 | // |
| 1261 | // void MayNeverExit(int32_t foo) { |
| 1262 | // base::debug::ScopedActivity track_me(0, 0xE44873CC, foo); |
| 1263 | // ... |
| 1264 | // } |
| 1265 | ALWAYS_INLINE |
| 1266 | ScopedActivity(uint8_t action, uint32_t id, int32_t info) |
| 1267 | : ScopedActivity(GetProgramCounter(), action, id, info) {} |
| 1268 | ScopedActivity(Location from_here, uint8_t action, uint32_t id, int32_t info) |
| 1269 | : ScopedActivity(from_here.program_counter(), action, id, info) {} |
| 1270 | ScopedActivity() : ScopedActivity(0, 0, 0) {} |
| 1271 |
| 1272 | // Changes the |action| and/or |info| of this activity on the stack. This |
| 1273 | // is useful for tracking progress through a function, updating the action |
| 1274 | // to indicate "milestones" in the block (max 16 milestones: 0-15) or the |
| 1275 | // info to reflect other changes. Changing both is not atomic so a snapshot |
| 1276 | // operation could occur between the update of |action| and |info|. |
| 1277 | void ChangeAction(uint8_t action); |
| 1278 | void ChangeInfo(int32_t info); |
| 1279 | void ChangeActionAndInfo(uint8_t action, int32_t info); |
| 1280 |
| 1281 | private: |
| 1282 | // Constructs the object using a passed-in program-counter. |
| 1283 | ScopedActivity(const void* program_counter, |
| 1284 | uint8_t action, |
| 1285 | uint32_t id, |
| 1286 | int32_t info); |
| 1287 |
| 1288 | // A copy of the ID code so it doesn't have to be passed by the caller when |
| 1289 | // changing the |info| field. |
| 1290 | uint32_t id_; |
| 1291 |
| 1292 | DISALLOW_COPY_AND_ASSIGN(ScopedActivity); |
| 1293 | }; |
| 1294 |
| 1295 |
| 1296 | // These "scoped" classes provide easy tracking of various blocking actions. |
| 1297 |
| 1298 | class BASE_EXPORT ScopedTaskRunActivity |
| 1299 | : public GlobalActivityTracker::ScopedThreadActivity { |
| 1300 | public: |
| 1301 | ALWAYS_INLINE |
| 1302 | explicit ScopedTaskRunActivity(const PendingTask& task) |
| 1303 | : ScopedTaskRunActivity(GetProgramCounter(), task) {} |
| 1304 |
| 1305 | private: |
| 1306 | ScopedTaskRunActivity(const void* program_counter, const PendingTask& task); |
| 1307 | DISALLOW_COPY_AND_ASSIGN(ScopedTaskRunActivity); |
| 1308 | }; |
| 1309 |
| 1310 | class BASE_EXPORT ScopedLockAcquireActivity |
| 1311 | : public GlobalActivityTracker::ScopedThreadActivity { |
| 1312 | public: |
| 1313 | ALWAYS_INLINE |
| 1314 | explicit ScopedLockAcquireActivity(const base::internal::LockImpl* lock) |
| 1315 | : ScopedLockAcquireActivity(GetProgramCounter(), lock) {} |
| 1316 |
| 1317 | private: |
| 1318 | ScopedLockAcquireActivity(const void* program_counter, |
| 1319 | const base::internal::LockImpl* lock); |
| 1320 | DISALLOW_COPY_AND_ASSIGN(ScopedLockAcquireActivity); |
| 1321 | }; |
| 1322 |
| 1323 | class BASE_EXPORT ScopedEventWaitActivity |
| 1324 | : public GlobalActivityTracker::ScopedThreadActivity { |
| 1325 | public: |
| 1326 | ALWAYS_INLINE |
| 1327 | explicit ScopedEventWaitActivity(const WaitableEvent* event) |
| 1328 | : ScopedEventWaitActivity(GetProgramCounter(), event) {} |
| 1329 |
| 1330 | private: |
| 1331 | ScopedEventWaitActivity(const void* program_counter, |
| 1332 | const WaitableEvent* event); |
| 1333 | DISALLOW_COPY_AND_ASSIGN(ScopedEventWaitActivity); |
| 1334 | }; |
| 1335 |
| 1336 | class BASE_EXPORT ScopedThreadJoinActivity |
| 1337 | : public GlobalActivityTracker::ScopedThreadActivity { |
| 1338 | public: |
| 1339 | ALWAYS_INLINE |
| 1340 | explicit ScopedThreadJoinActivity(const PlatformThreadHandle* thread) |
| 1341 | : ScopedThreadJoinActivity(GetProgramCounter(), thread) {} |
| 1342 |
| 1343 | private: |
| 1344 | ScopedThreadJoinActivity(const void* program_counter, |
| 1345 | const PlatformThreadHandle* thread); |
| 1346 | DISALLOW_COPY_AND_ASSIGN(ScopedThreadJoinActivity); |
| 1347 | }; |
| 1348 |
| 1349 | // Some systems don't have base::Process |
| 1350 | #if !defined(OS_NACL) && !defined(OS_IOS) |
| 1351 | class BASE_EXPORT ScopedProcessWaitActivity |
| 1352 | : public GlobalActivityTracker::ScopedThreadActivity { |
| 1353 | public: |
| 1354 | ALWAYS_INLINE |
| 1355 | explicit ScopedProcessWaitActivity(const Process* process) |
| 1356 | : ScopedProcessWaitActivity(GetProgramCounter(), process) {} |
| 1357 |
| 1358 | private: |
| 1359 | ScopedProcessWaitActivity(const void* program_counter, |
| 1360 | const Process* process); |
| 1361 | DISALLOW_COPY_AND_ASSIGN(ScopedProcessWaitActivity); |
| 1362 | }; |
| 1363 | #endif |
| 1364 |
| 1365 | } // namespace debug |
| 1366 | } // namespace base |
| 1367 |
| 1368 | #endif // BASE_DEBUG_ACTIVITY_TRACKER_H_ |
| 1369 |