Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
hrydgard
GitHub Repository: hrydgard/ppsspp
Path: blob/master/Core/Debugger/WebSocket.cpp
3186 views
1
// Copyright (c) 2017- PPSSPP Project.
2
3
// This program is free software: you can redistribute it and/or modify
4
// it under the terms of the GNU General Public License as published by
5
// the Free Software Foundation, version 2.0 or later versions.
6
7
// This program is distributed in the hope that it will be useful,
8
// but WITHOUT ANY WARRANTY; without even the implied warranty of
9
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10
// GNU General Public License 2.0 for more details.
11
12
// A copy of the GPL 2.0 should have been included with the program.
13
// If not, see http://www.gnu.org/licenses/
14
15
// Official git repository and contact information can be found at
16
// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/.
17
18
#include <mutex>
19
#include <condition_variable>
20
21
#include "Common/Thread/ThreadUtil.h"
22
#include "Core/Debugger/WebSocket.h"
23
#include "Core/Debugger/WebSocket/WebSocketUtils.h"
24
25
// This WebSocket (connected through the same port as disc sharing) allows API/debugger access to PPSSPP.
26
// Currently, the only subprotocol "debugger.ppsspp.org" uses a simple JSON based interface.
27
//
28
// Messages to and from PPSSPP follow the same basic format:
29
// { "event": "NAME", ... }
30
//
31
// And are primarily of these types:
32
// * Events from the debugger/client (you) to PPSSPP
33
// If there's a response, it will generally use the same name. It may not be immedate - it's an event.
34
// * Spontaneous events from PPSSPP
35
// Things like logs, breakpoint hits, etc. not directly requested.
36
//
37
// Otherwise you may see error events which indicate PPSSPP couldn't understand or failed internally:
38
// - "event": "error"
39
// - "message": A string describing what happened.
40
// - "level": Integer severity level. (1 = NOTICE, 2 = ERROR, 3 = WARN, 4 = INFO, 5 = DEBUG, 6 = VERBOSE)
41
// - "ticket": Optional, present if in response to an event with a "ticket" field, simply repeats that value.
42
//
43
// At start, please send a "version" event. See WebSocket/GameSubscriber.cpp for more details.
44
//
45
// For other events, look inside Core/Debugger/WebSocket/ for details on each event.
46
47
#include "Core/Debugger/WebSocket/GameBroadcaster.h"
48
#include "Core/Debugger/WebSocket/InputBroadcaster.h"
49
#include "Core/Debugger/WebSocket/LogBroadcaster.h"
50
#include "Core/Debugger/WebSocket/SteppingBroadcaster.h"
51
52
#include "Core/Debugger/WebSocket/BreakpointSubscriber.h"
53
#include "Core/Debugger/WebSocket/CPUCoreSubscriber.h"
54
#include "Core/Debugger/WebSocket/DisasmSubscriber.h"
55
#include "Core/Debugger/WebSocket/GameSubscriber.h"
56
#include "Core/Debugger/WebSocket/GPUBufferSubscriber.h"
57
#include "Core/Debugger/WebSocket/GPURecordSubscriber.h"
58
#include "Core/Debugger/WebSocket/GPUStatsSubscriber.h"
59
#include "Core/Debugger/WebSocket/HLESubscriber.h"
60
#include "Core/Debugger/WebSocket/InputSubscriber.h"
61
#include "Core/Debugger/WebSocket/MemoryInfoSubscriber.h"
62
#include "Core/Debugger/WebSocket/MemorySubscriber.h"
63
#include "Core/Debugger/WebSocket/ReplaySubscriber.h"
64
#include "Core/Debugger/WebSocket/SteppingSubscriber.h"
65
#include "Core/Debugger/WebSocket/ClientConfigSubscriber.h"
66
67
typedef DebuggerSubscriber *(*SubscriberInit)(DebuggerEventHandlerMap &map);
68
static const std::vector<SubscriberInit> subscribers({
69
&WebSocketBreakpointInit,
70
&WebSocketCPUCoreInit,
71
&WebSocketDisasmInit,
72
&WebSocketGameInit,
73
&WebSocketGPUBufferInit,
74
&WebSocketGPURecordInit,
75
&WebSocketGPUStatsInit,
76
&WebSocketHLEInit,
77
&WebSocketInputInit,
78
&WebSocketMemoryInfoInit,
79
&WebSocketMemoryInit,
80
&WebSocketReplayInit,
81
&WebSocketSteppingInit,
82
&WebSocketClientConfigInit,
83
});
84
85
// To handle webserver restart, keep track of how many running.
86
static volatile int debuggersConnected = 0;
87
static volatile bool stopRequested = false;
88
static std::mutex stopLock;
89
static std::condition_variable stopCond;
90
91
// Prevent threading surprises and obscure crashes by locking startup/shutdown.
92
static bool lifecycleLockSetup = false;
93
static std::mutex lifecycleLock;
94
95
static void UpdateConnected(int delta) {
96
std::lock_guard<std::mutex> guard(stopLock);
97
debuggersConnected += delta;
98
stopCond.notify_all();
99
}
100
101
static void WebSocketNotifyLifecycle(CoreLifecycle stage) {
102
switch (stage) {
103
case CoreLifecycle::STARTING:
104
case CoreLifecycle::STOPPING:
105
case CoreLifecycle::MEMORY_REINITING:
106
if (debuggersConnected > 0) {
107
DEBUG_LOG(Log::System, "Waiting for debugger to complete on shutdown");
108
}
109
lifecycleLock.lock();
110
break;
111
112
case CoreLifecycle::START_COMPLETE:
113
case CoreLifecycle::STOPPED:
114
case CoreLifecycle::MEMORY_REINITED:
115
lifecycleLock.unlock();
116
if (debuggersConnected > 0) {
117
DEBUG_LOG(Log::System, "Debugger ready for shutdown");
118
}
119
break;
120
}
121
}
122
123
static void SetupDebuggerLock() {
124
if (!lifecycleLockSetup) {
125
Core_ListenLifecycle(&WebSocketNotifyLifecycle);
126
lifecycleLockSetup = true;
127
}
128
}
129
130
void HandleDebuggerRequest(const http::ServerRequest &request) {
131
net::WebSocketServer *ws = net::WebSocketServer::CreateAsUpgrade(request, "debugger.ppsspp.org");
132
if (!ws)
133
return;
134
135
SetCurrentThreadName("Debugger");
136
UpdateConnected(1);
137
SetupDebuggerLock();
138
139
WebSocketClientInfo client_info;
140
auto& disallowed_config = client_info.disallowed;
141
142
GameBroadcaster game;
143
LogBroadcaster logger;
144
InputBroadcaster input;
145
SteppingBroadcaster stepping;
146
147
std::unordered_map<std::string, DebuggerEventHandler> eventHandlers;
148
std::vector<DebuggerSubscriber *> subscriberData;
149
for (auto init : subscribers) {
150
std::lock_guard<std::mutex> guard(lifecycleLock);
151
subscriberData.push_back(init(eventHandlers));
152
}
153
154
// There's a tradeoff between responsiveness to incoming events, and polling for changes.
155
int highActivity = 0;
156
ws->SetTextHandler([&](const std::string &t) {
157
JsonReader reader(t.c_str(), t.size());
158
if (!reader.ok()) {
159
ws->Send(DebuggerErrorEvent("Bad message: invalid JSON", LogLevel::LERROR));
160
return;
161
}
162
163
const JsonGet root = reader.root();
164
const char *event = root ? root.getStringOr("event", nullptr) : nullptr;
165
if (!event) {
166
ws->Send(DebuggerErrorEvent("Bad message: no event property", LogLevel::LERROR, root));
167
return;
168
}
169
170
DebuggerRequest req(event, ws, root, &client_info);
171
auto eventFunc = eventHandlers.find(event);
172
if (eventFunc != eventHandlers.end()) {
173
std::lock_guard<std::mutex> guard(lifecycleLock);
174
eventFunc->second(req);
175
if (!req.Finish()) {
176
// Poll more frequently for a second in case this triggers something.
177
highActivity = 1000;
178
}
179
} else {
180
req.Fail("Bad message: unknown event");
181
}
182
});
183
ws->SetBinaryHandler([&](const std::vector<uint8_t> &d) {
184
ws->Send(DebuggerErrorEvent("Bad message", LogLevel::LERROR));
185
});
186
187
while (ws->Process(highActivity ? 1.0f / 1000.0f : 1.0f / 60.0f)) {
188
std::lock_guard<std::mutex> guard(lifecycleLock);
189
// These send events that aren't just responses to requests
190
191
// The client can explicitly ask not to be notified about some events
192
// so we check the client settings first
193
if (!disallowed_config["logger"])
194
logger.Broadcast(ws);
195
if (!disallowed_config["game"])
196
game.Broadcast(ws);
197
if (!disallowed_config["stepping"])
198
stepping.Broadcast(ws);
199
if (!disallowed_config["input"])
200
input.Broadcast(ws);
201
202
for (size_t i = 0; i < subscribers.size(); ++i) {
203
if (subscriberData[i]) {
204
subscriberData[i]->Broadcast(ws);
205
}
206
}
207
208
if (stopRequested) {
209
ws->Close(net::WebSocketClose::GOING_AWAY);
210
}
211
if (highActivity > 0) {
212
highActivity--;
213
}
214
}
215
216
std::lock_guard<std::mutex> guard(lifecycleLock);
217
for (size_t i = 0; i < subscribers.size(); ++i) {
218
delete subscriberData[i];
219
}
220
221
delete ws;
222
request.In()->Discard();
223
UpdateConnected(-1);
224
}
225
226
void StopAllDebuggers() {
227
std::unique_lock<std::mutex> guard(stopLock);
228
while (debuggersConnected != 0) {
229
stopRequested = true;
230
stopCond.wait(guard);
231
}
232
233
// Reset it back for next time.
234
stopRequested = false;
235
}
236
237