Repository navigation
Expand file tree
/
Copy pathExampleMod.cpp
More file actions
395 lines (355 loc) · 14.1 KB
/
Copy pathExampleMod.cpp
File metadata and controls
395 lines (355 loc) · 14.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
#include <cemod_example/ExampleMod.hpp>
#include <cemuextend/cemuextend.hpp>
#include <cemuextend/guest.hpp>
#include <cemuextend/services.hpp>
#include <game_profile.h>
#include <cstddef>
#include <cstring>
#include <span>
#include <string>
#include <string_view>
namespace cemod_example {
namespace {
namespace guest = cemuextend::guest;
namespace wire = cemuextend::wire;
// ---------------------------------------------------------------------------
// A 192-byte line builder, used instead of snprintf.
//
// The trusted-native payload runs inside a game's process from a codecave: it
// has its own 2 MiB heap and a hand-written set of newlib syscalls, and every
// libc facility it touches has to be paid for there. Formatting a handful of
// integers is not worth pulling newlib's stdio (and its reentrancy state, and
// its locking) into that image, so the mod formats its own.
// ---------------------------------------------------------------------------
class Line {
public:
Line& operator<<(std::string_view text) {
const std::size_t count = text.size() < remaining() ? text.size() : remaining();
std::memcpy(buffer_ + length_, text.data(), count);
length_ += count;
return *this;
}
Line& operator<<(const char* text) { return *this << std::string_view(text ? text : "<null>"); }
Line& operator<<(std::uint64_t value) {
char digits[20];
std::size_t count = 0;
do {
digits[count++] = static_cast<char>('0' + value % 10);
value /= 10;
} while (value);
while (count)
*this << std::string_view(&digits[--count], 1);
return *this;
}
Line& operator<<(std::int32_t value) {
if (value < 0) {
*this << "-";
return *this << static_cast<std::uint64_t>(-static_cast<std::int64_t>(value));
}
return *this << static_cast<std::uint64_t>(value);
}
Line& operator<<(std::uint32_t value) { return *this << static_cast<std::uint64_t>(value); }
[[nodiscard]] const char* c_str() {
buffer_[length_] = '\0';
return buffer_;
}
private:
[[nodiscard]] std::size_t remaining() const { return sizeof(buffer_) - 1 - length_; }
char buffer_[192]{};
std::size_t length_{};
};
const char* StatusName(wire::Status status) {
switch (status) {
case wire::Status::Ok: return "ok";
case wire::Status::InvalidArgument: return "invalid-argument";
case wire::Status::PermissionDenied: return "permission-denied";
case wire::Status::NotSupported: return "not-supported";
case wire::Status::Busy: return "busy";
case wire::Status::NotFound: return "not-found";
case wire::Status::TooLarge: return "too-large";
case wire::Status::ProtocolError: return "protocol-error";
case wire::Status::IoError: return "io-error";
case wire::Status::TimedOut: return "timed-out";
case wire::Status::Disconnected: return "disconnected";
case wire::Status::Cancelled: return "cancelled";
}
return "unknown";
}
const char* ErrorName(wire::Error error) {
switch (error) {
case wire::Error::Ok: return "ok";
case wire::Error::InvalidArgument: return "invalid-argument";
case wire::Error::Unavailable: return "unavailable";
case wire::Error::AbiMismatch: return "abi-mismatch";
case wire::Error::PermissionDenied: return "permission-denied";
case wire::Error::NotSupported: return "not-supported";
case wire::Error::Busy: return "busy";
case wire::Error::NotFound: return "not-found";
case wire::Error::TooLarge: return "too-large";
case wire::Error::ProtocolError: return "protocol-error";
case wire::Error::Disconnected: return "disconnected";
case wire::Error::IoError: return "io-error";
case wire::Error::TimedOut: return "timed-out";
}
return "unknown";
}
// ---------------------------------------------------------------------------
// Demo sequence.
//
// Each stage sends exactly one request and advances from that request's
// completion callback, so the whole thing runs on Pump() without a thread and
// without blocking the caller (which, in the trusted-native payload, is one of
// the game's own threads in the middle of a displaced instruction).
// ---------------------------------------------------------------------------
enum class Stage {
Announce, // Logging::Write -- show up in Cemu's log
ConfigWrite, // Configuration::Set
ConfigRead, // Configuration::Get, reads back what we just wrote
Services, // Core::GetServices
RoundTrip, // Core::Ping, timed with the host clock
Idle, // just Pump(), and report statistics now and then
Failed,
};
// The persistent key the demo writes. Namespacing config keys by mod id keeps
// two mods from fighting over one name.
constexpr std::string_view kLaunchCountKey = CEMOD_MOD_ID "/launch_count";
constexpr std::uint32_t kStatisticsInterval = 3600; // ticks
constexpr std::uint64_t kPingCookie = 0xC0FFEEULL;
struct State {
HostInterface host{};
guest::Client client;
Stage stage{Stage::Announce};
bool initialized{};
bool requestInFlight{};
std::uint32_t launchCount{};
std::uint32_t ticks{};
std::uint64_t pingSentNs{};
};
// Deliberately a pointer to a lazily constructed object rather than a plain
// global: the trusted-native payload runs .init_array itself, and keeping the
// client out of static construction means Initialize() decides when the
// allocator is first used.
State* g_state = nullptr;
void Log(const char* message) {
if (g_state && g_state->host.log)
g_state->host.log(message);
}
void Log(Line& line) { Log(line.c_str()); }
void Fail(const char* what, wire::Error error) {
Line line;
line << "cemuextend: " << what << " failed: " << ErrorName(error);
Log(line);
g_state->stage = Stage::Failed;
g_state->requestInFlight = false;
}
// Every stage funnels its response through here so a non-Ok status is
// reported once, in one place, instead of at six call sites.
bool Accept(const char* what, wire::Status status) {
g_state->requestInFlight = false;
if (status == wire::Status::Ok)
return true;
Line line;
line << "cemuextend: " << what << ": " << StatusName(status);
Log(line);
// A rejected request is not fatal -- Cemu refusing one service (say,
// configuration writes without the `write` permission) says nothing about
// the others -- so the sequence carries on.
return false;
}
void Announce();
void ConfigWrite();
void ConfigRead();
void QueryServices();
void RoundTrip();
void Announce() {
g_state->stage = Stage::Announce;
Line line;
line << CEMOD_MOD_ID " " CEMOD_GAME_DISPLAY_NAME " (profile " CEMOD_GAME_ID ")";
const wire::Error error = g_state->client.Log(
wire::LogLevel::Info, line.c_str(), [](wire::Status status, std::span<const std::byte>) {
if (Accept("logging.write", status))
Log("cemuextend: host logging works");
ConfigWrite();
});
if (error != wire::Error::Ok)
Fail("logging.write", error);
else
g_state->requestInFlight = true;
}
void ConfigWrite() {
g_state->stage = Stage::ConfigWrite;
// Cemu keeps this across launches, so it doubles as proof that the value
// really made it to the host: the count read back in the next stage should
// be one higher on every run.
const std::uint32_t next = g_state->launchCount + 1;
const wire::Be32 encoded{next};
const auto* bytes = reinterpret_cast<const std::byte*>(&encoded);
const wire::Error error = g_state->client.ConfigurationSet(
kLaunchCountKey, wire::ValueType::UnsignedInteger, {bytes, sizeof(encoded)},
[](wire::Status status, std::span<const std::byte>) {
Accept("configuration.set", status);
ConfigRead();
});
if (error != wire::Error::Ok)
Fail("configuration.set", error);
else
g_state->requestInFlight = true;
}
void ConfigRead() {
g_state->stage = Stage::ConfigRead;
const wire::Error error = g_state->client.ConfigurationGet(
kLaunchCountKey, [](wire::Status status, std::span<const std::byte> payload) {
if (Accept("configuration.get", status)) {
// Response: value type (u8), length (u32), value bytes.
wire::Decoder decoder(payload);
std::uint8_t type{};
std::uint32_t size{};
std::span<const std::byte> value;
std::uint32_t count{};
if (decoder.U8(type) && decoder.U32(size) && decoder.Bytes(size, value) &&
type == static_cast<std::uint8_t>(wire::ValueType::UnsignedInteger) &&
value.size() == sizeof(wire::Be32)) {
wire::Be32 encoded{};
std::memcpy(&encoded, value.data(), sizeof(encoded));
count = encoded.get();
g_state->launchCount = count;
}
Line line;
line << "cemuextend: launch #" << count;
Log(line);
}
QueryServices();
});
if (error != wire::Error::Ok)
Fail("configuration.get", error);
else
g_state->requestInFlight = true;
}
void QueryServices() {
g_state->stage = Stage::Services;
const wire::Error error = g_state->client.GetServices(
[](wire::Status status, std::span<const std::byte> payload) {
if (Accept("core.get-services", status)) {
// The list is a count followed by that many service records;
// the demo only reports how many Cemu offered.
wire::Decoder decoder(payload);
std::uint16_t count{};
(void)decoder.U16(count);
const guest::Version version = g_state->client.HostVersion();
Line line;
line << "cemuextend: host " << version.major << "." << version.minor
<< " build " << version.buildId << ", " << count << " services";
Log(line);
}
RoundTrip();
});
if (error != wire::Error::Ok)
Fail("core.get-services", error);
else
g_state->requestInFlight = true;
}
void RoundTrip() {
g_state->stage = Stage::RoundTrip;
g_state->pingSentNs = g_state->host.monotonicTimeNs();
// The cookie is echoed back unchanged; any value identifies the reply.
const wire::Error error = g_state->client.Ping(
kPingCookie, [](wire::Status status, std::span<const std::byte>) {
if (Accept("core.ping", status)) {
const std::uint64_t elapsed =
g_state->host.monotonicTimeNs() - g_state->pingSentNs;
Line line;
line << "cemuextend: ping round trip " << elapsed / 1000 << "us";
Log(line);
}
g_state->stage = Stage::Idle;
});
if (error != wire::Error::Ok)
Fail("core.ping", error);
else
g_state->requestInFlight = true;
}
void ReportStatistics() {
const guest::Statistics statistics = g_state->client.GetStatistics();
Line line;
line << "cemuextend: sent " << statistics.requestsSent << " received "
<< statistics.responsesReceived << " events " << statistics.eventsReceived
<< " overflows " << statistics.queueOverflows << " bytes " << statistics.bytesCopied;
Log(line);
}
} // namespace
bool Initialize(const HostInterface& host) {
if (g_state)
return g_state->initialized;
if (!host.acquire || !host.findExport || !host.monotonicTimeNs)
return false;
g_state = new State();
g_state->host = host;
if (!guest::ConfigureTrustedCafePlatform(host.acquire, host.findExport,
host.monotonicTimeNs)) {
// Cemu without CemuExtend, or a build whose CEX2 module is missing.
// The mod is still loaded and the game still runs; it just has no host
// to talk to, which is exactly what a mod should do about it.
Log("cemuextend: CEX2 transport unavailable, running detached");
return false;
}
const wire::Error error = g_state->client.Initialize();
if (error != wire::Error::Ok) {
Line line;
line << "cemuextend: client initialize failed: " << ErrorName(error);
Log(line);
return false;
}
// Core events tell us when the service list changes or the host is going
// away. Subscribing is optional; not subscribing simply means Pump()
// delivers nothing but responses.
const wire::Error subscribed = g_state->client.Subscribe(
wire::ServiceId::Core, [](std::uint16_t operation, std::span<const std::byte>) {
switch (static_cast<wire::CoreEvent>(operation)) {
case wire::CoreEvent::ServicesChanged:
Log("cemuextend: host service list changed");
break;
case wire::CoreEvent::Closing:
Log("cemuextend: host is closing the connection");
break;
default:
break;
}
});
if (subscribed != wire::Error::Ok) {
Line line;
line << "cemuextend: core subscribe failed: " << ErrorName(subscribed);
Log(line);
}
g_state->initialized = true;
Log("cemuextend: connected");
Announce();
return true;
}
void Tick() {
if (!g_state || !g_state->initialized)
return;
// Pump() runs completion callbacks, so the stage may advance inside it.
g_state->client.Pump();
if (!g_state->client.IsConnected() && g_state->stage != Stage::Failed) {
Log("cemuextend: disconnected");
g_state->stage = Stage::Failed;
return;
}
if (g_state->stage == Stage::Idle && ++g_state->ticks >= kStatisticsInterval) {
g_state->ticks = 0;
ReportStatistics();
}
}
void Shutdown() {
if (!g_state)
return;
if (g_state->initialized) {
(void)g_state->client.Unsubscribe(wire::ServiceId::Core);
g_state->client.Shutdown();
Log("cemuextend: shut down");
}
delete g_state;
g_state = nullptr;
}
bool IsInitialized() { return g_state && g_state->initialized; }
} // namespace cemod_example