blob: 0cb6b5964a569fc04dd0defbafd287da29e0ef8a [file] [log] [blame]
Ryan Harrisondbc13af2022-02-21 15:19:07 +00001// Copyright 2022 The Tint Authors.
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
dan sinclair22b4dd22023-07-21 00:40:07 +000015#include "src/tint/utils/debug/debugger.h"
Ryan Harrisondbc13af2022-02-21 15:19:07 +000016
17#ifdef TINT_ENABLE_BREAK_IN_DEBUGGER
18
19#ifdef _MSC_VER
20#include <Windows.h>
21#elif defined(__linux__)
22#include <signal.h>
23#include <fstream>
24#include <string>
25#endif
26
27#ifdef _MSC_VER
28#define TINT_DEBUGGER_BREAK_DEFINED
29void tint::debugger::Break() {
dan sinclair41e4d9a2022-05-01 14:40:55 +000030 if (::IsDebuggerPresent()) {
31 ::DebugBreak();
32 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +000033}
34
35#elif defined(__linux__)
36
37#define TINT_DEBUGGER_BREAK_DEFINED
38void tint::debugger::Break() {
dan sinclair41e4d9a2022-05-01 14:40:55 +000039 // A process is being traced (debugged) if "/proc/self/status" contains a
40 // line with "TracerPid: <non-zero-digit>...".
41 bool is_traced = false;
42 std::ifstream fin("/proc/self/status");
43 std::string line;
44 while (!is_traced && std::getline(fin, line)) {
45 const char kPrefix[] = "TracerPid:\t";
46 static constexpr int kPrefixLen = sizeof(kPrefix) - 1;
47 if (line.length() > kPrefixLen && line.compare(0, kPrefixLen, kPrefix) == 0) {
48 is_traced = line[kPrefixLen] != '0';
49 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +000050 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +000051
dan sinclair41e4d9a2022-05-01 14:40:55 +000052 if (is_traced) {
53 raise(SIGTRAP);
54 }
Ryan Harrisondbc13af2022-02-21 15:19:07 +000055}
56#endif // platform
57
58#endif // TINT_ENABLE_BREAK_IN_DEBUGGER
59
60#ifndef TINT_DEBUGGER_BREAK_DEFINED
61void tint::debugger::Break() {}
62#endif