1 // Copyright (c) 2012 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
5 #include "build/build_config.h"
6
7 #if defined(COMPILER_MSVC)
8 #include <intrin.h>
9 #endif
10
11 #include "base/location.h"
12 #include "base/strings/string_number_conversions.h"
13 #include "base/strings/stringprintf.h"
14
15 namespace tracked_objects {
16
Location(const char * function_name,const char * file_name,int line_number,const void * program_counter)17 Location::Location(const char* function_name,
18 const char* file_name,
19 int line_number,
20 const void* program_counter)
21 : function_name_(function_name),
22 file_name_(file_name),
23 line_number_(line_number),
24 program_counter_(program_counter) {
25 }
26
Location()27 Location::Location()
28 : function_name_("Unknown"),
29 file_name_("Unknown"),
30 line_number_(-1),
31 program_counter_(NULL) {
32 }
33
ToString() const34 std::string Location::ToString() const {
35 return std::string(function_name_) + "@" + file_name_ + ":" +
36 base::IntToString(line_number_);
37 }
38
Write(bool display_filename,bool display_function_name,std::string * output) const39 void Location::Write(bool display_filename, bool display_function_name,
40 std::string* output) const {
41 base::StringAppendF(output, "%s[%d] ",
42 display_filename ? file_name_ : "line",
43 line_number_);
44
45 if (display_function_name) {
46 WriteFunctionName(output);
47 output->push_back(' ');
48 }
49 }
50
WriteFunctionName(std::string * output) const51 void Location::WriteFunctionName(std::string* output) const {
52 // Translate "<" to "<" for HTML safety.
53 // TODO(jar): Support ASCII or html for logging in ASCII.
54 for (const char *p = function_name_; *p; p++) {
55 switch (*p) {
56 case '<':
57 output->append("<");
58 break;
59
60 case '>':
61 output->append(">");
62 break;
63
64 default:
65 output->push_back(*p);
66 break;
67 }
68 }
69 }
70
71 //------------------------------------------------------------------------------
LocationSnapshot()72 LocationSnapshot::LocationSnapshot() : line_number(-1) {
73 }
74
LocationSnapshot(const tracked_objects::Location & location)75 LocationSnapshot::LocationSnapshot(
76 const tracked_objects::Location& location)
77 : file_name(location.file_name()),
78 function_name(location.function_name()),
79 line_number(location.line_number()) {
80 }
81
~LocationSnapshot()82 LocationSnapshot::~LocationSnapshot() {
83 }
84
85 //------------------------------------------------------------------------------
86 #if defined(COMPILER_MSVC)
87 __declspec(noinline)
88 #endif
GetProgramCounter()89 BASE_EXPORT const void* GetProgramCounter() {
90 #if defined(COMPILER_MSVC)
91 return _ReturnAddress();
92 #elif defined(COMPILER_GCC) && !defined(OS_NACL)
93 return __builtin_extract_return_addr(__builtin_return_address(0));
94 #else
95 return NULL;
96 #endif
97 }
98
99 } // namespace tracked_objects
100