メインコンテンツへスキップ
見出し画像

#RP2 : RP2350をBoot from Scratch!Swiftで...

    RP2350を入手。
    Bootだ、Bootだぁー、まずはBootダァー!と、ノリノリでTypingしていたら、ふと、「これって..どうBootしてんだっけ?」と久々に好奇心が。
    というわけで、ありがたきSDKに見向きもせずに、たまたま目に入ったSwiftでCodingを始めてしまったので、note。

    その名もRP2.swift からstartしよう。今後色々と初期化するだろうからinitialize()を作り、そこからmain()を呼んでぇ、とりあえずInfinity loopと、戻らないのでreturnはNeverと… resetは再初期化…  書く順番気にしなかったけど、まあいいか、おしまい。

    enum RP2 {
        static func initialize() -> Never { main() }
        static func main() -> Never { while true {} }
        static func reset() -> Never { RP2.initialize() }
    }

    って、わけにはいかない。

    RP2350はBoot ROMからBoot

    RP2350のDatasheetによると、

    A 32 kB read-only memory (ROM) appears at address 0x00000000. 
    (snip)
    • Core 0 Boot code (Section 5.2. Processor-controlled boot sequence)

    4.1 ROM

    Boot ROM内のBoot codeが実行されてboot処理が開始される。

    Flash image boot requires the bootrom to discover a block loop starting within the first 4 kB of flash which contains a valid IMAGE_DEF (and no PARTITION_TABLE).

    5.1.12. Flash image boot

    Arm Cortex-M33 ProgramをFlashに配置する場合は、外付Flash先頭Address 4kB以内にProgram特性を表現するIMAGE_DEFを含むblock loopを配置。

    Assuming CRIT1.SECURE_BOOT_ENABLE is clear, the minimum valid IMAGE_DEF is the following 20-byte sequence:
    (snip)
    The LE Value column indicates a 32-bit little-endian value that should appear verbatim in your program image.
    Since the above block does not specify an explicit entry point, the bootrom will assume the binary starts with a Cortex-M vector table, and enter via the reset handler and initial stack pointer specified in that table (offsets +4 and +0 bytes into the table).

    5.9.5.1. Minimum Arm IMAGE_DEF

    最も単純な最小IMAGE_DEFは以下の20bytes

    Cf. Table 503
    
    word | LE Value   | Bytes         | Description
    -----+------------+---------------+----------------------------------
    0    | 0xffffded3 | 4             | PICOBIN_BLOCK_MARKER_START
    -----+------------+---------------+----------------------------------
    1    | 0x10210142 | 1:       0x42 | PICOBIN_BLOCK_ITEM_1BS_IMAGE_TYPE
         |            | 1:     0x01   | item is 1 word in size
         |            | 2: 0x1021     | Exe, Security, ARM, RP2350
    -----+------------+---------------+----------------------------------
    2    | 0x000001ff | 1:       0xff | PICOBIN_BLOCK_ITEM_2BS_LAST
         |            | 2:   0x0001   | Size:1
         |            | 1: 0x00       | Pad:0
    -----+------------+---------------+----------------------------------
    3    | 0x00000000 | 4             | block loop link to self
    -----+------------+---------------+----------------------------------
    4    | 0xab123579 | 4             | PICOBIN_BLOCK_MARKER_END

    最も簡単な配置は、Flashの先頭AddressにVector Tableを配置、4KB以内にIMAGE_DEF(20bytes)、そしてProgramを配置

    CPU見えAddress        [Flash Address Map]                Flash Address
     0x10000000 +--------------------------------------------+ 0x00000000
                │ VectorTable: initial stack pointer 4 bytes │
     0x10000004 +              ------------------------------+ 0x00000004
                │              reset handler         4 bytes |
     0x10000008 +--------------------------------------------+ 0x00000008
                │ IMAGE_DEF:                        20 bytes |
                |                                            |
                |         (See, Table 503)                   |
                |                                            |
                |                                            | 
     0x1000001C +--------------------------------------------+ 0x0000001c
                │ Program (swift):                           │
                │    .text / .rodata                         │
               ~~~                                          ~~~
                |                                            |
                +--------------------------------------------+

    Boot ROM仕様に沿ってLinker(ld.lld)設定

    Swift Compilerが生成する.o(Object File) に含まれるCodeやDataのAddressを、.ld(Linker Script)によってLinker(ld.lld)がBoot ROM仕様に合うように決定し、.elf(Executable and Linkable Format)を生成。

    ```mermaid
    flowchart LR
        A("(Swift Compiler)") --> B("[RP2.o]")
        B --> D("(ld.lld)")
        C("[rp2350.ld]<br/>Mapping Rule<br/>for RP2350 Boot ROM") --> D
        D --> E("Section<br/>Symbol<br/>Relocation")
        E --> F("[RP2.elf]")
    
        classDef Compiler fill:#DBEAFE,stroke:#2563EB,color:#1E40AF
        classDef Input fill:#F3E8FF,stroke:#9333EA,color:#6B21A8
        classDef Linker fill:#FEF3C7,stroke:#D97706,color:#92400E
        classDef Relocation fill:#DCFCE7,stroke:#16A34A,color:#166534
        classDef Output fill:#CFFAFE,stroke:#0891B2,color:#155E75
    
        linkStyle default stroke:#94A3B8,stroke-width:2px
    
        class A Compiler
        class B,C Input
        class D Linker
        class E Relocation
        class F Output
    ```

    ld.lld用のconfig、rp2350.ld はBoot ROM仕様に合わせる。

    ENTRY(rp2_reset)
    FLASH_BASE = 0x10000000
    SRAM_BASE =  0x20000000
    /* ........................... snip ...................... */
    MEMORY {
        FLASH (rx) : ORIGIN = FLASH_BASE, LENGTH = FLASH_BYTES
        RAM (rwx) : ORIGIN = SRAM_BASE, LENGTH = SRAM_BYTES
    }
    SECTIONS {
        .vectors ORIGIN(FLASH) : {
            LONG(STACK_TOP)
            LONG(rp2_reset)
        } > FLASH
        .picobin : {
            LONG(PICOBIN_BLOCK_MARKER_START)
            LONG((PICOBIN_IMAGE_TYPE_RP2350_ARM_SECURE << 16) |
                 (1 << 8) | PICOBIN_ITEM_IMAGE_TYPE)
            LONG((1 << 8) | PICOBIN_ITEM_LAST)
            LONG(0)
            LONG(PICOBIN_BLOCK_MARKER_END)
        } > FLASH
        .text : ALIGN(4) {
            *(.text .text.*)
            *(.rodata .rodata.*)
            . = ALIGN(4);
        } > FLASH
    }
    • ORIGIN(FLASH): FLASH領域の開始アドレス(0x10000000)取得

    • .vectors, .picobin, .text: 自ら命名したsection名

      • .vectors: VectorTableを定義、stack pointerの初期値、Etrypoint, 将来的にHandler等

      • .picobin: IMAGEDEFを定義

      • .text: ELFをあとで配置

    • LONG() : 32bit[4byte]を LE(little endian)で書き込み

      • RP2350 Arm Cortex-M33はLE固定

    • > FLASH: FLASH領域へ書き込み

    ここで、ENTRY()でSwift ProgramのEntry Pointとしてrp2_resetを指定。
    でもrp2_resetはまだ定義してない、ようやくSwiftに戻れる。

    SwiftでEntryPointを定義

    現時点ではCompiler option次第で生成されるmainを指定してもOKだがrp2_resetを敢えてEntryPointとして定義。

    @_cdecl("rp2_reset")
    func resetHandler() -> Never { RP2.reset() }

    Linkerが期待するのは指定されたSymbolの存在だが、Swift CompilerはGlobal functionや公開methodをName Mangling(名前修飾)するのでSymbol固定のためにunOfficial AttributeだけどC declarationを実現する@_cdecl Attributeを指定。これはGlobal functionにつける必要があるからRP2.reset()直ではなく、わざわざGlobal functionとしてRP2.reset()を呼ぶresetHandler()を作成して指定。

    $ nm RP2.o | grep reset
    00000000 T $e3RP212resetHandlers5NeverOyF
    00000000 T rp2_reset

    あとでcompileするけどこんなかんじ。@_cdeclのおかげで固定名。

    $ nm RP2.o | swift-demangle | grep reset
    00000000 T RP2.resetHandler() -> Swift.Never
    00000000 T rp2_reset

    swift-demangleを挟むと読める形に戻してくれる。ちなみに00000000なのはLink前だから、RP2.resetが見えないのは最適化で見えたり見えなかったりだから。

    ```mermaid
    flowchart LR
        A("BootROM") --> B("rp2_reset / resetHandler")
        B --> C("RP2.reset")
        C --> D("RP2.initialize")
        D --> E("RP2.main")
    
        classDef BootROM fill:#DBEAFE,stroke:#2563EB,color:#1E40AF
        classDef Swift fill:#FEF3C7,stroke:#D97706,color:#92400E
        linkStyle default stroke:#60A5FA,stroke-width:3px
    
        class A BootROM
        class B,C,D,E Swift
    ```

    swiftcでCompileする

    $ swiftc -target armv8m.main-none-none-eabi \
       -enable-experimental-feature Embedded -wmo \
       -parse-as-library \
       -emit-object -o "$BUILD_DIR/RP2.o" \
       -Xfrontend -function-sections \
       -Osize \
       RP2.swift
    • -target armv8m.main-none-none-eabi

      • Target Triple(といいつつ今4要素:arch-vendor-os-env)

        • arch: arm8m.main: Cortex-M33に最適なArm8-M Main Extensions 

        • vendor: none: Vendor指定なし

        • os: none: OSなし(bare-metal)

        • env: eabi: Embedded ABI

    • -enable-experimental-feature Embedded -wmo

      • Embedded swift(静的処理、依存なるべく排除)を有効化(まだ実験的)

      • wmo必須、複数fileまとめて解析/最適化。指定しないと”error: Whole module optimization (wmo) must be enabled with embedded Swift."

    • -parse-as-library

      • Top Levelで実行/main自動生成禁止。EntryPointは自己制御だから指定

    • -Xfrontend -function-sections

      • swift-frontendに-function-sectionsを渡しfunctionごとに独立した.text sectionを生成させる(不要関数をsection単位で削除するため->後述)

    ld.lldでLinkする

    $ ld.lld -T $CFG_DIR/rp2350.ld \
        --gc-sections \
        --build-id=none \
        -Map="$BUILD_DIR/RP2.map" \
        "$BUILD_DIR/RP2.o" -o "$BUILD_DIR/RP2.elf"
    • --gc-sections

      • swiftcの-Xfronted -function-sectionsで生成したsectionを解析した結果Linkerが不要としたsectionを削除。意図に関わらずswiftが自動生成するアレコレがあるので

    • --build-id=none

      • GNU由来.note.gnu.build-idを生成しない、ELF内不要meta data削除

    • -Map

      • debug用途で、必要なとこだけpickしているが以下の様なmapが出力される。今回.dataを作ってないのでVMA=LMAのだけしか見えなくてOK

         VMA      LMA     Size Align Out
    10000000 10000000        8     1 .vectors
    10000008 10000008       14     1 .picobin
    1000001c 1000001c        8     1 .text

    OpenOCDでSWD経由ELF転送してBoot

    今回は、RP2350のSWDIO、SWCLK、RUN、GNDをRPi4のGPIO22-24、GNDに接続。FlashへELF転送後、Core 0がFlashのXIP領域(0x10000020)を実行中を確認。おめでとう、初Boot!

    $ cat $CFG_DIR/rp-swd-rp2350.cfg
    adapter driver bcm2835gpio
    bcm2835gpio peripheral_mem_dev /dev/gpiomem
    adapter gpio swclk 22
    adapter gpio swdio 23
    adapter gpio srst 24
    adapter speed 100
    $ openocd -f $CFG_DIR/rp-swd-rp2350.cfg -f target/rp2350.cfg \
      -c "program $BUILD_DIR/RP2.elf verify reset"
      -c "sleep 2000; halt; echo [reg pc]; resume; sleep 2000; shutdown"
    (snip)
    ** Programming Started **
    Info : Padding image section 1 at 0x10000024 with 220 bytes (bank write end alignment)
    Warn : Adding extra erase range, 0x10000100 .. 0x10000fff
    ** Programming Finished **
    ** Verify Started **
    ** Verified OK **
    ** Resetting Target **
    pc (/32): 0x10000020
    [rp2350.cm0] halted due to debug-request, current mode: Thread 
    xPSR: 0x29000000 pc: 0x10000020 msp: 0x20082000
    [rp2350.cm1] halted due to debug-request, current mode: Thread 
    xPSR: 0x09000000 pc: 0x000000ec msp: 0xf0000000
    shutdown command invoked
    • -f: configを指定

      • 先にGPIO/速度設定等のIF config、後でchip固有config指定が一般的。実態は/usr/local/share/openocd/scripts/target/rp2350.cfgとかににあるけどtarget/xxxと指定すると探してくれる

    • -c: commandを指定

      • program xxx.elf:  ELFをFlashに書き込み

        • verify: 書き込み後、内容照合

        • reset: RP2350をreset=BootROM経由でFlashに書いたProgram実行

      • sleep: 指定msの間、OpenOCDを一時停止

      • halt: RP2350の実行を一時停止

      • echo [reg pc]: program counterの値を表示(telnet等で接続する方に表示されちゃうのでechoでこちらのttyに表示)

      • resume: RP2350の実行を再開

      • shutdown: OpenOCDを終了

    0x10000020の場所を確認

    $ llvm-objdump -d --no-show-raw-insn RP2.elf | swift-demangle
    
    RP2.elf:	file format elf32-littlearm
    
    Disassembly of section .text:
    
    1000001c <rp2_reset>:
    1000001c:   bl  0x10000020 <RP2.resetHandler() -> Swift.Never> @ imm = #0x0
    
    10000020 <RP2.resetHandler() -> Swift.Never>:
    10000020:    b  0x10000020 <RP2.resetHandler() -> Swift.Never> @ imm = #-0x4
    
    10000022 <_swift_exceptionPersonality>:
    10000022: trap

    "b 0x10000020"というわけで、Branch命令で自分自身、RP2.resetHandler()内で無限Loop。書いたCodeと動作違うのは最適化影響。

    書いた通りに実行できるかな?

    最適化されているので実質的に動作は同じなんだけども、せっかくCode書いたのでCodeの通りに動かしてみるか。swiftcのoptionでsize重視の最適化-Osizeを指定していたので、-Ononeを指定すれば書いた通りになるはず。

    $ swiftc -target armv8m.main-none-none-eabi \
       -enable-experimental-feature Embedded -wmo \
       -parse-as-library \
       -emit-object -o "$BUILD_DIR/RP2.o" \
       -Xfrontend -function-sections \
       -Onone \
       RP2.swift
    $ ld.lld -T $CFG_DIR/rp2350.ld \
        --gc-sections \
        --build-id=none \
        -Map="$BUILD_DIR/RP2.map" \
        "$BUILD_DIR/RP2.o" -o "$BUILD_DIR/RP2.elf"
    ld.lld: error: undefined symbol: __stack_chk_fail
    >>> referenced by RP2.o
    >>>               RP2.o:($es31_embeddedReportFatalErrorInFile6prefix7message4file4lineys12StaticStringV_A2GSutF)
    
    ld.lld: error: undefined symbol: __stack_chk_guard
    >>> referenced by RP2.o
    >>>               RP2.o:($es31_embeddedReportFatalErrorInFile6prefix7message4file4lineys12StaticStringV_A2GSutF)
    >>> referenced by RP2.o
    >>>               RP2.o:($es31_embeddedReportFatalErrorInFile6prefix7message4file4lineys12StaticStringV_A2GSutF)
    
    ld.lld: error: undefined symbol: putchar
    >>> referenced by RP2.o
    >>>               RP2.o:($es5print_10terminatorys12StaticStringV_ADtF)
    >>> referenced by RP2.o
    >>>               RP2.o:($es5print_10terminatorys12StaticStringV_ADtF)
    >>> referenced by RP2.o
    >>>               RP2.o:($es15printCharactersyySRys5UInt8VGF)
    
    ld.lld: error: undefined symbol: __aeabi_memmove
    >>> referenced by RP2.o
    >>>               RP2.o:($eSv10copyMemory4from9byteCountySV_SitF)
    $ nm $BUILD_DIR/RP2.o | grep "U "
             U __aeabi_memmove
             U __stack_chk_fail
             U __stack_chk_guard
             U free
             U posix_memalign
             U putchar
    

    Compileは通るけど-Onone影響でUndefinedなfunction残りLink error発生。最適化が色々頑張ってくれていたので気がつかなかったが、swiftが余計なfunction呼びだしたりするのでその辺りの自前解決が必要。

    • _embeddedReportFatalErrorInFile()

      • EmbeddedRuntimeのfunctionだがsource codeを読んだところで、__stack_chk_failや、__stack_chk_guardは見つからない。なぜならstack protectorとしてCompilerが自動的に挿入しているから。これを回避するにはswiftcに-Xfrontend -disable-stack-protectorを渡す。

    • print(_:terminator:) と printCharacters(_:)

      • 最終的にputcharを呼び出す。Embeddedなのでlibcのputchar呼んでもしょうがないから自ら実装する感じ。

    • copyMemory(from:byteCount:)

      • UnsafeMutableRawPointerのfunctionからmemmove関連呼び出し最終的にARM EABI向けのruntime functionである__aeabi_memmoveを呼んでる。これを解決するにはarm向けcompiler-rtを導入してlinkするか、自ら実装する感じ。

    今回は、書いたところが動けば良いので無理くり動かそう。

    $ swiftc -target armv8m.main-none-none-eabi \
       -enable-experimental-feature Embedded -wmo \
       -parse-as-library -emit-object -o "$BUILD_DIR/RP2.o" \
       -Xfrontend -function-sections -Xfrontend -disable-stack-protector \
       -Onone RP2.swift
    $ stub.S << TEST
    .thumb
    .global putchar, __aeabi_memmove
    .thumb_func
    putchar:
    __aeabi_memmove:
        b .
    TEST
    $ clang -target armv8m.main-none-none-eabi -c stub.S -o stub.o
    root@04b284d75062:/workspace/Work/rp-swift_work/Blog/001-rp2350-boot/Code/Sources# clang -target armv8m.main-none-none-eabi -c stub.S -o stubs.o
    $ ld.lld -T $CFG_DIR/rp2350.ld --gc-sections --build-id=none \
        -Map="$BUILD_DIR/RP2_test.map" \
        "$BUILD_DIR/RP2.o" "$BUILD_DIR/stub.o" -o "$BUILD_DIR/RP2_test.elf"
    $ openocd -f $CFG_DIR/rp-swd-rp2350.cfg -f target/rp2350.cfg \
      -c "program $BUILD_DIR/RP2.elf verify reset"
      -c "sleep 2000; halt; echo [reg pc]; resume; sleep 2000; shutdown"
    (snip)
    pc (/32): 0x10000028
    (snip)
    $ llvm-objdump -d --no-show-raw-insn RP2_test.elf \
       | swift-demangle | grep -A 5 -B 5 10000028
    10000020 <static RP2.RP2.initialize() -> Swift.Never>:
    10000020:      	push	{r7, lr}
    10000022:      	bl	0x10000026 <static RP2.RP2.main() -> Swift.Never> @ imm = #0x0
    
    10000026 <static RP2.RP2.main() -> Swift.Never>:
    10000026:      	b	0x10000028 <static RP2.RP2.main() -> Swift.Never+0x2> @ imm = #-0x2
    10000028:      	movs	r0, #0x0
    1000002a:      	cbnz	r0, 0x10000030 <static RP2.RP2.reset() -> Swift.Never> @ imm = #0x2
    1000002c:      	b	0x1000002e <static RP2.RP2.main() -> Swift.Never+0x8> @ imm = #-0x2
    1000002e:      	b	0x10000028 <static RP2.RP2.main() -> Swift.Never+0x2> @ imm = #-0xa
    
    10000030 <static RP2.RP2.reset() -> Swift.Never>:
    10000030:      	push	{r7, lr}
    10000032:      	bl	0x10000020 <static RP2.RP2.initialize() -> Swift.Never> @ imm = #-0x16
    ```mermaid
    flowchart LR
        A(RP2.reset) --> B("RP2.initialize")
        B --> C("RP2.main")
        classDef Swift fill:#FEF3C7,stroke:#D97706,color:#92400E
        linkStyle default stroke:#60A5FA,stroke-width:3px
        class A,B,C Swift
    ```

    書いた通りに動いていることを確認。

    まとめ

    今回はRP2350のBoot周りの確認のみ。久々にLinker触ったなぁ。自前でやるとアレコレ仕組みがよーくわかる、と、同時に仮にこういう基礎的な部分に不具合/脆弱性があったら…ゾッとするねぇ、勝手に何がLinkされてるかなんて調べないとわからんし… あと、今のところSwiftで余計に面倒に…は言わない約束、きっとあとでいいことあるハズ。


    Copyright (c) 2026 tkagy All rights reserved.


     
     

    tkagy

     
     
    なんとなく、なんとなく。

    あなたへのおすすめ