activity_tracker.h 55 KB

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