-
-
Notifications
You must be signed in to change notification settings - Fork 170
/
apt.c
1490 lines (1255 loc) · 36.7 KB
/
apt.c
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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
apt.c _ Applet/NS shell interaction
*/
#include <stdlib.h>
#include <string.h>
#include <3ds/types.h>
#include <3ds/result.h>
#include <3ds/svc.h>
#include <3ds/srv.h>
#include <3ds/synchronization.h>
#include <3ds/services/apt.h>
#include <3ds/services/gspgpu.h>
#include <3ds/services/ptmsysm.h> // for PtmWakeEvents
#include <3ds/allocator/mappable.h>
#include <3ds/ipc.h>
#include <3ds/env.h>
#include <3ds/thread.h>
#include <3ds/os.h>
#define APT_HANDLER_STACKSIZE (0x1000)
static int aptRefCount = 0;
static Handle aptLockHandle;
static Handle aptEvents[2];
static LightEvent aptReceiveEvent;
static LightEvent aptSleepEvent;
static Thread aptEventHandlerThread;
static bool aptEventHandlerThreadQuit;
static aptHookCookie aptFirstHook;
static aptMessageCb aptMessageFunc;
static void* aptMessageFuncData;
enum
{
// Current applet state
FLAG_ACTIVE = BIT(0),
FLAG_SLEEPING = BIT(1),
// Sleep handling flags
FLAG_ALLOWSLEEP = BIT(2),
FLAG_SHOULDSLEEP = BIT(3),
// Home button flags
FLAG_ALLOWHOME = BIT(4),
FLAG_SHOULDHOME = BIT(5),
FLAG_HOMEREJECTED = BIT(6),
// Power button flags
FLAG_POWERBUTTON = BIT(7),
FLAG_SHUTDOWN = BIT(8),
// Close handling flags
FLAG_ORDERTOCLOSE = BIT(9),
FLAG_CANCELLED = BIT(10),
// Miscellaneous
FLAG_DSPWAKEUP = BIT(29),
FLAG_CHAINLOAD = BIT(30),
FLAG_SPURIOUS = BIT(31),
};
static u8 aptHomeButtonState;
static u32 aptFlags;
static u32 aptParameters[0x1000/4];
static u64 aptChainloadTid;
static u8 aptChainloadDeliverArg[0x300];
static u32 aptChainloadDeliverArgSize = sizeof(aptChainloadDeliverArg);
static u8 aptChainloadHmac[0x20];
static u8 aptChainloadMediatype;
static u8 aptChainloadFlags;
typedef enum
{
TR_ENABLE = 0x62,
TR_JUMPTOMENU = 0x0E,
TR_SYSAPPLET = 0x05,
TR_LIBAPPLET = 0x04,
TR_CANCELLIB = 0x03,
TR_CLOSEAPP = 0x09,
TR_APPJUMP = 0x12,
} APT_Transition;
static void aptEventHandler(void *arg);
static APT_Command aptWaitForWakeUp(APT_Transition transition);
// The following function can be overridden in order to log APT signals and notifications for debugging purposes
#ifdef LIBCTRU_APT_DEBUG
__attribute__((weak)) void _aptDebug(int a, int b) { }
#else
#define _aptDebug(a,b) ((void)0)
#endif
// APT<->DSP interaction functions (stubbed when not using DSP)
__attribute__((weak)) bool aptDspSleep(void) { return false; }
__attribute__((weak)) void aptDspWakeup(void) { }
__attribute__((weak)) void aptDspCancel(void) { }
static void aptCallHook(APT_HookType hookType)
{
aptHookCookie* c;
for (c = &aptFirstHook; c && c->callback; c = c->next)
c->callback(hookType, c->param);
}
static bool aptIsReinit(void)
{
return (envGetSystemRunFlags() & RUNFLAG_APTREINIT) != 0;
}
static bool aptIsChainload(void)
{
return (envGetSystemRunFlags() & RUNFLAG_APTCHAINLOAD) != 0;
}
static bool aptIsCrippled(void)
{
u32 flags = envGetSystemRunFlags();
return (flags & RUNFLAG_APTWORKAROUND) && !(flags & RUNFLAG_APTREINIT);
}
static Result aptGetServiceHandle(Handle* aptuHandle)
{
static const char* serviceName;
static const char* const serviceNameTable[3] = {"APT:S", "APT:A", "APT:U"};
if (serviceName)
return srvGetServiceHandleDirect(aptuHandle, serviceName);
Result ret;
int i;
for (i = 0; i < 3; i ++)
{
ret = srvGetServiceHandleDirect(aptuHandle, serviceNameTable[i]);
if (R_SUCCEEDED(ret))
{
serviceName = serviceNameTable[i];
break;
}
}
return ret;
}
static inline int countPrmWords(u32 hdr)
{
return 1 + (hdr&0x3F) + ((hdr>>6)&0x3F);
}
Result aptSendCommand(u32* aptcmdbuf)
{
Handle aptuHandle;
if (aptLockHandle) svcWaitSynchronization(aptLockHandle, U64_MAX);
Result res = aptGetServiceHandle(&aptuHandle);
if (R_SUCCEEDED(res))
{
u32* cmdbuf = getThreadCommandBuffer();
memcpy(cmdbuf, aptcmdbuf, 4*countPrmWords(aptcmdbuf[0]));
res = svcSendSyncRequest(aptuHandle);
if (R_SUCCEEDED(res))
{
memcpy(aptcmdbuf, cmdbuf, 4*countPrmWords(cmdbuf[0]));
res = aptcmdbuf[1];
}
svcCloseHandle(aptuHandle);
}
if (aptLockHandle) svcReleaseMutex(aptLockHandle);
return res;
}
static void aptInitCaptureInfo(aptCaptureBufInfo* capinfo, const GSPGPU_CaptureInfo* gspcapinfo)
{
// Fill in display-capture info for NS.
capinfo->is3D = (gspcapinfo->screencapture[0].format & 0x20) != 0;
capinfo->top.format = gspcapinfo->screencapture[0].format & 0x7;
capinfo->bottom.format = gspcapinfo->screencapture[1].format & 0x7;
u32 main_pixsz = gspGetBytesPerPixel((GSPGPU_FramebufferFormat)capinfo->top.format);
u32 sub_pixsz = gspGetBytesPerPixel((GSPGPU_FramebufferFormat)capinfo->bottom.format);
capinfo->bottom.leftOffset = 0;
capinfo->bottom.rightOffset = 0;
capinfo->top.leftOffset = sub_pixsz * 0x14000;
capinfo->top.rightOffset = capinfo->top.leftOffset;
if (capinfo->is3D)
capinfo->top.rightOffset += main_pixsz * 0x19000;
capinfo->size = main_pixsz * 0x7000 + main_pixsz * 0x19000 + capinfo->top.rightOffset;
}
Result aptInit(void)
{
Result ret=0;
if (AtomicPostIncrement(&aptRefCount)) return 0;
// Retrieve APT lock
ret = APT_GetLockHandle(0x0, &aptLockHandle);
if (R_FAILED(ret)) goto _fail;
if (aptIsCrippled()) return 0;
// Initialize APT
APT_AppletAttr attr = aptMakeAppletAttr(APTPOS_APP, false, false);
ret = APT_Initialize(envGetAptAppId(), attr, &aptEvents[0], &aptEvents[1]);
if (R_FAILED(ret)) goto _fail2;
// Initialize light events
LightEvent_Init(&aptReceiveEvent, RESET_STICKY);
LightEvent_Init(&aptSleepEvent, RESET_ONESHOT);
// Create APT event handler thread
aptEventHandlerThreadQuit = false;
aptEventHandlerThread = threadCreate(aptEventHandler, 0x0, APT_HANDLER_STACKSIZE, 0x31, -2, true);
if (!aptEventHandlerThread) goto _fail3;
// By default allow sleep mode and home button presses
aptFlags = FLAG_ALLOWSLEEP;
if (osGetSystemCoreVersion() == 2) // ... except in safe mode, which doesn't have home menu running
aptFlags |= FLAG_ALLOWHOME;
// Enable APT
ret = APT_Enable(attr);
if (R_FAILED(ret)) goto _fail3;
// If the homebrew environment requires it, chainload-to-self by default
if (aptIsChainload())
aptSetChainloaderToSelf();
// Wait for wakeup
aptWaitForWakeUp(TR_ENABLE);
// Special handling for aptReinit (aka hax 2.x):
// In certain cases when running under hax 2.x, we may receive a spurious
// second wakeup command. Therefore we must silently drop it in order to
// avoid keeping stale commands in APT's internal buffer.
if (aptIsReinit())
aptFlags |= FLAG_SPURIOUS;
return 0;
_fail3:
svcCloseHandle(aptEvents[0]);
svcCloseHandle(aptEvents[1]);
_fail2:
svcCloseHandle(aptLockHandle);
_fail:
AtomicDecrement(&aptRefCount);
return ret;
}
bool aptIsActive(void)
{
return (aptFlags & FLAG_ACTIVE) != 0;
}
bool aptShouldClose(void)
{
return (aptFlags & (FLAG_ORDERTOCLOSE|FLAG_CANCELLED)) != 0;
}
bool aptIsSleepAllowed(void)
{
return (aptFlags & FLAG_ALLOWSLEEP) != 0;
}
void aptSetSleepAllowed(bool allowed)
{
bool cur = aptIsSleepAllowed();
if (allowed && !cur)
{
aptFlags |= FLAG_ALLOWSLEEP;
APT_SleepIfShellClosed();
}
else if (!allowed && cur)
{
aptFlags &= ~FLAG_ALLOWSLEEP;
APT_ReplySleepQuery(envGetAptAppId(), APTREPLY_REJECT);
}
}
bool aptIsHomeAllowed(void)
{
return (aptFlags & FLAG_ALLOWHOME) != 0;
}
void aptSetHomeAllowed(bool allowed)
{
if (allowed)
aptFlags |= FLAG_ALLOWHOME;
else
aptFlags &= ~FLAG_ALLOWHOME;
}
bool aptShouldJumpToHome(void)
{
return aptHomeButtonState || (aptFlags & (FLAG_SHOULDHOME|FLAG_POWERBUTTON)) != 0;
}
bool aptCheckHomePressRejected(void)
{
if (aptFlags & FLAG_HOMEREJECTED)
{
aptFlags &= ~FLAG_HOMEREJECTED;
return true;
}
return false;
}
static void aptClearJumpToHome(void)
{
aptHomeButtonState = 0;
APT_UnlockTransition(0x01);
APT_SleepIfShellClosed();
}
void aptClearChainloader(void)
{
aptFlags &= ~FLAG_CHAINLOAD;
aptChainloadDeliverArgSize = sizeof(aptChainloadDeliverArg);
memset(aptChainloadDeliverArg, 0, sizeof(aptChainloadDeliverArg));
memset(aptChainloadHmac, 0, sizeof(aptChainloadHmac));
}
void aptSetChainloader(u64 programID, u8 mediatype)
{
aptFlags |= FLAG_CHAINLOAD;
aptChainloadFlags = 0;
aptChainloadTid = programID;
aptChainloadMediatype = mediatype;
}
void aptSetChainloaderToCaller(void)
{
aptFlags |= FLAG_CHAINLOAD;
aptChainloadFlags = 1;
aptChainloadTid = 0;
aptChainloadMediatype = 0;
}
void aptSetChainloaderToSelf(void)
{
aptFlags |= FLAG_CHAINLOAD;
aptChainloadFlags = 2;
aptChainloadTid = 0;
aptChainloadMediatype = 0;
}
void aptSetChainloaderArgs(const void *deliverArg, size_t deliverArgSize, const void *hmac)
{
if (deliverArgSize >= sizeof(aptChainloadDeliverArg))
deliverArgSize = sizeof(aptChainloadDeliverArg);
aptChainloadDeliverArgSize = deliverArgSize;
memcpy(aptChainloadDeliverArg, deliverArg, deliverArgSize);
if (hmac != NULL)
memcpy(aptChainloadHmac, hmac, sizeof(aptChainloadHmac));
else
memset(aptChainloadHmac, 0, sizeof(aptChainloadHmac));
}
extern void (*__system_retAddr)(void);
static void aptExitProcess(void)
{
APT_CloseApplication(NULL, 0, 0);
}
void aptExit(void)
{
if (AtomicDecrement(&aptRefCount)) return;
bool closeAptLock = true;
bool doDirtyChainload = false;
if (!aptIsCrippled())
{
bool doClose;
if (aptShouldClose())
{
// The system instructed us to close, so do just that
aptCallHook(APTHOOK_ONEXIT);
doClose = true;
}
else if (aptIsReinit())
{
// The homebrew environment expects APT to be reinitializable, so unregister ourselves without closing
APT_Finalize(envGetAptAppId());
doClose = false;
}
else if (aptFlags & FLAG_CHAINLOAD)
{
// A chainload target is configured, so perform a jump to it
// Doing this requires help from HOME menu, so ensure that it is running
bool hmRegistered;
if (R_SUCCEEDED(APT_IsRegistered(aptGetMenuAppID(), &hmRegistered)) && hmRegistered)
{
// Normal, sane chainload
APT_PrepareToDoApplicationJump(aptChainloadFlags, aptChainloadTid, aptChainloadMediatype);
APT_DoApplicationJump(aptChainloadDeliverArg, aptChainloadDeliverArgSize, aptChainloadHmac);
}
else
{
// XX: HOME menu doesn't exist, so we need to use a workaround provided by Luma3DS
APT_Finalize(envGetAptAppId());
doDirtyChainload = true;
}
// After a chainload has been applied, we don't need to manually close
doClose = false;
__system_retAddr = NULL;
}
else
{
// None of the other situations apply, so close anyway by default
doClose = true;
}
// If needed, perform the APT application closing sequence
if (doClose)
{
APT_PrepareToCloseApplication(true);
// APT_CloseApplication kills us if we aren't signed up for srv closing notifications, so
// defer APT_CloseApplication for as long as possible (TODO: actually use srv notif instead)
__system_retAddr = aptExitProcess;
closeAptLock = false;
srvInit(); // Keep srv initialized
}
aptEventHandlerThreadQuit = true;
svcSignalEvent(aptEvents[0]);
threadJoin(aptEventHandlerThread, U64_MAX);
int i;
for (i = 0; i < 2; i ++)
svcCloseHandle(aptEvents[i]);
}
if (closeAptLock)
svcCloseHandle(aptLockHandle);
if (doDirtyChainload)
{
// Provided by Luma3DS
Handle notificationHandle = 0;
Result res = 0;
u32 notificationNumber = 0;
srvEnableNotification(¬ificationHandle);
// Not needed, but official (sysmodule) code does this:
srvSubscribe(0x100);
// Make PM modify our run flags and ask us to terminate
srvPublishToSubscriber(0x3000, 0);
do
{
// Bail out after 3 seconds, we don't want to wait forever for this
res = svcWaitSynchronization(notificationHandle, 3 * 1000 * 1000LL);
res = res == 0 ? srvReceiveNotification(¬ificationNumber) : res;
} while(res == 0 && notificationNumber != 0x100);
svcCloseHandle(notificationHandle);
}
}
void aptEventHandler(void *arg)
{
while (!aptEventHandlerThreadQuit)
{
s32 id = 0;
svcWaitSynchronizationN(&id, aptEvents, 2, 0, U64_MAX);
if (aptEventHandlerThreadQuit)
break;
// If the receive event is still signaled, sleep for a bit and retry
if (LightEvent_TryWait(&aptReceiveEvent))
{
_aptDebug(222, 0);
svcSleepThread(10000000); // 10ms
svcSignalEvent(aptEvents[id]);
continue;
}
// This is done by official sw, even though APT events are oneshot...
svcClearEvent(aptEvents[id]);
// Relay receive events to our light event
if (id == 1)
{
NS_APPID sender;
APT_Command cmd;
Result res = APT_GlanceParameter(envGetAptAppId(), aptParameters, sizeof(aptParameters), &sender, &cmd, NULL, NULL);
if (R_FAILED(res))
continue; // Official sw panics here - we instead swallow the (non-)event.
_aptDebug(2, cmd); _aptDebug(22, sender);
// NOTE: Official software handles the following parameter types here:
// - APTCMD_MESSAGE (cancelled afterwards) (we handle it in aptReceiveParameter instead)
// - APTCMD_REQUEST (cancelled afterwards) (only sent to and handled by libapplets?)
// - APTCMD_DSP_SLEEP (*NOT* cancelled afterwards)
// - APTCMD_DSP_WAKEUP (*NOT* cancelled afterwards)
// We will handle the following:
switch (cmd)
{
case APTCMD_DSP_SLEEP:
// Handle DSP sleep requests
aptDspSleep();
break;
case APTCMD_DSP_WAKEUP:
// Handle DSP wakeup requests
aptFlags &= ~FLAG_DSPWAKEUP;
aptDspWakeup();
break;
case APTCMD_WAKEUP_PAUSE:
// Handle spurious APTCMD_WAKEUP_PAUSE parameters
// (see aptInit for more details on the hax 2.x spurious wakeup problem)
if (aptFlags & FLAG_SPURIOUS)
{
APT_CancelParameter(APPID_NONE, envGetAptAppId(), NULL);
aptFlags &= ~FLAG_SPURIOUS;
break;
}
// Fallthrough otherwise
default:
// Others not accounted for -> pass it on to aptReceiveParameter
LightEvent_Signal(&aptReceiveEvent);
break;
}
continue;
}
APT_Signal signal;
Result res = APT_InquireNotification(envGetAptAppId(), &signal);
if (R_FAILED(res))
continue;
_aptDebug(1, signal);
switch (signal)
{
case APTSIGNAL_HOMEBUTTON:
case APTSIGNAL_HOMEBUTTON2:
if (!aptIsActive())
break;
else if (!aptIsHomeAllowed())
{
aptFlags |= FLAG_HOMEREJECTED;
aptClearJumpToHome();
}
else if (!aptHomeButtonState)
aptHomeButtonState = signal == APTSIGNAL_HOMEBUTTON ? 1 : 2;
break;
case APTSIGNAL_SLEEP_QUERY:
{
APT_QueryReply reply;
if (aptShouldClose())
// Reject sleep if we are expected to close
reply = APTREPLY_REJECT;
else if (aptIsActive())
// Accept sleep based on user setting if we are active
reply = aptIsSleepAllowed() ? APTREPLY_ACCEPT : APTREPLY_REJECT;
else
// Accept sleep if we are inactive regardless of user setting
reply = APTREPLY_ACCEPT;
_aptDebug(10, aptFlags);
_aptDebug(11, reply);
APT_ReplySleepQuery(envGetAptAppId(), reply);
break;
}
case APTSIGNAL_SLEEP_CANCEL:
if (aptIsActive())
aptFlags &= ~FLAG_SHOULDSLEEP;
break;
case APTSIGNAL_SLEEP_ENTER:
_aptDebug(10, aptFlags);
if (aptDspSleep())
aptFlags |= FLAG_DSPWAKEUP;
if (aptIsActive())
aptFlags |= FLAG_SHOULDSLEEP;
else
// Since we are not active, this must be handled here.
APT_ReplySleepNotificationComplete(envGetAptAppId());
break;
case APTSIGNAL_SLEEP_WAKEUP:
if (aptFlags & FLAG_DSPWAKEUP)
{
aptFlags &= ~FLAG_DSPWAKEUP;
aptDspWakeup();
}
if (!aptIsActive())
break;
if (aptFlags & FLAG_SLEEPING)
LightEvent_Signal(&aptSleepEvent);
else
aptFlags &= ~FLAG_SHOULDSLEEP;
break;
case APTSIGNAL_SHUTDOWN:
aptFlags |= FLAG_ORDERTOCLOSE | FLAG_SHUTDOWN;
break;
case APTSIGNAL_POWERBUTTON:
aptFlags |= FLAG_POWERBUTTON;
break;
case APTSIGNAL_POWERBUTTON2:
aptFlags &= ~FLAG_POWERBUTTON;
break;
case APTSIGNAL_TRY_SLEEP:
{
// Official software performs this APT_SleepSystem command here, although
// its purpose is unclear. For completeness' sake, we'll do it as well.
static const struct PtmWakeEvents s_sleepWakeEvents = {
.pdn_wake_events = 0,
.mcu_interupt_mask = BIT(6),
};
APT_SleepSystem(&s_sleepWakeEvents);
break;
}
case APTSIGNAL_ORDERTOCLOSE:
aptFlags |= FLAG_ORDERTOCLOSE;
break;
default:
break;
}
}
}
static Result aptReceiveParameter(APT_Command* cmd, size_t* actualSize, Handle* handle)
{
NS_APPID sender;
size_t temp_actualSize;
if (!actualSize) actualSize = &temp_actualSize;
LightEvent_Wait(&aptReceiveEvent);
LightEvent_Clear(&aptReceiveEvent);
Result res = APT_ReceiveParameter(envGetAptAppId(), aptParameters, sizeof(aptParameters), &sender, cmd, actualSize, handle);
if (R_SUCCEEDED(res) && *cmd == APTCMD_MESSAGE && aptMessageFunc)
aptMessageFunc(aptMessageFuncData, sender, aptParameters, *actualSize);
return res;
}
APT_Command aptWaitForWakeUp(APT_Transition transition)
{
APT_Command cmd;
APT_NotifyToWait(envGetAptAppId());
aptFlags &= ~FLAG_ACTIVE;
if (transition != TR_ENABLE)
APT_SleepIfShellClosed();
for (;;)
{
Result res = aptReceiveParameter(&cmd, NULL, NULL);
if (R_SUCCEEDED(res)
&& (cmd==APTCMD_WAKEUP || cmd==APTCMD_WAKEUP_PAUSE || cmd==APTCMD_WAKEUP_EXIT || cmd==APTCMD_WAKEUP_CANCEL
|| cmd==APTCMD_WAKEUP_CANCELALL || cmd==APTCMD_WAKEUP_POWERBUTTON || cmd==APTCMD_WAKEUP_JUMPTOHOME
|| cmd==APTCMD_WAKEUP_LAUNCHAPP)) break;
}
aptFlags |= FLAG_ACTIVE;
void __ctru_speedup_config();
__ctru_speedup_config();
if (transition != TR_CANCELLIB && cmd != APTCMD_WAKEUP_CANCEL && cmd != APTCMD_WAKEUP)
{
GSPGPU_AcquireRight(0);
GSPGPU_RestoreVramSysArea();
aptCallHook(APTHOOK_ONRESTORE);
}
if (cmd == APTCMD_WAKEUP_CANCEL || cmd == APTCMD_WAKEUP_CANCELALL)
{
aptDspCancel();
if (cmd == APTCMD_WAKEUP_CANCEL) // for some reason, not for CANCELALL... is this a bug in official sw?
aptFlags |= FLAG_CANCELLED;
} else if (cmd != APTCMD_WAKEUP_LAUNCHAPP)
{
aptFlags &= ~FLAG_DSPWAKEUP;
aptDspWakeup();
}
if (cmd != APTCMD_WAKEUP_JUMPTOHOME)
{
APT_UnlockTransition(0x10);
APT_SleepIfShellClosed();
} else
{
aptFlags |= FLAG_SHOULDHOME;
aptHomeButtonState = 1;
APT_LockTransition(0x01, true);
}
if (transition == TR_JUMPTOMENU || transition == TR_LIBAPPLET || transition == TR_SYSAPPLET || transition == TR_APPJUMP)
{
if (cmd != APTCMD_WAKEUP_JUMPTOHOME)
aptClearJumpToHome();
}
return cmd;
}
static void aptConvertScreenForCapture(void* dst, const void* src, u32 height, GSPGPU_FramebufferFormat format)
{
const u32 width = 240;
const u32 width_po2 = 1U << (32 - __builtin_clz(width-1)); // next_po2(240) = 256
const u32 bpp = gspGetBytesPerPixel(format);
const u32 tilesize = 8*8*bpp;
// Terrible conversion code that is also probably really slow
u8* out = (u8*)dst;
const u8* in = (u8*)src;
for (u32 tiley = 0; tiley < height; tiley += 8)
{
u32 tilex = 0;
for (tilex = 0; tilex < width; tilex += 8)
{
for (u32 y = 0; y < 8; y ++)
{
for (u32 x = 0; x < 8; x ++)
{
static const u8 morton_x[] = { 0x00, 0x01, 0x04, 0x05, 0x10, 0x11, 0x14, 0x15 };
static const u8 morton_y[] = { 0x00, 0x02, 0x08, 0x0a, 0x20, 0x22, 0x28, 0x2a };
unsigned inoff = bpp*(width*(tiley+y)+(tilex+x));
unsigned outoff = bpp*(morton_x[x] + morton_y[y]);
for (u32 c = 0; c < bpp; c ++)
out[outoff+c] = in[inoff+c];
}
}
out += tilesize;
}
for (; tilex < width_po2; tilex += 8)
out += tilesize;
}
}
static void aptScreenTransfer(NS_APPID appId, bool sysApplet)
{
// Retrieve display capture info from GSP
GSPGPU_CaptureInfo gspcapinfo = {0};
GSPGPU_ImportDisplayCaptureInfo(&gspcapinfo);
// Wait for the target applet to be registered
for (;;)
{
bool tmp;
Result res = APT_IsRegistered(appId, &tmp);
if (R_SUCCEEDED(res) && tmp) break;
svcSleepThread(10000000);
}
// Calculate the layout/size of the capture memory block
aptCaptureBufInfo capinfo;
aptInitCaptureInfo(&capinfo, &gspcapinfo);
// Request the capture memory block to be allocated
for (;;)
{
Result res = APT_SendParameter(envGetAptAppId(), appId, sysApplet ? APTCMD_SYSAPPLET_REQUEST : APTCMD_REQUEST, &capinfo, sizeof(capinfo), 0);
if (R_SUCCEEDED(res)) break;
svcSleepThread(10000000);
}
// Receive the response from APT
Handle hCapMemBlk = 0;
for (;;)
{
APT_Command cmd;
Result res = aptReceiveParameter(&cmd, NULL, &hCapMemBlk);
if (R_SUCCEEDED(res) && cmd==APTCMD_RESPONSE)
break;
}
// For library applets, we need to manually do the capture ourselves
// (this involves mapping the memory block and doing the conversion)
if (!sysApplet)
{
void* map = mappableAlloc(capinfo.size);
if (map)
{
Result res = svcMapMemoryBlock(hCapMemBlk, (u32)map, MEMPERM_READWRITE, MEMPERM_READWRITE);
if (R_SUCCEEDED(res))
{
aptConvertScreenForCapture( // Bottom screen
(u8*)map + capinfo.bottom.leftOffset,
gspcapinfo.screencapture[1].framebuf0_vaddr,
320, (GSPGPU_FramebufferFormat)capinfo.bottom.format);
aptConvertScreenForCapture( // Top screen (Left eye)
(u8*)map + capinfo.top.leftOffset,
gspcapinfo.screencapture[0].framebuf0_vaddr,
400, (GSPGPU_FramebufferFormat)capinfo.top.format);
if (capinfo.is3D)
aptConvertScreenForCapture( // Top screen (Right eye)
(u8*)map + capinfo.top.rightOffset,
gspcapinfo.screencapture[0].framebuf1_vaddr,
400, (GSPGPU_FramebufferFormat)capinfo.top.format);
svcUnmapMemoryBlock(hCapMemBlk, (u32)map);
}
mappableFree(map);
}
}
// Close the capture memory block handle
if (hCapMemBlk)
svcCloseHandle(hCapMemBlk);
// Send capture buffer information back to APT
APT_SendCaptureBufferInfo(&capinfo);
}
void aptJumpToHomeMenu(void)
{
bool sleep = aptIsSleepAllowed();
aptSetSleepAllowed(false);
aptFlags &= ~(FLAG_SHOULDHOME|FLAG_SPURIOUS); // If we haven't received a spurious wakeup by now, we probably never will (see aptInit)
APT_PrepareToJumpToHomeMenu();
aptCallHook(APTHOOK_ONSUSPEND);
GSPGPU_SaveVramSysArea();
aptScreenTransfer(aptGetMenuAppID(), true);
aptDspSleep();
GSPGPU_ReleaseRight();
APT_JumpToHomeMenu(NULL, 0, 0);
aptFlags &= ~FLAG_ACTIVE;
aptWaitForWakeUp(TR_JUMPTOMENU);
aptSetSleepAllowed(sleep);
}
void aptHandleSleep(void)
{
if (!(aptFlags & FLAG_SHOULDSLEEP))
return;
aptFlags = (aptFlags &~ FLAG_SHOULDSLEEP) | FLAG_SLEEPING;
aptCallHook(APTHOOK_ONSLEEP);
APT_ReplySleepNotificationComplete(envGetAptAppId());
LightEvent_Wait(&aptSleepEvent);
aptFlags &= ~FLAG_SLEEPING;
if (aptIsActive())
GSPGPU_SetLcdForceBlack(0);
aptCallHook(APTHOOK_ONWAKEUP);
}
bool aptMainLoop(void)
{
aptHandleSleep();
aptHandleJumpToHome();
return !aptShouldClose();
}
void aptHook(aptHookCookie* cookie, aptHookFn callback, void* param)
{
if (!callback) return;
aptHookCookie* hook = &aptFirstHook;
*cookie = *hook; // Structure copy.
hook->next = cookie;
hook->callback = callback;
hook->param = param;
}
void aptUnhook(aptHookCookie* cookie)
{
aptHookCookie* hook;
for (hook = &aptFirstHook; hook; hook = hook->next)
{
if (hook->next == cookie)
{
*hook = *cookie; // Structure copy.
break;
}
}
}
void aptSetMessageCallback(aptMessageCb callback, void* user)
{
aptMessageFunc = callback;
aptMessageFuncData = user;
}
void aptLaunchLibraryApplet(NS_APPID appId, void* buf, size_t bufsize, Handle handle)
{
bool sleep = aptIsSleepAllowed();
aptSetSleepAllowed(false);
aptFlags &= ~FLAG_SPURIOUS; // If we haven't received a spurious wakeup by now, we probably never will (see aptInit)
APT_PrepareToStartLibraryApplet(appId);
aptSetSleepAllowed(sleep);
aptCallHook(APTHOOK_ONSUSPEND);
GSPGPU_SaveVramSysArea();
aptScreenTransfer(appId, false);
GSPGPU_ReleaseRight();
aptSetSleepAllowed(false);
APT_StartLibraryApplet(appId, buf, bufsize, handle);
aptFlags &= ~FLAG_ACTIVE;
aptWaitForWakeUp(TR_LIBAPPLET);
memcpy(buf, aptParameters, bufsize);
aptSetSleepAllowed(sleep);
}
Result APT_GetLockHandle(u16 flags, Handle* lockHandle)
{
u32 cmdbuf[16];
cmdbuf[0]=IPC_MakeHeader(0x1,1,0); // 0x10040
cmdbuf[1]=flags;
Result ret = aptSendCommand(cmdbuf);
if (R_SUCCEEDED(ret))
*lockHandle = cmdbuf[5];
return ret;
}
Result APT_Initialize(NS_APPID appId, APT_AppletAttr attr, Handle* signalEvent, Handle* resumeEvent)
{
u32 cmdbuf[16];
cmdbuf[0]=IPC_MakeHeader(0x2,2,0); // 0x20080
cmdbuf[1]=appId;
cmdbuf[2]=attr;
Result ret = aptSendCommand(cmdbuf);
if (R_SUCCEEDED(ret))
{
if(signalEvent) *signalEvent=cmdbuf[3];
if(resumeEvent) *resumeEvent=cmdbuf[4];
}
return ret;
}
Result APT_Finalize(NS_APPID appId)
{
u32 cmdbuf[16];
cmdbuf[0]=IPC_MakeHeader(0x4,1,0); // 0x40040
cmdbuf[1]=appId;
return aptSendCommand(cmdbuf);
}
Result APT_HardwareResetAsync(void)
{
u32 cmdbuf[16];
cmdbuf[0]=IPC_MakeHeader(0x4E,0,0); // 0x4E0000
return aptSendCommand(cmdbuf);
}
Result APT_Enable(APT_AppletAttr attr)
{
u32 cmdbuf[16];
cmdbuf[0]=IPC_MakeHeader(0x3,1,0); // 0x30040
cmdbuf[1]=attr;
return aptSendCommand(cmdbuf);
}
Result APT_GetAppletManInfo(APT_AppletPos inpos, APT_AppletPos* outpos, NS_APPID* req_appid, NS_APPID* menu_appid, NS_APPID* active_appid)
{
u32 cmdbuf[16];
cmdbuf[0]=IPC_MakeHeader(0x5,1,0); // 0x50040
cmdbuf[1]=inpos;
Result ret = aptSendCommand(cmdbuf);
if (R_SUCCEEDED(ret))
{
if (outpos) *outpos =cmdbuf[2];
if (req_appid) *req_appid =cmdbuf[3];
if (menu_appid) *menu_appid =cmdbuf[4];
if (active_appid) *active_appid=cmdbuf[5];
}
return ret;
}
Result APT_GetAppletInfo(NS_APPID appID, u64* pProgramID, u8* pMediaType, bool* pRegistered, bool* pLoadState, APT_AppletAttr* pAttributes)
{
u32 cmdbuf[16];
cmdbuf[0]=IPC_MakeHeader(0x6,1,0); // 0x60040
cmdbuf[1]=appID;
Result ret = aptSendCommand(cmdbuf);
if (R_SUCCEEDED(ret))
{
if (pProgramID) *pProgramID =(u64)cmdbuf[2]|((u64)cmdbuf[3]<<32);
if (pMediaType) *pMediaType =cmdbuf[4];
if (pRegistered) *pRegistered=cmdbuf[5] & 0xFF;
if (pLoadState) *pLoadState =cmdbuf[6] & 0xFF;
if (pAttributes) *pAttributes=cmdbuf[7];
}