Skip to content

Commit adeb496

Browse files
authored
examples/arduino: write the platform layer against Arduino, not Zephyr (pytorch#21992)
## Summary The library shipped `runtime/platform/default/zephyr.cpp`, which calls `k_uptime_ticks` and `k_malloc`. That pinned it to the one Arduino core built on Zephyr, for seven functions that all have Arduino equivalents. `arduino_pal.cpp` uses `micros()`, `malloc()` and `free()` instead, and routes logging through the weak `et_arduino_log` hook the examples already implement. Both upstream backends are dropped so link order cannot pick one. It also corrects a timestamp bug: `zephyr.cpp` returned a tick ratio of `{1, 1}` with a comment admitting it did not know the units. `micros()` is microseconds, so `{1000, 1}` is right, and profiling numbers now mean something. Two things had to be fixed before another core could work at all. The Renesas cores define `abs` as a macro in `Arduino.h`, which turns c10's `inline T abs(T a)` into a syntax error and takes `<complex>` with it — the Zephyr core happens not to, which is the only reason this was invisible. And those cores ship `arm-none-eabi-gcc 7.2.1` from 2017, which cannot resolve `EValue::to()`'s overload set. Nothing in the library fixes that, so it now fails with one line naming the toolchain rather than pages of template errors: ``` error: #error "ExecuTorch needs GCC 9 or newer. This board core ships an older arm-none-eabi-gcc (Renesas cores are on 7.2.1 from 2017). Nothing in the library can work around it; the core's toolchain has to be updated." ``` `architectures` stays `zephyr`. Every other Arduino core ships `arm-none-eabi-gcc 7` -- mbed_nano, renesas_uno and renesas_portenta all do -- so opening it up would advertise the library to boards that would every one of them stop at the `#error`, trading a clear message for a wasted install. Zephyr's SDK 0.16.8 is the only Arduino toolchain new enough today. It becomes `*` when that changes, and the guard is what makes that safe to do. To be clear about what this does and does not do: **it adds no new board**. What it buys is the `abs` fix, the corrected tick ratio, one platform layer instead of two, and the blocker moving off our side and onto Arduino's toolchain. GCC 12.2 is verified working and 7.2.1 verified failing. The floor of 9 is conservative rather than measured; 8 through 11 are untested. ## Test plan Arduino Uno Q, core 0.90.0, `link_mode=static`: ``` HelloExecuTorch 473,368 flash (60%) 3,060 RAM (1%) AddModel 508,556 flash (64%) 12,276 RAM (4%) KeywordSpotting 564,352 flash (71%) 47,092 RAM (17%) ``` All three flashed and run. KeywordSpotting still detects every class, with scores identical to the `zephyr.cpp` build, so the swap is behaviourally inert: ``` yes 8.95 no -2.16 up -8.49 down -6.48 left -0.77 right -9.26 on -14.81 off -0.46 stop -5.40 go -7.10 -> Detected: yes CORRECT! ``` Compiler guard checked in both directions — Uno Q (GCC 12.2) compiles; Portenta C33 (GCC 7.2.1) stops at the `#error` above rather than emitting template failures. `lintrunner` clean. Authored with Claude Code (Opus 5).
1 parent 1d4df21 commit adeb496

4 files changed

Lines changed: 126 additions & 41 deletions

File tree

‎.lintrunner.toml‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,10 @@ exclude_patterns = [
205205
# Top-level test and platform integration areas.
206206
'test/**',
207207
'zephyr/**',
208+
209+
# An ExecuTorch platform layer, same as runtime/platform/default above; the
210+
# et_pal_* functions are called by the runtime, not from this file.
211+
'examples/arduino/arduino_pal.cpp',
208212
]
209213
command = [
210214
'python',

‎examples/arduino/ExecuTorch.h‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,37 @@
2222
#define FLATBUFFERS_MAX_ALIGNMENT 1024
2323
#endif
2424

25+
// ExecuTorch's C++ needs a compiler newer than some Arduino cores ship. The
26+
// Renesas cores are on arm-none-eabi-gcc 7.2.1 from 2017, which cannot resolve
27+
// EValue::to()'s overload set and fails with pages of template errors that say
28+
// nothing about the real cause. Fail with one line instead.
29+
//
30+
// Verified on GCC 12.2 (Zephyr SDK 0.16.8). 7.2.1 is known bad. The versions
31+
// in between are untested, so 9 is a conservative floor rather than a measured
32+
// one.
33+
//
34+
// library.properties still says architectures=zephyr, because every other
35+
// Arduino core currently ships arm-none-eabi-gcc 7. Advertising the library to
36+
// boards that cannot build it would trade a clear error for a wasted install.
37+
// This guard is for anyone who copies the library in by hand, and for whenever
38+
// a second core becomes usable.
39+
#if defined(__GNUC__) && !defined(__clang__) && __GNUC__ < 9
40+
#error \
41+
"ExecuTorch needs GCC 9 or newer. This board core ships an older \
42+
arm-none-eabi-gcc (Renesas cores are on 7.2.1 from 2017). Nothing in the \
43+
library can work around it; the core's toolchain has to be updated."
44+
#endif
45+
46+
// Several Arduino cores define abs/min/max/round as macros in Arduino.h. They
47+
// expand inside c10's templates and inside <complex>, turning `inline T abs(T
48+
// a)` into a syntax error. The Zephyr core happens not to define abs, which is
49+
// the only reason this went unnoticed. Undefine them before the ExecuTorch
50+
// headers; std::abs, std::min and std::max are available to sketches instead.
51+
#undef abs
52+
#undef min
53+
#undef max
54+
#undef round
55+
2556
#include <executorch/extension/data_loader/buffer_data_loader.h>
2657
#include <executorch/runtime/core/memory_allocator.h>
2758
#include <executorch/runtime/executor/method.h>

‎examples/arduino/arduino_pal.cpp‎

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
/*
2+
* Copyright (c) Meta Platforms, Inc. and affiliates.
3+
* All rights reserved.
4+
*
5+
* This source code is licensed under the BSD-style license found in the
6+
* LICENSE file in the root directory of this source tree.
7+
*/
8+
9+
/*
10+
* ExecuTorch platform layer written against the Arduino API rather than any
11+
* one board core. runtime/platform/default has a zephyr.cpp, but it calls
12+
* k_uptime_ticks and k_malloc, which pins the library to the single Arduino
13+
* core built on Zephyr. millis() and malloc() exist on all of them.
14+
*
15+
* The build script vendors this in place of the upstream backends and deletes
16+
* them; shipping two would leave the choice to link order.
17+
*/
18+
19+
#include <Arduino.h>
20+
#include <executorch/runtime/platform/compiler.h>
21+
#include <executorch/runtime/platform/platform.h>
22+
#include <cstdio>
23+
#include <cstdlib>
24+
25+
/*
26+
* Logging goes through a weak hook so the library does not have to know how a
27+
* board exposes its console. On the Uno Q, Serial comes from
28+
* Arduino_RouterBridge rather than the core, and a sketch may not want the
29+
* runtime writing to it at all. Sketches that do implement this see the
30+
* runtime's own diagnostics -- allocation shortfalls, operator mismatches --
31+
* instead of a bare error code.
32+
*/
33+
extern "C" ET_WEAK void et_arduino_log(const char* message) {
34+
(void)message;
35+
}
36+
37+
void et_pal_init(void) {}
38+
39+
ET_NORETURN void et_pal_abort(void) {
40+
// No _Exit on a microcontroller: there is nothing to return to. Park with
41+
// interrupts off so a watchdog resets the board rather than letting it run
42+
// on in an undefined state.
43+
noInterrupts();
44+
while (true) {
45+
}
46+
}
47+
48+
et_timestamp_t et_pal_current_ticks(void) {
49+
return static_cast<et_timestamp_t>(micros());
50+
}
51+
52+
et_tick_ratio_t et_pal_ticks_to_ns_multiplier(void) {
53+
// micros() ticks are microseconds, so nanoseconds are 1000/1 of them.
54+
return {1000, 1};
55+
}
56+
57+
void et_pal_emit_log_message(
58+
ET_UNUSED et_timestamp_t timestamp,
59+
et_pal_log_level_t level,
60+
const char* filename,
61+
ET_UNUSED const char* function,
62+
size_t line,
63+
const char* message,
64+
ET_UNUSED size_t length) {
65+
char buffer[256];
66+
snprintf(
67+
buffer,
68+
sizeof(buffer),
69+
"%c [ET:%s:%zu] %s",
70+
static_cast<char>(level),
71+
filename,
72+
line,
73+
message);
74+
et_arduino_log(buffer);
75+
}
76+
77+
void* et_pal_allocate(size_t size) {
78+
return malloc(size);
79+
}
80+
81+
void et_pal_free(void* ptr) {
82+
free(ptr);
83+
}

‎examples/arduino/build_arduino_library.sh‎

Lines changed: 8 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -426,48 +426,15 @@ find "$OUT_DIR" -path "*test*" -name "*.cpp" -delete 2>/dev/null || true
426426
rm -f "$OUT_DIR/src/executorch/runtime/platform/default/android.cpp"
427427
rm -f "$OUT_DIR/src/executorch/runtime/platform/default/posix.cpp"
428428
rm -f "$OUT_DIR/src/executorch/runtime/platform/default/windows.cpp"
429-
# minimal.cpp and zephyr.cpp both define the et_pal_* backend, so shipping both
430-
# leaves the choice to link order. minimal's logger is an empty body and its
431-
# et_pal_allocate returns nullptr, which silently discards every ET_LOG.
429+
# Ship one platform layer, written against the Arduino API rather than any one
430+
# board core. Upstream's zephyr.cpp calls k_uptime_ticks and k_malloc, which
431+
# would pin the library to the single Arduino core built on Zephyr; minimal.cpp
432+
# has an empty logger and an allocator that returns nullptr. Both define the
433+
# same et_pal_* symbols, so keeping any of them alongside ours would leave the
434+
# choice to link order.
432435
rm -f "$OUT_DIR/src/executorch/runtime/platform/default/minimal.cpp"
433-
434-
# zephyr.cpp logs through fprintf, and platform_stubs.c stubs fprintf out to
435-
# nothing, so runtime diagnostics never reach the user. Route them to a weak
436-
# hook a sketch can implement -- see the examples for a Serial implementation.
437-
ZEPHYR_PAL="$OUT_DIR/src/executorch/runtime/platform/default/zephyr.cpp"
438-
"$PYTHON" - "$ZEPHYR_PAL" << 'PATCH'
439-
import sys
440-
p = sys.argv[1]
441-
s = open(p).read()
442-
old = """ fprintf(
443-
stderr,
444-
"%c [executorch:%s:%zu %s()] %s\\n",
445-
level,
446-
filename,
447-
line,
448-
function,
449-
message);"""
450-
new = """ char et_log_buf[256];
451-
snprintf(
452-
et_log_buf,
453-
sizeof(et_log_buf),
454-
"%c [ET:%s:%zu] %s",
455-
(char)level,
456-
filename,
457-
line,
458-
message);
459-
et_arduino_log(et_log_buf);"""
460-
if old not in s:
461-
sys.exit("ERROR: zephyr.cpp log call not found; the PAL changed upstream.")
462-
s = s.replace(old, new)
463-
s = s.replace(
464-
"void et_pal_emit_log_message(",
465-
'extern "C" __attribute__((weak)) void et_arduino_log(const char*) {}\n\n'
466-
"void et_pal_emit_log_message(",
467-
1,
468-
)
469-
open(p, "w").write(s)
470-
PATCH
436+
rm -f "$OUT_DIR/src/executorch/runtime/platform/default/zephyr.cpp"
437+
cp "$SCRIPT_DIR/arduino_pal.cpp" "$OUT_DIR/src/executorch/runtime/platform/default/"
471438

472439
# Regenerate schema headers if flatc is available
473440
FLATC=""

0 commit comments

Comments
 (0)