1 /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
2
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6
7 http://www.apache.org/licenses/LICENSE-2.0
8
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 ==============================================================================*/
15
16 #ifndef TENSORFLOW_CORE_UTIL_ABSTRACT_STACK_TRACE_H_
17 #define TENSORFLOW_CORE_UTIL_ABSTRACT_STACK_TRACE_H_
18
19 #include <string>
20 #include <vector>
21
22 #include "absl/strings/match.h"
23 #include "absl/types/optional.h"
24 #include "tensorflow/core/platform/stack_frame.h"
25
26 namespace tensorflow {
27
28 // Maps filename/line_no combination into a stack frame.
29 using StackTraceMap =
30 std::function<absl::optional<StackFrame>(std::pair<const char*, int>)>;
31
32 // Returns "true" on filenames which should be skipped.
33 using StackTraceFilter = std::function<bool(const char*)>;
34
35 using ToStackFramesFunctor = std::vector<StackFrame>(int, const StackTraceMap&,
36 const StackTraceFilter&,
37 bool, int);
38
39 // Returns whether the given frame is internal to TF.
IsInternalFrameForFilename(absl::string_view file_name)40 inline bool IsInternalFrameForFilename(absl::string_view file_name) {
41 // Use a simple heuristic for now.
42 // TODO(cheshire): Build a more sophisticated mechanism, rely on @tf.export.
43 return (absl::StrContains(file_name, "tensorflow/python") ||
44 absl::StrContains(file_name, "tensorflow\\python")) &&
45 !absl::StrContains(file_name, "keras") &&
46 !absl::StrContains(file_name, "test.py");
47 }
48
49 // Language agnostic stack trace class. It only saves an id, and language
50 // clients are responsible for managing the actual stack trace objects.
51 class ManagedStackTrace {
52 public:
ManagedStackTrace(int id,ToStackFramesFunctor * to_stack_frames)53 ManagedStackTrace(int id, ToStackFramesFunctor* to_stack_frames)
54 : id_(id), to_stack_frames_(to_stack_frames) {}
55
56 // Returns stack trace as a vector of `StackFrame`s.
57 std::vector<StackFrame> ToStackFrames(const StackTraceMap& mapper = {},
58 const StackTraceFilter& filtered = {},
59 bool reverse_traversal = false,
60 int limit = -1) const {
61 return to_stack_frames_(id_, mapper, filtered, reverse_traversal, limit);
62 }
63
64 private:
65 int id_;
66 ToStackFramesFunctor* to_stack_frames_;
67 };
68
69 } // namespace tensorflow
70
71 #endif // TENSORFLOW_CORE_UTIL_ABSTRACT_STACK_TRACE_H_
72