-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrecovery_export.txt
More file actions
3055 lines (2614 loc) · 121 KB
/
Copy pathrecovery_export.txt
File metadata and controls
3055 lines (2614 loc) · 121 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
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
======================================================================
FILE: common/include/toob_swap_event_wire.h
======================================================================
/**
* @file toob_swap_event_wire.h
* @brief Neutral OS <-> Core mailbox wire format (single source of truth).
*
* Contains only the memory structures and notifications layout, allowing it to
* be included from both the bootloader core and libtoob/OS side without dependencies.
* Adheres to standard C17 and embeds size and layout checks.
*/
#ifndef TOOB_SWAP_EVENT_WIRE_H
#define TOOB_SWAP_EVENT_WIRE_H
#include <stdint.h>
#include <stddef.h>
#define TOOB_SWAP_EVENT_ABI_VERSION 1U
/* ============================================================================
* COMPILE-TIME FEATURE GATES (SWEV-T2)
* Supports dynamic configuration via device.toml [driver_config].
* ============================================================================ */
/* Map driver compiler prefix overrides if they exist */
#ifdef TOOB_DRIVER_SWAP_EVENT_STATE
#define TOOB_SWAP_EVENT_STATE TOOB_DRIVER_SWAP_EVENT_STATE
#endif
#ifdef TOOB_DRIVER_SWAP_EVENT_PROGRESS
#define TOOB_SWAP_EVENT_PROGRESS TOOB_DRIVER_SWAP_EVENT_PROGRESS
#endif
#ifdef TOOB_DRIVER_SWAP_EVENT_PHASE
#define TOOB_SWAP_EVENT_PHASE TOOB_DRIVER_SWAP_EVENT_PHASE
#endif
/* Fallback default definitions if not configured */
#ifndef TOOB_SWAP_EVENT_STATE
#define TOOB_SWAP_EVENT_STATE 1 /* 1: State change notifications (PREPARE, DONE, etc.) enabled */
#endif
#ifndef TOOB_SWAP_EVENT_PROGRESS
#define TOOB_SWAP_EVENT_PROGRESS 1 /* 1: Detailed sectors done/total progress tracking enabled */
#endif
#ifndef TOOB_SWAP_EVENT_PHASE
#define TOOB_SWAP_EVENT_PHASE 0 /* 1: Sub-phases (e.g., RESUMED) enabled */
#endif
/* ============================================================================
* SWAP LIFECYCLE PHASES
* ============================================================================ */
typedef enum {
TOOB_SWAP_PHASE_PREPARE = 0, /* OS is running and prepping for reboot (Level A) */
TOOB_SWAP_PHASE_SWAPPING = 1, /* Stage 1 is in active flash swap execution (Level B) */
TOOB_SWAP_PHASE_DONE = 2, /* Swap has been successfully completed */
TOOB_SWAP_PHASE_RESUMED = 3, /* Swap process resumed after power loss / interruption */
TOOB_SWAP_PHASE_RECOVERY = 4 /* Recovery OS has boot notification context (Level C) */
} toob_swap_phase_t;
/**
* @brief Versioned progress / swap notification event.
* Stable 16-byte layout to prevent compiler padding or drift between OS and Core builds.
*/
typedef struct {
uint16_t abi_version; /* Layout version marker (TOOB_SWAP_EVENT_ABI_VERSION) */
uint16_t phase; /* toob_swap_phase_t value */
uint32_t sectors_done; /* Done count (always 0 if PROGRESS feature is compiled out) */
uint32_t sectors_total; /* Total count (always 0 if PROGRESS feature is compiled out) */
uint32_t flags; /* Future expansion / specific state flags */
} toob_swap_event_t;
_Static_assert(sizeof(toob_swap_event_t) == 16, "toob_swap_event_t must be exactly 16 bytes");
_Static_assert(offsetof(toob_swap_event_t, phase) == 2, "phase offset drift");
_Static_assert(offsetof(toob_swap_event_t, sectors_done) == 4, "sectors_done offset drift");
_Static_assert(offsetof(toob_swap_event_t, sectors_total) == 8, "sectors_total offset drift");
_Static_assert(offsetof(toob_swap_event_t, flags) == 12, "flags offset drift");
/**
* @brief Manufacturer notification function contract.
* Contract: MUST be non-blocking (< 1ms execution budget) and fail-safe.
*/
typedef void (*toob_swap_notify_fn)(const toob_swap_event_t *ev);
#endif /* TOOB_SWAP_EVENT_WIRE_H */
======================================================================
FILE: common/include/toob_mailbox_wire.h
======================================================================
/**
* @file toob_mailbox_wire.h
* @brief Neutral OS <-> Core mailbox wire format (single source of truth).
*
* Contains ONLY the on-flash record and geometry contract — no status type, no
* function declarations — so it can be included from both sides without dragging
* in libtoob_types.h (OS) or boot_types.h (Core). Pure C17, no C++ linkage block
* needed (data only).
*
* Two-sector A/B: TOOB_MAILBOX_SLOTS independent erase sectors, one record each.
* The writer targets the stale slot and erases only that sector; the reader takes
* the valid slot with the highest `seq`. See toob_mailbox.c (writer) and
* boot_mailbox.c (reader).
*/
#ifndef TOOB_MAILBOX_WIRE_H
#define TOOB_MAILBOX_WIRE_H
#include <stdint.h>
#include <stddef.h>
/* 'TMBX' little-endian */
#define TOOB_MAILBOX_MAGIC 0x58424D54U
#define TOOB_MAILBOX_VERSION 1U
#define TOOB_MAILBOX_SLOTS 2U
typedef enum {
TOOB_REQ_NONE = 0,
TOOB_REQ_UPDATE_PENDING = 1, /* tbm1_addr = flat-package address */
TOOB_REQ_CONFIRM = 2, /* nonce = boot_nonce being confirmed */
TOOB_REQ_RECOVERY_RESOLVED = 3
} toob_req_t;
/**
* @brief One mailbox record. Fixed little-endian wire format, 32 bytes.
* `nonce` is naturally 8-aligned. CRC-32 covers [0 .. offsetof(crc32));
* `_reserved` is excluded and MUST be zero.
*/
typedef struct __attribute__((packed, aligned(8))) {
uint32_t magic; /* 0 : TOOB_MAILBOX_MAGIC */
uint16_t version; /* 4 : TOOB_MAILBOX_VERSION */
uint16_t request; /* 6 : toob_req_t */
uint32_t seq; /* 8 : monotonic; Core consumes iff seq > last_consumed */
uint32_t tbm1_addr; /* 12 : UPDATE_PENDING flat-package address (else 0) */
uint64_t nonce; /* 16 : CONFIRM boot_nonce (else 0) */
uint32_t crc32; /* 24 : CRC-32 over [0 .. 24) */
uint32_t _reserved; /* 28 : must be 0 */
} toob_mailbox_t; /* 32 bytes */
_Static_assert(sizeof(toob_mailbox_t) == 32, "toob_mailbox_t must be exactly 32 bytes");
_Static_assert(offsetof(toob_mailbox_t, crc32) == 24, "crc32 offset drift");
_Static_assert(offsetof(toob_mailbox_t, nonce) == 16, "nonce must be 8-byte aligned");
/* CRC-covered prefix length (one definition for writer and reader). */
#define TOOB_MAILBOX_CRC_LEN offsetof(toob_mailbox_t, crc32)
#endif /* TOOB_MAILBOX_WIRE_H */
======================================================================
FILE: sdk/libtoob/include/libtoob.h
======================================================================
/**
* ==============================================================================
* Toob-Boot C-Interface (libtoob.h)
* ==============================================================================
*
* REFERENCED SPECIFICATIONS:
* - docs/libtoob_api.md (API definitions, toob_status_t, .noinit references)
* - docs/concept_fusion.md (Strict isolation policy, State Machine interactions)
* - docs/structure_plan.md (Strict isolation from core/ headers)
* - docs/testing_requirements.md (P10 compliance & Interface definition standards)
*
* This is the EXCLUSIVE OS-side API for Toob-Boot interaction.
* Es spannt den C++ kompatiblen Schutzschirm (extern "C") für externe Feature-OS.
*
* ==============================================================================
* ERROR HANDLING MATRIX & OS CONTRACTS (L1 / Mailbox Policy)
* ==============================================================================
* Die Funktionen toob_confirm_boot(), toob_recovery_resolved(),
* und toob_set_next_update() schreiben Mailbox-Anfragen in den Flash.
* Diese Operationen können spezifische Fehlercodes zurückgeben:
*
* | Fehlercode | Ursache | Erwartete OS-Reaktion |
* |----------------------------|--------------------------------------|--------------------------------|
* | TOOB_ERR_FLASH / FLASH_HW | Hardwarefehler im Flash-Treiber. | Fehler protokollieren. |
*/
#ifndef LIBTOOB_H
#define LIBTOOB_H
/*
* ARCHITEKTUR-GRUND: System-Header MÜSSEN vor dem `extern "C"` Block geladen
* werden, da eingebaute C++ Systembibliotheken bei geschachteltem `extern "C"`
* crashen können.
*/
#include <stdint.h>
#include <stdbool.h>
#include <stddef.h>
#include "libtoob_types.h"
#include "toob_swap_event_wire.h"
#ifdef __cplusplus
extern "C" {
#endif
/* ==============================================================================
* P10 Compliance & Symmetrie Validierungen
* ============================================================================== */
/* GAP-39: Strict 8-Byte Formatierung für Boundaries */
_Static_assert(sizeof(toob_handoff_t) % 8 == 0, "GAP-39: toob_handoff_t size must align to 8 bytes.");
_Static_assert(sizeof(toob_boot_diag_t) % 8 == 0, "GAP-39: toob_boot_diag_t size must align to 8 bytes.");
/* Host-Compiler Symmetrie Check */
#ifndef TOOB_NOINIT
#error "FATAL: Host-Compiler lacks TOOB_NOINIT support. Must provide fallback for .noinit section mapping."
#endif
/* ==============================================================================
* Handoff Verification Guard
* ==============================================================================
* Das `.noinit` RAM enthält illegitimate Garbage-Werte, wenn das OS durch den
* Watchdog abgewürgt wird, ohne dass Toob-Boot involviert war. Das Lesen der
* ungeschützten Boot-Variablen OHNE vorherige CRC-32 Validation riskiert Boot-Loop Crashes!
*/
/**
* @brief Validiert die Integrität der .noinit Toob-Boot Boundary (GAP-Handoff).
* @return TOOB_OK bei validem Magic/CRC-32, TOOB_ERR_VERIFY bei Fehler.
*/
TOOB_MUST_CHECK toob_status_t toob_validate_handoff(void);
/**
* @brief Liefert eine sichere, verifizierte "By-Value"-Kopie der Handoff-Daten.
*
* @note [Opaque validating accessor pattern]
* Dies ist der einzige legitime und unterstützte Zugriffspfad für das OS,
* um an Boot-Handoff-Daten zu gelangen. Direkter Zugriff auf die uninitialisierte
* RAM-Variable (toob_handoff_state) ist gesperrt, um zu verhindern, dass das
* Betriebssystem korrupten RAM-Zustand liest. Die Funktion verifiziert Magic,
* ABI-Strukturversion und CRC32 vor dem Kopieren. Bei Validierungsfehler
* wird der Zielpuffer defensiv genullt und TOOB_ERR_VERIFY zurückgegeben.
*
* @param out_handoff Pointer auf eine vom OS allozierte Ausgabestruktur.
* @return TOOB_OK bei Erfolg, TOOB_ERR_VERIFY wenn die Validierung fehlschlägt, TOOB_ERR_INVALID_ARG bei NULL.
*/
TOOB_MUST_CHECK toob_status_t toob_get_handoff(toob_handoff_t* out_handoff);
/**
* @brief P10 Absicherungsmakro zur ausfallsicheren OS-Initialisierung.
*
* Validates the .noinit handoff from Toob-Boot. On corruption, enters an
* infinite TOOB_TRAP() loop — by design, this halts the system immediately
* to prevent propagation of corrupted boot state into the OS.
*
* @warning Fail-Closed by Design. This macro NEVER RETURNS on failure.
* On systems with a Hardware Watchdog (WDT), the trap loop triggers
* a WDT reset within the configured timeout. On systems WITHOUT a
* WDT, the trap loop hangs PERMANENTLY — the device is bricked until
* a physical power cycle.
* Systems without WDT should use toob_os_init() instead and implement
* their own recovery strategy based on the returned status code.
*
* @note Must be called as the very first statement in main()/app_main().
*/
#define TOOB_OS_INIT_OR_PANIC() \
do { \
if (toob_validate_handoff() != TOOB_OK) { \
while (true) { TOOB_TRAP(); } \
} \
} while (false)
/**
* @brief Non-panicking OS initialization — validates the .noinit handoff.
*
* Unlike TOOB_OS_INIT_OR_PANIC(), this function returns the validation
* result instead of trapping. The caller decides the recovery strategy:
* logging, rebooting, entering a safe mode, etc.
*
* @return TOOB_OK if the handoff is valid and the OS may proceed.
* TOOB_ERR_VERIFY if the .noinit region is corrupted — the OS
* MUST NOT call any other toob_* function in this case.
*/
static inline TOOB_MUST_CHECK toob_status_t toob_os_init(void) {
return toob_validate_handoff();
}
/**
* @brief Prüft, ob der Rückgabewert einer WAL-Operation einen System-Reboot erfordert.
* @param status Rückgabewert einer libtoob-Funktion.
* @return true wenn ein Reboot erforderlich ist, andernfalls false.
*/
#define TOOB_IS_REBOOT_REQUIRED(status) \
(((status) == TOOB_ERR_REQUIRES_RESET) || ((status) == TOOB_ERR_WAL_FULL))
/* ==============================================================================
* Primary Feature-OS API (IDE-UX & Doxygen Mappings)
* ============================================================================== */
/**
* @brief Bestätigt das asynchrone OTA-Update (Commit Flag).
*
* @note [GAP-07: Network Watchdog TTL]
* Das Feature-OS MUSS diese Funktion rufen, um ein laufendes Update
* als erfolgreich zu flaggen. Nutzt das Update ein Cloud-Handshake
* (z.B. DICE/CDI), MUSS das OS zwingend die Cloud-Bestätigung abwarten.
* Dafür sammelt das OS "Network-TTL" Minuten via WAL. Bei Überschreiten
* dieses TTLs führt das Ausbleiben des Aufrufs unwiderruflich zum Rollback.
*
* @return TOOB_OK bei Erfolg.
* @return TOOB_OK bei Erfolg.
* Mögliche Fehler:
* - TOOB_ERR_FLASH / TOOB_ERR_FLASH_HW: Flash-Hardwarefehler.
*/
TOOB_MUST_CHECK toob_status_t toob_confirm_boot(void);
/**
* @brief Befreit das Recovery-OS aus dem Rettungsmodus (Anti Roach-Motel).
* @note Sobald das Recovery-OS die App repariert hat, MUSS es diese Funktion
* aufrufen, um den RECOVERY_RESOLVED Intent in die Mailbox zu schreiben.
*
* @return TOOB_OK bei Erfolg.
* Mögliche Fehler:
* - TOOB_ERR_FLASH / TOOB_ERR_FLASH_HW: Flash-Hardwarefehler.
*/
TOOB_MUST_CHECK toob_status_t toob_recovery_resolved(void);
/* ==============================================================================
* Zero-Bloat Platform & Cryptography Hooks (must precede OTA context definition)
* ============================================================================== */
#include "toob_port.h"
/* ==============================================================================
* Toob-Boot OTA Daemon (Network-Agnostic Stream Writer)
* ============================================================================== */
/* OTA alignment buffer size — must match CHIP_FLASH_WRITE_ALIGNMENT multiples */
#define TOOB_OTA_BUF_SIZE 256U
/**
* @brief OTA Session Context (caller-allocated, zero dynamic allocation).
*
* Encapsulates the complete state of a single OTA transfer session. The caller
* allocates this struct (stack or static) and passes it to all toob_ota_*
* functions. This enables re-entrant, testable OTA sessions without globals.
*
* Must be initialized with toob_ota_ctx_init() before first use.
*/
typedef struct __attribute__((aligned(8))) {
uint8_t state; /* Internal state machine (opaque) */
uint8_t is_verified; /* SHA-256 stream verification active */
uint8_t _reserved[2]; /* Alignment padding */
uint32_t write_cursor; /* Absolute flash address of next write */
uint32_t total_size; /* Declared image size from manifest */
uint32_t bytes_queued; /* Bytes received so far */
uint32_t buf_len; /* Bytes currently in alignment buffer */
uint8_t align_buf[TOOB_OTA_BUF_SIZE]; /* DMA-safe flash write buffer */
uint8_t expected_sha256[32];/* Expected hash for verified streams */
toob_os_sha256_ctx_t sha_ctx; /* Streaming SHA-256 context */
} toob_ota_ctx_t;
_Static_assert(sizeof(toob_ota_ctx_t) == 440, "toob_ota_ctx_t ABI size drift");
/**
* @brief Registers a manufacturer-supplied notifier callback for update progress events.
* @param cb Manufacturer callback function pointer (NULL to disable).
*/
void toob_set_swap_notifier(toob_swap_notify_fn cb);
/**
* @brief Initializes a toob_ota_ctx_t to a clean idle state.
* Must be called once before first use. Securely zeroes all fields.
* @param ctx Caller-allocated context.
* @return TOOB_OK on success, TOOB_ERR_INVALID_ARG if ctx is NULL.
*/
TOOB_MUST_CHECK toob_status_t toob_ota_ctx_init(toob_ota_ctx_t *ctx);
/**
* @brief Initializes the OTA Daemon for receiving a new update stream.
* @param ctx Caller-allocated OTA session context.
* @param total_size Expected total size of the incoming image (Manifest + Payload).
* @param expected_sha256 Optional 32-byte hash to verify the stream against (nullable).
* @return TOOB_OK on success, TOOB_ERR_INVALID_ARG if size exceeds staging slot.
*/
TOOB_MUST_CHECK toob_status_t toob_ota_begin(toob_ota_ctx_t *ctx, uint32_t total_size, const uint8_t expected_sha256[32]);
/**
* @brief Resumes a partially downloaded OTA update.
*
* Restores the internal write cursor and byte counter from the handoff RAM
* checkpoint. If expected_sha256 is non-NULL, reconstructs the SHA-256
* streaming context by re-reading and re-hashing the already-staged flash prefix.
*
* @param ctx Caller-allocated OTA session context.
* @param total_size Expected total size of the image (from the manifest).
* @param expected_sha256 Optional 32-byte hash to verify the stream against (nullable).
* @param resume_offset Output pointer for the byte offset to resume from.
* @return TOOB_OK if resumable, TOOB_ERR_NOT_FOUND if no partial download exists.
*/
TOOB_MUST_CHECK toob_status_t toob_ota_resume(toob_ota_ctx_t *ctx, uint32_t total_size, const uint8_t expected_sha256[32], uint32_t* resume_offset);
/**
* @brief Aborts an active OTA download and securely zeroizes buffers.
* @param ctx OTA session context to abort.
* @return TOOB_OK.
*/
TOOB_MUST_CHECK toob_status_t toob_ota_abort(toob_ota_ctx_t *ctx);
/**
* @brief Processes a chunk of incoming bytes, writing them linearly to Staging.
* @param ctx OTA session context.
* @param chunk Pointer to the downloaded bytes.
* @param len Length of the chunk.
* @return TOOB_OK, or TOOB_ERR_FLASH on write error.
*/
TOOB_MUST_CHECK toob_status_t toob_ota_process_chunk(toob_ota_ctx_t *ctx, const uint8_t* chunk, uint32_t len);
/**
* @brief Finalizes the OTA process and registers the update intent in the WAL.
*
* After all chunks have been received and the stream transitions to DONE,
* this function flushes residual bytes, verifies the SHA-256 digest (if
* verified mode), and atomically writes the update intent into the WAL.
*
* @param ctx OTA session context.
* @return TOOB_OK on success. The system should be rebooted immediately after.
* TOOB_ERR_VERIFY — SHA-256 mismatch (stream corrupted, re-download required).
* TOOB_ERR_FLASH — Flash write failed during residual flush.
* TOOB_ERR_WAL_LOCKED — A previous update is already pending in the WAL.
* The OS must reboot to consume it before staging a new one.
* TOOB_ERR_WAL_FULL — WAL sector exhausted. Reboot required.
* TOOB_ERR_INVALID_ARG — Context is NULL or not in DONE state.
*/
TOOB_MUST_CHECK toob_status_t toob_ota_finalize(toob_ota_ctx_t *ctx);
/**
* @brief Registriert ein empfangenes Manifest in der Mailbox.
*
* @note [L1: Mailbox-Atomarität]
* Ein Crash (Brownout) während der Ausführung dieser Funktion hinterlässt
* niemals einen halben Zustand. Das System evaluiert CRC-gesicherte Mailbox-Einträge
* beim nächsten Boot und faltet sie in seine interne WAL ein.
*
* @param manifest_flash_addr Absolute, hardware-bündige Flash-Adresse des Manifests im SPI.
* @return TOOB_OK bei Erfolg.
* Mögliche Fehler:
* - TOOB_ERR_FLASH / TOOB_ERR_FLASH_HW: Flash-Hardwarefehler.
*/
TOOB_MUST_CHECK toob_status_t toob_set_next_update(uint32_t manifest_flash_addr);
/**
* @brief Extrahiert die rohen Hardware-Metriken aus dem .noinit RAM.
*
* @note [CRA Regulatorik & CBOR Extraktion]
* Liest die `toob_boot_diag_t` Struktur. Diese enthält u.A. den
* kryptographischen SHA-256 Digest der SBOM, was direkt der Erfüllung
* des EU Cyber Resilience Acts 2027 (CRA) dient. Die weiterführende
* Telemetrie zur Hardware-Lebensdauer ist optional via CBOR verpackt.
*
* @param diag Zeiger auf die vom OS bereitgestellte Struct-Instanz.
* @return TOOB_OK bei Erfolg, TOOB_ERR_VERIFY bei gebrochener Checksumme.
*/
TOOB_MUST_CHECK toob_status_t toob_get_boot_diag(toob_boot_diag_t* diag);
/**
* @brief Extrahiert die Diagnosedaten kodiert im Cloud-tauglichen CBOR-Format.
* @param out_buf Buffer für den CBOR-Stream
* @param max_len Maximale Größe von out_buf
* @param out_len Tatsächliche Größe des geschriebenen CBOR-Streams
* @return TOOB_OK bei Erfolg
*/
TOOB_MUST_CHECK toob_status_t toob_get_boot_diag_cbor(uint8_t* out_buf, size_t max_len, size_t* out_len);
/* ==============================================================================
* Cloud-Command Submission API (Phase 7)
* ==============================================================================
* Das OS empfängt Cloud-Command Envelopes (CBOR, Ed25519-signiert) vom Server
* und delegiert sie über dieses API an den Bootloader. Der Bootloader evaluiert
* den Command beim nächsten Boot (Step 2.5 in boot_state.c).
*/
/**
* @brief Schreibt ein Cloud-Command-Envelope in den CHIP_CLOUD_CMD_SLOT.
*
* Sequenz: Guard → Erase → Write → CRC Read-Back → Zeroize.
* Der Bootloader evaluiert den Slot beim nächsten Boot autonom.
*
* @param envelope Zeiger auf das rohe CBOR-Envelope (inkl. Signatur).
* @param len Länge des Envelopes in Bytes.
* @return TOOB_OK bei Erfolg, TOOB_ERR_INVALID_ARG bei NULL/Überlänge,
* TOOB_ERR_FLASH bei Erase/Write-Fehler,
* TOOB_ERR_FLASH_HW bei Read-Back-Mismatch.
*/
TOOB_MUST_CHECK toob_status_t toob_submit_cloud_command(const uint8_t *envelope, uint32_t len);
/**
* @brief Extrahiert die 32-Byte DICE Device-ID aus dem Boot-Handoff.
*
* @note [Validating Accessor Reference Pattern]
* Diese Funktion dient als Referenz-Muster für den sicheren, gekapselten
* Zugriff auf spezifische Handoff-Felder. Sie holt sich den Handoff-State
* validiert über toob_get_handoff(), liest die ID aus und löscht den temporären
* Stack-Buffer anschließend sicher mittels toob_secure_zeroize().
*
* @param out_id Ziel-Buffer (mind. 32 Bytes).
* @param id_len Größe des Buffers. Muss >= 32 sein.
* @return TOOB_OK bei Erfolg, TOOB_ERR_INVALID_ARG bei NULL oder zu kleinem Buffer,
* TOOB_ERR_VERIFY bei korruptem Handoff.
*/
TOOB_MUST_CHECK toob_status_t toob_get_device_id(uint8_t *out_id, size_t id_len);
/* ==============================================================================
* Der Hard-Linker Contract "Zero-Bloat Shim"
* ==============================================================================
* Toob-Loader verweigert die Kopplung an ausufernde Vendor-SDK SPI Treiber.
* Um dem Bootloader dennoch persistente WAL-Transktionen (`toob_set_next_update`)
* zu ermöglichen, fordert die Library exakt diese beiden Symbole als harten Linker-Contract ein.
* Das Feature-OS (z.B. der Zephyr OS Storage API Stack) MUSS diese in seinem C/C++ Code
* zwingend physikalisch bereitstellen! Ein Fehlen führt absichtlich zu einem
* "Undefined Symbol" Kompilierungsabbruch (Fail-Fast).
*/
/**
* @brief Zero-Bloat Hook: Physikalischer Flash-Lesezugriff.
* @param addr Absolute Byte-Adresse im SPI Flash.
* @param buf Datenpuffer im lokalen OS-SRAM.
* @param len Länge der zu lesenden Daten.
* @return TOOB_OK bei Erfolg. Bei Hardware-Fehler zwingend TOOB_ERR_FLASH!
*/
TOOB_MUST_CHECK toob_status_t toob_os_flash_read(uint32_t addr, uint8_t* buf, uint32_t len);
/**
* @brief Zero-Bloat Hook: Physikalischer Flash-Schreibzugriff.
* @param addr Absolute Byte-Adresse im SPI Flash (Muss an Page-Boundary ausgerichtet sein).
* @param buf Zu schreibender, konstanter Datenpuffer.
* @param len Länge der zu schreibenden Daten.
* @return TOOB_OK bei Erfolg. Bei Hardware-Fehler zwingend TOOB_ERR_FLASH!
*/
TOOB_MUST_CHECK toob_status_t toob_os_flash_write(uint32_t addr, const uint8_t* buf, uint32_t len);
/**
* @brief Zero-Bloat Hook: Physikalischer Flash-Löschzugriff.
* @param addr Absolute Byte-Adresse im SPI Flash (Muss Sektor-bündig sein).
* @param len Länge der zu löschenden Daten (Muss Sektor-bündig sein).
* @return TOOB_OK bei Erfolg. Bei Hardware-Fehler zwingend TOOB_ERR_FLASH!
*/
TOOB_MUST_CHECK toob_status_t toob_os_flash_erase(uint32_t addr, uint32_t len);
#ifdef __cplusplus
}
#endif
#endif /* LIBTOOB_H */
======================================================================
FILE: sdk/libtoob/include/libtoob_types.h
======================================================================
/*
* Toob-Boot OS Boundary Types (libtoob_types.h)
*
* Diese Datei definiert die mathematisch strikt ausgerichteten Datenstrukturen
* und Konstanten, durch die das Feature-OS mit dem Toob-Boot Bootloader
* kommuniziert (Zero-Allocation Boundary, .noinit Handoff).
*
* Relevante Spezifikationen:
* - docs/libtoob_api.md: Definition der toob_handoff_t OS-Boundary & RAM Section.
* - docs/toob_telemetry.md: CBOR Diagnostic Structs (toob_boot_diag_t).
* - docs/concept_fusion.md: TENTATIVE/COMMITTED State-Machine Logik.
*/
#ifndef LIBTOOB_TYPES_H
#define LIBTOOB_TYPES_H
#include <stdint.h>
#include <stdbool.h>
#include <stddef.h>
/* ========================================================
* 0. Cross-Compiler Utilities
* ======================================================== */
/* Forces callers to check toob_status_t returns at compile time. */
#if defined(__GNUC__) || defined(__clang__)
# define TOOB_MUST_CHECK __attribute__((warn_unused_result))
#elif defined(__ICCARM__)
# define TOOB_MUST_CHECK _Pragma("diag_error=Pe940")
#elif defined(__CC_ARM) || defined(__ARMCC_VERSION)
# define TOOB_MUST_CHECK __attribute__((warn_unused_result))
#else
# define TOOB_MUST_CHECK
#endif
/* ========================================================
* 1. Status & Boot States
* ======================================================== */
/* GAP-06: Spezifische libtoob Fehlercodes für sauberes OS-Handling */
typedef enum {
TOOB_OK = 0x55AA55AA,
TOOB_ERR_NOT_FOUND = 0xE1101CAE, /* Abstandskorrekte Hamming-Hex Werte */
TOOB_ERR_WAL_FULL = 0xE2201CAE,
TOOB_ERR_WAL_LOCKED = 0xE3301CAE,
TOOB_ERR_FLASH = 0xE4401CAE,
TOOB_ERR_INVALID_ARG= 0xE5501CAE,
TOOB_ERR_VERIFY = 0xE6601CAE, /* RAM Korruption / CRC-32 Mismatch */
TOOB_ERR_REQUIRES_RESET = 0xE7701CAE, /* Fataler WAL Lock (Reset zwingend) */
TOOB_ERR_COUNTER_EXHAUSTED = 0xE8801CAE,
TOOB_ERR_FLASH_HW = 0xE9901CAE,
TOOB_ERR_STATE = 0xEAA01CAE, /* GAP-N03: Invalid State/Initialization */
TOOB_ERR_TIMEOUT = 0xEBB01CAE, /* GAP-N03: Network/Operation Timeout */
TOOB_ERR_NOT_SUPPORTED = 0xECC01CAE /* GAP-N03: Feature not implemented */
} toob_status_t;
/* Partition Layout für boot_target Auswertung */
typedef enum {
TOOB_PARTITION_APP = 0x0000000A,
TOOB_PARTITION_RECOVERY = 0x0000000B
} toob_partition_t;
/* Reset-Gründe (Isoliert von der boot_types.h um Zero-Dependency zu wahren) */
/* HINWEIS: Numeric Mapping muss strikt identisch zur internen reset_reason_t sein! */
typedef enum {
TOOB_RESET_UNKNOWN = 0,
TOOB_RESET_POWER_ON = 1,
TOOB_RESET_PIN = 2,
TOOB_RESET_WATCHDOG = 3,
TOOB_RESET_BROWNOUT = 4,
TOOB_RESET_SOFTWARE = 5,
TOOB_RESET_HARD_FAULT = 6
} toob_reset_reason_t;
/* GAP-12: Explizite Boot-State Konstanten für TENTATIVE/COMMITTED Logik */
#define TOOB_STATE_TENTATIVE 0xAAAA5555
#define TOOB_STATE_COMMITTED 0x55AA55AA
/* ========================================================
* 2. OS Interface (.noinit Handoff)
* ======================================================== */
/* GAP-39: Zwingendes 8-Byte Alignment für 64-bit Architektur-Kompatibilität (z.B. AArch64) */
typedef struct __attribute__((aligned(8))) {
uint32_t magic; /* Immer 0x55AA55AA */
uint32_t struct_version; /* GAP-11: ABI Versionierung (z.B. 0x01000000) für Abwärtskompatibilität */
uint64_t boot_nonce; /* Deterministische Anti-Replay Nonce */
uint32_t booted_partition; /* toob_partition_t (0x0A = App Slot A, 0x0B = Recovery OS) */
uint32_t reset_reason; /* Letzter Hardware-Reset-Grund (toob_reset_reason_t) */
uint32_t boot_failure_count; /* Aktueller Stand des Edge-Recovery Counters */
uint32_t net_search_accum_ms;/* Anti-Lagerhaus Netz-Suchzeit Akkumulator */
uint32_t resume_offset; /* Partielle Download Resume-Stelle (aus WAL Checkpoint) */
uint8_t device_id[32]; /* P10: Unique DICE Device Identity for Cloud Sync */
uint8_t wipe_requested; /* OS Instruction to wipe user partitions */
uint8_t _padding[7]; /* P10: 8-Byte Alignment Padding */
uint32_t crc32_trailer; /* Kryptographische Versiegelung in .noinit durch S1 */
} toob_handoff_t;
/* Mathematische Perfektion: Compile-Time Checks (P10) */
_Static_assert(sizeof(toob_handoff_t) == 80, "toob_handoff_t size breach - must be exactly 80 bytes");
_Static_assert(sizeof(toob_handoff_t) % 8 == 0, "toob_handoff_t alignment breach - must be 8-byte aligned");
_Static_assert(offsetof(toob_handoff_t, crc32_trailer) == 76, "crc32_trailer ABI offset drift detected");
/* ========================================================
* Handoff ABI Layout Static Asserts (P10)
* ======================================================== */
_Static_assert(offsetof(toob_handoff_t, magic) == 0, "magic offset drift");
_Static_assert(offsetof(toob_handoff_t, struct_version) == 4, "struct_version offset drift");
_Static_assert(offsetof(toob_handoff_t, boot_nonce) == 8, "boot_nonce offset drift");
_Static_assert(offsetof(toob_handoff_t, booted_partition) == 16, "booted_partition offset drift");
_Static_assert(offsetof(toob_handoff_t, reset_reason) == 20, "reset_reason offset drift");
_Static_assert(offsetof(toob_handoff_t, boot_failure_count) == 24, "boot_failure_count offset drift");
_Static_assert(offsetof(toob_handoff_t, net_search_accum_ms) == 28, "net_search_accum_ms offset drift");
_Static_assert(offsetof(toob_handoff_t, resume_offset) == 32, "resume_offset offset drift");
_Static_assert(offsetof(toob_handoff_t, device_id) == 36, "device_id offset drift");
_Static_assert(offsetof(toob_handoff_t, wipe_requested) == 68, "wipe_requested offset drift");
_Static_assert(offsetof(toob_handoff_t, _padding) == 69, "_padding offset drift");
_Static_assert(offsetof(toob_handoff_t, crc32_trailer) == 76, "crc32_trailer offset drift");
/* Konstante für struct_version des Handoff-Headers zur Vermeidung von ABI-Drift */
#define TOOB_HANDOFF_STRUCT_VERSION 0x02000000
/*
* Cross-Compiler Abstraktion für die ".noinit" Linker-Section.
* Da libtoob OS-seitig eingebunden wird, müssen wir verschiedene Compiler tolerieren.
*/
#if defined(__GNUC__) || defined(__clang__) || defined(__ICCARM__)
#define TOOB_NOINIT __attribute__((section(".noinit")))
#define TOOB_TRAP() __builtin_trap()
#elif defined(__CC_ARM) || defined(__ARMCC_VERSION) /* ARM Compiler (Keil) */
/*
* WARNING: .bss.noinit is fragile! Keil requires a dedicated Execution
* Region with the `UNINIT` attribute in the scatter file (.sct),
* otherwise the C-Runtime WILL zeroize it!
*/
#define TOOB_NOINIT __attribute__((section(".bss.noinit")))
#define TOOB_TRAP() __breakpoint(0)
#else
#warning "Compiler not officially supported by libtoob. Defaulting to GCC syntax."
#define TOOB_NOINIT __attribute__((section(".noinit")))
#define TOOB_TRAP() do { volatile int* p = 0; *p = 0; } while(0)
#endif
/* ========================================================
* 3. Telemetrie & Health Diagnostik (CBOR Extraction)
* ======================================================== */
/* Health & Wear Data (Sub-Struct für Verschleißdaten) */
typedef struct {
uint32_t wal_erase_count; /* Sliding Window Pointer */
uint32_t app_slot_erase_count; /* App Image Verschleiß */
uint32_t staging_slot_erase_count; /* Staging Image Verschleiß */
uint32_t swap_buffer_erase_count; /* In-Place Swap Buffer Verschleiß */
} toob_ext_health_t;
/*
* Strukturierte Boot-Diagnostik für OS CBOR Extraction
* Harmonisiert GAP-F29 & GAP-16 mit toob_telemetry.md
*/
typedef struct __attribute__((aligned(8))) {
uint32_t struct_version; /* Abwärtskompatibler Header */
/* Systemwerte */
uint32_t boot_duration_ms; /* Gesamtdauer Start (boot_time_ms) */
uint32_t verify_time_ms; /* Zeit für Krypto-Hashes */
/* Fehler-State */
uint32_t last_error_code; /* z.B. BOOT_ERR_WDT_TRIGGER */
uint32_t vendor_error; /* Spezifischer Flash-Fehler */
uint32_t hardware_fault_record; /* Hardware-Fault register dump */
/* Identity & Revisions */
uint32_t active_key_index; /* eFuse Epoch Index */
uint32_t current_svn; /* Aktuelle SVN Version */
uint32_t build_number; /* CI build number */
/* Protection & Crash History */
uint32_t edge_recovery_events; /* Aktuelle Edge-Recovery Versuche (boot_failure_count) */
uint32_t wdt_kicks; /* Watchdog Kick Counter */
/* Telemetry / Version Oracle (v2) */
uint16_t fw_ver_major; /* Firmware version */
uint16_t fw_ver_minor;
uint16_t fw_ver_patch;
uint8_t fallback_occurred; /* 1 = recovery booted, 0 = normal */
uint8_t _reserved_diag[1]; /* Alignment padding to 4-byte boundary */
/* SBOM & Handoff */
uint32_t boot_session_id; /* Monotoner Boot-Counter */
uint8_t sbom_digest[32]; /* SHA-256 der letzten Stückliste (deterministisch 32 Bytes) */
/* Extended Health (Optional gem. CBOR Spec) */
uint8_t ext_health_present; /* P10: Explicit uint8_t statt bool für ABI Sicherheit */
uint8_t _padding[3]; /* P10: Explizites Padding für exaktes 4-Byte Alignment vor der Sub-Struct */
toob_ext_health_t ext_health; /* Health & Wear Data */
uint32_t crc32_trailer; /* CRC32 Versiegelung im .noinit */
} toob_boot_diag_t;
_Static_assert(sizeof(toob_boot_diag_t) == 112, "toob_boot_diag_t size breach - must be exactly 112 bytes for ABI stability");
_Static_assert(offsetof(toob_boot_diag_t, ext_health) % 4 == 0, "toob_ext_health_t alignment is broken in diag struct");
_Static_assert(offsetof(toob_boot_diag_t, crc32_trailer) > offsetof(toob_boot_diag_t, ext_health), "CRC32 trailer must be last field");
/* ========================================================
* Diag ABI Layout Static Asserts (P10)
* ======================================================== */
_Static_assert(offsetof(toob_boot_diag_t, struct_version) == 0, "struct_version offset drift");
_Static_assert(offsetof(toob_boot_diag_t, boot_duration_ms) == 4, "boot_duration_ms offset drift");
_Static_assert(offsetof(toob_boot_diag_t, verify_time_ms) == 8, "verify_time_ms offset drift");
_Static_assert(offsetof(toob_boot_diag_t, last_error_code) == 12, "last_error_code offset drift");
_Static_assert(offsetof(toob_boot_diag_t, vendor_error) == 16, "vendor_error offset drift");
_Static_assert(offsetof(toob_boot_diag_t, hardware_fault_record) == 20, "hardware_fault_record offset drift");
_Static_assert(offsetof(toob_boot_diag_t, active_key_index) == 24, "active_key_index offset drift");
_Static_assert(offsetof(toob_boot_diag_t, current_svn) == 28, "current_svn offset drift");
_Static_assert(offsetof(toob_boot_diag_t, build_number) == 32, "build_number offset drift");
_Static_assert(offsetof(toob_boot_diag_t, edge_recovery_events) == 36, "edge_recovery_events offset drift");
_Static_assert(offsetof(toob_boot_diag_t, wdt_kicks) == 40, "wdt_kicks offset drift");
_Static_assert(offsetof(toob_boot_diag_t, fw_ver_major) == 44, "fw_ver_major offset drift");
_Static_assert(offsetof(toob_boot_diag_t, fw_ver_minor) == 46, "fw_ver_minor offset drift");
_Static_assert(offsetof(toob_boot_diag_t, fw_ver_patch) == 48, "fw_ver_patch offset drift");
_Static_assert(offsetof(toob_boot_diag_t, fallback_occurred) == 50, "fallback_occurred offset drift");
_Static_assert(offsetof(toob_boot_diag_t, boot_session_id) == 52, "boot_session_id offset drift");
_Static_assert(offsetof(toob_boot_diag_t, sbom_digest) == 56, "sbom_digest offset drift");
_Static_assert(offsetof(toob_boot_diag_t, ext_health_present) == 88, "ext_health_present offset drift");
_Static_assert(offsetof(toob_boot_diag_t, _padding) == 89, "_padding offset drift");
_Static_assert(offsetof(toob_boot_diag_t, ext_health) == 92, "ext_health offset drift");
_Static_assert(offsetof(toob_ext_health_t, wal_erase_count) == 0, "wal_erase_count offset drift");
_Static_assert(offsetof(toob_ext_health_t, app_slot_erase_count) == 4, "app_slot_erase_count offset drift");
_Static_assert(offsetof(toob_ext_health_t, staging_slot_erase_count) == 8, "staging_slot_erase_count offset drift");
_Static_assert(offsetof(toob_ext_health_t, swap_buffer_erase_count) == 12, "swap_buffer_erase_count offset drift");
_Static_assert(offsetof(toob_boot_diag_t, crc32_trailer) == 108, "crc32_trailer offset drift");
/* Konstante für struct_version des Diag-Headers zur Vermeidung von ABI-Drift */
#define TOOB_DIAG_STRUCT_VERSION 0x02000000
/* ========================================================
* 4. WAL (Write-Ahead-Log) Wire Format
* Shared definition lives in common/include/toob_wal_wire.h.
* ======================================================== */
#include "toob_wal_wire.h"
/* OTA Network Failsafe Timeout (Default: 5 Minutes) */
#ifndef TOOB_SMOKE_TEST_TIMEOUT_MS
#define TOOB_SMOKE_TEST_TIMEOUT_MS 300000
#endif
/* Extern Definitions (After structs are fully typed!) */
extern TOOB_NOINIT toob_boot_diag_t toob_diag_state;
#endif /* LIBTOOB_TYPES_H */
======================================================================
FILE: sdk/libtoob/include/toob_mailbox.h
======================================================================
/**
* @file toob_mailbox.h
* @brief OS -> Core Mailbox SDK writer interface (C17).
*
* Implements the OS-side API to send update registration, confirmation, and
* recovery resolution requests to the Core bootloader.
*
* Sharing contract: all wire structure and enum definitions are defined in
* toob_mailbox_wire.h to prevent structure layout and static assertion drift.
*/
#ifndef TOOB_MAILBOX_H
#define TOOB_MAILBOX_H
#include "libtoob_types.h" /* toob_status_t */
#include "toob_mailbox_wire.h"
#ifdef __cplusplus
extern "C" {
#endif
/* ===== OS-side writers (implemented in toob_mailbox.c) ===== */
toob_status_t toob_mailbox_set_update(uint32_t manifest_flash_addr);
toob_status_t toob_mailbox_set_confirm(uint64_t nonce);
toob_status_t toob_mailbox_set_recovery_resolved(void);
#ifdef __cplusplus
}
#endif
#endif /* TOOB_MAILBOX_H */
======================================================================
FILE: sdk/libtoob/toob_confirm.c
======================================================================
/**
* @file toob_confirm.c
* @brief Boot Confirmation — OS-side confirm/recovery intent via Mailbox.
*
* Implements toob_confirm_boot() and toob_recovery_resolved().
* Writes Mailbox records instead of WAL entries. The RTC fast-path
* remains for hardware with backup registers.
*/
#include "libtoob.h"
#ifdef TOOB_HOST_FUZZING
#include "libtoob_config_sandbox.h"
#else
#include "generated_boot_config.h"
#endif
#include "toob_internal.h"
#include <stddef.h>
#ifdef ADDR_CONFIRM_RTC_RAM
uint64_t mock_rtc_ram = 0;
#endif
toob_status_t toob_confirm_boot(void) {
toob_handoff_t handoff __attribute__((aligned(8)));
toob_secure_zeroize(&handoff, sizeof(handoff));
toob_status_t status = toob_get_handoff(&handoff);
volatile uint32_t get_shield_1 = 0, get_shield_2 = 0;
if (status == TOOB_OK)
get_shield_1 = TOOB_OK;
TOOB_GLITCH_DELAY();
if (get_shield_1 == TOOB_OK && status == TOOB_OK)
get_shield_2 = TOOB_OK;
if (get_shield_1 != TOOB_OK || get_shield_2 != TOOB_OK ||
get_shield_1 != get_shield_2) {
toob_secure_zeroize(&handoff, sizeof(handoff));
return (status != TOOB_OK) ? status : TOOB_ERR_VERIFY;
}
#ifdef ADDR_CONFIRM_RTC_RAM
/* RTC fast-path: write nonce to backup register + mailbox. */
volatile uint64_t *rtc_ptr = (volatile uint64_t *)ADDR_CONFIRM_RTC_RAM;
*rtc_ptr = handoff.boot_nonce;
#if defined(__GNUC__) || defined(__clang__)
__sync_synchronize();
#endif
uint64_t verified_nonce = *rtc_ptr;
volatile uint32_t rtc_shield_1 = 0, rtc_shield_2 = 0;
if (verified_nonce == handoff.boot_nonce)
rtc_shield_1 = TOOB_OK;
TOOB_GLITCH_DELAY();
if (rtc_shield_1 == TOOB_OK && verified_nonce == handoff.boot_nonce)
rtc_shield_2 = TOOB_OK;
/* Mailbox write (fire-and-forget alongside RTC). */
(void)toob_mailbox_set_confirm(handoff.boot_nonce);
toob_secure_zeroize(&handoff, sizeof(handoff));
if (rtc_shield_1 != TOOB_OK || rtc_shield_2 != TOOB_OK ||
rtc_shield_1 != rtc_shield_2) {
return TOOB_ERR_FLASH_HW;
}
return TOOB_OK;
#else
/* Mailbox-only path. */
toob_status_t mb_stat = toob_mailbox_set_confirm(handoff.boot_nonce);
volatile uint32_t mb_shield_1 = 0, mb_shield_2 = 0;
if (mb_stat == TOOB_OK)
mb_shield_1 = TOOB_OK;
TOOB_GLITCH_DELAY();
if (mb_shield_1 == TOOB_OK && mb_stat == TOOB_OK)
mb_shield_2 = TOOB_OK;
toob_secure_zeroize(&handoff, sizeof(handoff));
if (mb_shield_1 == TOOB_OK && mb_shield_2 == TOOB_OK &&
mb_shield_1 == mb_shield_2) {
return TOOB_OK;
}
return (mb_stat != TOOB_OK) ? mb_stat : TOOB_ERR_FLASH_HW;
#endif
}
toob_status_t toob_recovery_resolved(void) {
toob_status_t status = toob_mailbox_set_recovery_resolved();
volatile uint32_t shield_1 = 0, shield_2 = 0;
if (status == TOOB_OK)
shield_1 = TOOB_OK;
TOOB_GLITCH_DELAY();
if (shield_1 == TOOB_OK && status == TOOB_OK)
shield_2 = TOOB_OK;
if (shield_1 == TOOB_OK && shield_2 == TOOB_OK && shield_1 == shield_2)
return TOOB_OK;
return (status != TOOB_OK) ? status : TOOB_ERR_FLASH_HW;
}
======================================================================
FILE: sdk/libtoob/toob_mailbox.c
======================================================================
/**
* @file toob_mailbox.c
* @brief OS-side Mailbox writer (two-sector A/B, torn-write safe).
*
* Replaces the previous erase-both-then-write-slot-0 design, which defeated
* double-buffering: a torn write wiped the only surviving record and reset the
* sequence, causing the Core to silently ignore updates (seq <= last_consumed).
*
* This implementation writes only the STALE slot and erases only that slot's
* sector, so:
* - at every instant at least one slot holds a valid, complete record, and
* - `seq` is strictly monotonic across brownouts (it is derived from the
* surviving good slot, which a torn write never touches).
*
* The Core reader mirrors the slot scan below: read all slots, take the valid
* one with the highest `seq`.
*/
#include "toob_mailbox.h"
#include "libtoob.h"
#ifdef TOOB_HOST_FUZZING
#include "libtoob_config_sandbox.h"
#else
#include "generated_boot_config.h"
#endif
#include "toob_internal.h"
#include <stddef.h>
/* Geometry sanity: the writer erases exactly one slot sector at a time, so the
* mailbox region must be TOOB_MAILBOX_SLOTS distinct erase sectors. */
_Static_assert(CHIP_MAILBOX_SIZE == TOOB_MAILBOX_SLOTS * CHIP_MAILBOX_SLOT_SIZE,
"mailbox region must be exactly TOOB_MAILBOX_SLOTS slot sectors");
_Static_assert(sizeof(toob_mailbox_t) <= CHIP_MAILBOX_SLOT_SIZE,
"mailbox record must fit in one slot sector");
_Static_assert(sizeof(toob_mailbox_t) % CHIP_FLASH_WRITE_ALIGNMENT == 0,
"mailbox record must be a multiple of the flash write alignment");
static inline uint32_t slot_addr(uint32_t i) {
return CHIP_MAILBOX_ABS_ADDR + i * CHIP_MAILBOX_SLOT_SIZE;
}
/**
* @brief Read one slot and validate magic + CRC.
* @return true and fills *out if the slot holds a complete valid record.
*/
static bool slot_read_valid(uint32_t i, toob_mailbox_t *out) {
toob_secure_zeroize(out, sizeof(*out));
if (toob_os_flash_read(slot_addr(i), (uint8_t *)out, sizeof(*out)) != TOOB_OK) {
return false;
}
if (out->magic != TOOB_MAILBOX_MAGIC) {