• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2017 The Android Open Source Project
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 #include <dlfcn.h>
18 #include "logging_macros.h"
19 #include <cstdio>
20 #include "trace.h"
21 
22 static const int TRACE_MAX_SECTION_NAME_LENGTH = 100;
23 
24 // Tracing functions
25 static void *(*ATrace_beginSection)(const char *sectionName);
26 
27 static void *(*ATrace_endSection)(void);
28 
29 static bool *(*ATrace_isEnabled)(void);
30 
31 typedef void *(*fp_ATrace_beginSection)(const char *sectionName);
32 
33 typedef void *(*fp_ATrace_endSection)(void);
34 
35 typedef bool *(*fp_ATrace_isEnabled)(void);
36 
37 bool Trace::is_enabled_ = false;
38 bool Trace::has_error_been_shown_ = false;
39 
beginSection(const char * fmt,...)40 void Trace::beginSection(const char *fmt, ...) {
41 
42   if (is_enabled_) {
43     static char buff[TRACE_MAX_SECTION_NAME_LENGTH];
44     va_list args;
45     va_start(args, fmt);
46     vsprintf(buff, fmt, args);
47     va_end(args);
48     ATrace_beginSection(buff);
49   } else if (!has_error_been_shown_) {
50     LOGE("Tracing is either not initialized (call Trace::initialize()) "
51          "or not supported on this device");
52     has_error_been_shown_ = true;
53   }
54 }
55 
endSection()56 void Trace::endSection() {
57 
58   if (is_enabled_) {
59     ATrace_endSection();
60   }
61 }
62 
initialize()63 void Trace::initialize() {
64 
65   // Using dlsym allows us to use tracing on API 21+ without needing android/trace.h which wasn't
66   // published until API 23
67   void *lib = dlopen("libandroid.so", RTLD_NOW | RTLD_LOCAL);
68   if (lib == nullptr) {
69     LOGE("Could not open libandroid.so to dynamically load tracing symbols");
70   } else {
71     ATrace_beginSection =
72         reinterpret_cast<fp_ATrace_beginSection >(
73             dlsym(lib, "ATrace_beginSection"));
74     ATrace_endSection =
75         reinterpret_cast<fp_ATrace_endSection >(
76             dlsym(lib, "ATrace_endSection"));
77     ATrace_isEnabled =
78         reinterpret_cast<fp_ATrace_isEnabled >(
79             dlsym(lib, "ATrace_isEnabled"));
80 
81     if (ATrace_isEnabled != nullptr && ATrace_isEnabled()) {
82       is_enabled_ = true;
83     }
84   }
85 }
86