activity_tracker.h 55 KB

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