Ryan Harrison | dbc13af | 2022-02-21 15:19:07 +0000 | [diff] [blame] | 1 | // 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 sinclair | 22b4dd2 | 2023-07-21 00:40:07 +0000 | [diff] [blame] | 15 | #include "src/tint/utils/debug/debugger.h" |
Ryan Harrison | dbc13af | 2022-02-21 15:19:07 +0000 | [diff] [blame] | 16 | |
| 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 |
| 29 | void tint::debugger::Break() { |
dan sinclair | 41e4d9a | 2022-05-01 14:40:55 +0000 | [diff] [blame] | 30 | if (::IsDebuggerPresent()) { |
| 31 | ::DebugBreak(); |
| 32 | } |
Ryan Harrison | dbc13af | 2022-02-21 15:19:07 +0000 | [diff] [blame] | 33 | } |
| 34 | |
| 35 | #elif defined(__linux__) |
| 36 | |
| 37 | #define TINT_DEBUGGER_BREAK_DEFINED |
| 38 | void tint::debugger::Break() { |
dan sinclair | 41e4d9a | 2022-05-01 14:40:55 +0000 | [diff] [blame] | 39 | // 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 Harrison | dbc13af | 2022-02-21 15:19:07 +0000 | [diff] [blame] | 50 | } |
Ryan Harrison | dbc13af | 2022-02-21 15:19:07 +0000 | [diff] [blame] | 51 | |
dan sinclair | 41e4d9a | 2022-05-01 14:40:55 +0000 | [diff] [blame] | 52 | if (is_traced) { |
| 53 | raise(SIGTRAP); |
| 54 | } |
Ryan Harrison | dbc13af | 2022-02-21 15:19:07 +0000 | [diff] [blame] | 55 | } |
| 56 | #endif // platform |
| 57 | |
| 58 | #endif // TINT_ENABLE_BREAK_IN_DEBUGGER |
| 59 | |
| 60 | #ifndef TINT_DEBUGGER_BREAK_DEFINED |
| 61 | void tint::debugger::Break() {} |
| 62 | #endif |