1// Copyright 2018 the V8 project 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#ifndef V8_CODE_TRACER_H_
6#define V8_CODE_TRACER_H_
7
8#include "src/allocation.h"
9#include "src/flags.h"
10#include "src/globals.h"
11#include "src/utils.h"
12#include "src/vector.h"
13
14namespace v8 {
15namespace internal {
16
17class CodeTracer final : public Malloced {
18 public:
19 explicit CodeTracer(int isolate_id) : file_(nullptr), scope_depth_(0) {
20 if (!ShouldRedirect()) {
21 file_ = stdout;
22 return;
23 }
24
25 if (FLAG_redirect_code_traces_to != nullptr) {
26 StrNCpy(filename_, FLAG_redirect_code_traces_to, filename_.length());
27 } else if (isolate_id >= 0) {
28 SNPrintF(filename_, "code-%d-%d.asm", base::OS::GetCurrentProcessId(),
29 isolate_id);
30 } else {
31 SNPrintF(filename_, "code-%d.asm", base::OS::GetCurrentProcessId());
32 }
33
34 WriteChars(filename_.start(), "", 0, false);
35 }
36
37 class Scope {
38 public:
39 explicit Scope(CodeTracer* tracer) : tracer_(tracer) { tracer->OpenFile(); }
40 ~Scope() { tracer_->CloseFile(); }
41
42 FILE* file() const { return tracer_->file(); }
43
44 private:
45 CodeTracer* tracer_;
46 };
47
48 void OpenFile() {
49 if (!ShouldRedirect()) {
50 return;
51 }
52
53 if (file_ == nullptr) {
54 file_ = base::OS::FOpen(filename_.start(), "ab");
55 }
56
57 scope_depth_++;
58 }
59
60 void CloseFile() {
61 if (!ShouldRedirect()) {
62 return;
63 }
64
65 if (--scope_depth_ == 0) {
66 fclose(file_);
67 file_ = nullptr;
68 }
69 }
70
71 FILE* file() const { return file_; }
72
73 private:
74 static bool ShouldRedirect() { return FLAG_redirect_code_traces; }
75
76 EmbeddedVector<char, 128> filename_;
77 FILE* file_;
78 int scope_depth_;
79};
80
81} // namespace internal
82} // namespace v8
83
84#endif // V8_CODE_TRACER_H_
85