CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
hrydgard

CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!

GitHub Repository: hrydgard/ppsspp
Path: blob/master/Core/Debugger/WebSocket.cpp
Views: 1401
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
#include "Common/Thread/ThreadUtil.h"
21
#include "Core/Debugger/WebSocket.h"
22
#include "Core/Debugger/WebSocket/WebSocketUtils.h"
23
#include "Core/MemMap.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
// We'll likely already be locked during the reboot.
103
if (PSP_IsRebooting())
104
return;
105
106
switch (stage) {
107
case CoreLifecycle::STARTING:
108
case CoreLifecycle::STOPPING:
109
case CoreLifecycle::MEMORY_REINITING:
110
if (debuggersConnected > 0) {
111
DEBUG_LOG(Log::System, "Waiting for debugger to complete on shutdown");
112
}
113
lifecycleLock.lock();
114
break;
115
116
case CoreLifecycle::START_COMPLETE:
117
case CoreLifecycle::STOPPED:
118
case CoreLifecycle::MEMORY_REINITED:
119
lifecycleLock.unlock();
120
if (debuggersConnected > 0) {
121
DEBUG_LOG(Log::System, "Debugger ready for shutdown");
122
}
123
break;
124
}
125
}
126
127
static void SetupDebuggerLock() {
128
if (!lifecycleLockSetup) {
129
Core_ListenLifecycle(&WebSocketNotifyLifecycle);
130
lifecycleLockSetup = true;
131
}
132
}
133
134
void HandleDebuggerRequest(const http::ServerRequest &request) {
135
net::WebSocketServer *ws = net::WebSocketServer::CreateAsUpgrade(request, "debugger.ppsspp.org");
136
if (!ws)
137
return;
138
139
SetCurrentThreadName("Debugger");
140
UpdateConnected(1);
141
SetupDebuggerLock();
142
143
WebSocketClientInfo client_info;
144
auto& disallowed_config = client_info.disallowed;
145
146
GameBroadcaster game;
147
LogBroadcaster logger;
148
InputBroadcaster input;
149
SteppingBroadcaster stepping;
150
151
std::unordered_map<std::string, DebuggerEventHandler> eventHandlers;
152
std::vector<DebuggerSubscriber *> subscriberData;
153
for (auto init : subscribers) {
154
std::lock_guard<std::mutex> guard(lifecycleLock);
155
subscriberData.push_back(init(eventHandlers));
156
}
157
158
// There's a tradeoff between responsiveness to incoming events, and polling for changes.
159
int highActivity = 0;
160
ws->SetTextHandler([&](const std::string &t) {
161
JsonReader reader(t.c_str(), t.size());
162
if (!reader.ok()) {
163
ws->Send(DebuggerErrorEvent("Bad message: invalid JSON", LogLevel::LERROR));
164
return;
165
}
166
167
const JsonGet root = reader.root();
168
const char *event = root ? root.getStringOr("event", nullptr) : nullptr;
169
if (!event) {
170
ws->Send(DebuggerErrorEvent("Bad message: no event property", LogLevel::LERROR, root));
171
return;
172
}
173
174
DebuggerRequest req(event, ws, root, &client_info);
175
auto eventFunc = eventHandlers.find(event);
176
if (eventFunc != eventHandlers.end()) {
177
std::lock_guard<std::mutex> guard(lifecycleLock);
178
eventFunc->second(req);
179
if (!req.Finish()) {
180
// Poll more frequently for a second in case this triggers something.
181
highActivity = 1000;
182
}
183
} else {
184
req.Fail("Bad message: unknown event");
185
}
186
});
187
ws->SetBinaryHandler([&](const std::vector<uint8_t> &d) {
188
ws->Send(DebuggerErrorEvent("Bad message", LogLevel::LERROR));
189
});
190
191
while (ws->Process(highActivity ? 1.0f / 1000.0f : 1.0f / 60.0f)) {
192
std::lock_guard<std::mutex> guard(lifecycleLock);
193
// These send events that aren't just responses to requests
194
195
// The client can explicitly ask not to be notified about some events
196
// so we check the client settings first
197
if (!disallowed_config["logger"])
198
logger.Broadcast(ws);
199
if (!disallowed_config["game"])
200
game.Broadcast(ws);
201
if (!disallowed_config["stepping"])
202
stepping.Broadcast(ws);
203
if (!disallowed_config["input"])
204
input.Broadcast(ws);
205
206
for (size_t i = 0; i < subscribers.size(); ++i) {
207
if (subscriberData[i]) {
208
subscriberData[i]->Broadcast(ws);
209
}
210
}
211
212
if (stopRequested) {
213
ws->Close(net::WebSocketClose::GOING_AWAY);
214
}
215
if (highActivity > 0) {
216
highActivity--;
217
}
218
}
219
220
std::lock_guard<std::mutex> guard(lifecycleLock);
221
for (size_t i = 0; i < subscribers.size(); ++i) {
222
delete subscriberData[i];
223
}
224
225
delete ws;
226
request.In()->Discard();
227
UpdateConnected(-1);
228
}
229
230
void StopAllDebuggers() {
231
std::unique_lock<std::mutex> guard(stopLock);
232
while (debuggersConnected != 0) {
233
stopRequested = true;
234
stopCond.wait(guard);
235
}
236
237
// Reset it back for next time.
238
stopRequested = false;
239
}
240
241