Copyright 2014->2015
[folly.git] / folly / experimental / exception_tracer / StackTrace.h
1 /*
2  * Copyright 2015 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17
18 #ifndef FOLLY_EXPERIMENTAL_EXCEPTION_TRACER_STACKTRACE_H_
19 #define FOLLY_EXPERIMENTAL_EXCEPTION_TRACER_STACKTRACE_H_
20
21 #include <cassert>
22 #include <cstddef>
23 #include <cstdint>
24
25 namespace folly { namespace exception_tracer {
26
27 constexpr size_t kMaxFrames = 500;
28
29 struct StackTrace {
30   StackTrace() : frameCount(0) { }
31
32   size_t frameCount;
33   uintptr_t addresses[kMaxFrames];
34 };
35
36 // note: no constructor so this can be __thread.
37 // A StackTraceStack MUST be placed in zero-initialized memory.
38 class StackTraceStack {
39   class Node;
40  public:
41   /**
42    * Push the current stack trace onto the stack.
43    * Returns false on failure (not enough memory, getting stack trace failed),
44    * true on success.
45    */
46   bool pushCurrent();
47
48   /**
49    * Pop the top stack trace from the stack.
50    * Returns true on success, false on failure (stack was empty).
51    */
52   bool pop();
53
54   /**
55    * Move the top stack trace from other onto this.
56    * Returns true on success, false on failure (other was empty).
57    */
58   bool moveTopFrom(StackTraceStack& other);
59
60   /**
61    * Clear the stack.
62    */
63
64   void clear();
65
66   /**
67    * Is the stack empty?
68    */
69   bool empty() const { return !top_; }
70
71   /**
72    * Return the top stack trace, or nullptr if the stack is empty.
73    */
74   StackTrace* top();
75
76   /**
77    * Return the stack trace following p, or nullptr if p is the bottom of
78    * the stack.
79    */
80   StackTrace* next(StackTrace* p);
81
82  private:
83   // In debug mode, we assert that we're in zero-initialized memory by
84   // checking that the two guards around top_ are zero.
85   void checkGuard() const {
86 #ifndef NDEBUG
87     assert(guard1_ == 0 && guard2_ == 0);
88 #endif
89   }
90
91 #ifndef NDEBUG
92   uintptr_t guard1_;
93 #endif
94   Node* top_;
95 #ifndef NDEBUG
96   uintptr_t guard2_;
97 #endif
98 };
99
100 }}  // namespaces
101
102 #endif /* FOLLY_EXPERIMENTAL_EXCEPTION_TRACER_STACKTRACE_H_ */