01cabb0324
Boosted performance, board.json metadata, more mimxrt, rp2, samd features
This release of MicroPython sees a boost to the overall performance of the
VM and runtime. This is achieved by the addition of an optional cache to
speed up general hash table lookups, as well as a fast path in the VM for
the LOAD_ATTR opcode on instance types. The new configuration options are
MICROPY_OPT_MAP_LOOKUP_CACHE and MICROPY_OPT_LOAD_ATTR_FAST_PATH. As part
of this improvement the MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE option has
been removed, which provided a similar map caching mechanism but with the
cache stored in the bytecode, which made it not useful on bare metal ports.
The new mechanism is measured to be at least as good as the old one,
applies to more map lookups, has a constant RAM overhead, and applies to
native code as well as bytecode.
These performance options are enabled on the esp32, mimxrt, rp2, stm32 and
unix ports. For esp32 and mimxrt some code is also moved to RAM to further
boost performance. On stm32, performance increases by about 20% for
benchmarks that are heavy on name lookups, like misc_pystone.py and
misc_raytrace.py. On esp32 performance can increase by 2-3x, and on mimxrt
it is up to 6x.
All boards in all ports now have a board.json metadata file, which is used
to automatically build firmware and generate a webpage for that board
(among other possibilities). Auto-build scripts have been added for this
purpose and they build all esp32, mimxrt, rp2, samd and stm32 boards. The
generated output is available at https://micropython.org/download.
Support for FROZEN_DIR and FROZEN_MPY_DIR has been deprecated for some time
and was finally removed in this release. Instead of these, FROZEN_MANIFEST
can be used. The io.resource_stream() function is also removed, replaced
by the pure Python version in micropython-lib.
The search order for importing frozen Python modules is now controlled by
the ".frozen" entry in sys.path. This string is added by default in the
second position in sys.path. User code should adjust sys.path depending on
the desired behaviour. Putting ".frozen" first in sys.path will speed up
importing frozen modules.
A bug in multiple precision integers with bitwise of -0 was fixed in commit
2c139bbf4e
.
The platform module has been added to allow querying the compiler and
underlying SDK/HAL/libc version. This is enabled on esp32, mimxrt and
stm32 ports.
The mpremote tool now supports seek, flush, mkdir and rmdir on PC-mounted
filesystems. And a help command has been added.
The documentation has seen many additions and improvements thanks (for a
second time) to the Google Season of Docs project. The rp2 documentation
now includes a reference for PIO assembly instructions, a PIO quick
reference and a PIO tutorial. The random and stm modules have been
documented, along with sys.settrace, manifest.py files and mpremote. There
is also now more detail about the differences between MicroPython and
standard Python 3.5 and above.
The esp32 port sees support for ESP32-S3 SoCs, and new boards GENERIC_S3,
ESP32_S2_WROVER, LOLIN_S2_MINI, LOLIN_S2_PICO and UM_FEATHERS2NEO. The PWM
driver has been improved and now supports all PWM timers and channels, and
the duty_u16() and duty_ns() methods, and it keeps the duty constant when
changing frequency. The machine.bitstream() function has been improved to
use RMT, with an option to select the original bit-banging implementation.
The mimxrt port gained new hardware features: SDRAM and SD card support, as
well as network integration with a LAN driver. The machine.WDT class was
added along with the machine.reset_cause(), machine.soft_reset(),
machine.unique_id() add machine.bitstream() functions. DHT sensor support
was added, and f-strings were enabled.
The rp2 port now has support for networking, and bluetooth using NimBLE.
The Nina-W10 WiFi/BT driver is fully integrated and supported by the new
Arduino Nano RP2040 connect board. I2S protocol support is added along
with a machine.bitstream() driver and DHT sensor support. The PWM driver
had a bug fix with the accuracy of setting/getting the frequency, and the
duty value is now retained when changing the frequency.
On the samd port there is now support for the internal flash being a block
device, and for filesystems and the os module. Pin and LED classes have
been implemented. There are more time functions, more Python features
enabled, and the help() function is added. SEEED_WIO_TERMINAL and
SEEED_XIAO board definitions are now available.
The stm32 port now has support for F427, F479 and H7A3(Q)/H7B3(Q) MCUs, and
new board definitions for VCC_GND_H743VI, OLIMEX_H407, MIKROE_QUAIL,
GARATRONIC_PYBSTICK26_F411, STM32H73B3I_DK. A bug was fixed in the SPI
driver where a SPI transfer could fail if the CYW43 WiFi driver was also
active at the same time.
On the windows port the help() function has been enabled, and support for
build variants added, to match the unix port.
The zephyr port upgraded Zephyr to v2.7.0.
The change in code size since the previous release for various ports is
(absolute and percentage change in the text section):
bare-arm: -1520 -2.605%
minimal x86: -2256 -1.531%
unix x64: -457 -0.089%
unix nanbox: -925 -0.204%
stm32: +312 +0.079% PYBV10
cc3200: -176 -0.096%
esp8266: +532 +0.076% GENERIC
esp32: +27096 +1.820% GENERIC
nrf: -212 -0.121% pca10040
rp2: +9904 +2.051% PICO
samd: +35332 +33.969% ADAFRUIT_ITSYBITSY_M4_EXPRESS
The changes that dominate these numbers are:
- bare-arm, minimal: use of new MICROPY_CONFIG_ROM_LEVEL_MINIMUM option and
subsequent disabling of remaining optional features
- unix, cc3200, nrf: general code size reductions of the core
- stm32: performance improvements, addition of platform module
- esp8266: enabling f-strings
- esp32: use of -O2 instead of -Os
- rp2: machine.I2S and other new hardware features
- samd: filesystem support and other new hardware features
Thanks to everyone who contributed to this release: Alan Dragomirecký,
Alexey Shvetsov, Andrew Leech, Andrew Scheller, Antoine Aubert, Boris
Vinogradov, Chris Boudacoff, Chris Fiege, Christian Decker, Damien George,
Daniel Gorny, Dave Hylands, David Michieli, Emilie Feral, Frédéric Pierson,
gibbonsc, Henk Vergonet, iabdalkader, Ihor Nehrutsa, Jan Hrudka, Jan Staal,
jc_.kim, Jim Mussared, Jonathan Hogg, Laurens Valk, leo chung, Lorenzo
Cappelletti, Magnus von Wachenfeldt, Matt Trentini, Matt van de Werken,
Maureen Helm, Michael Bentley, Michael Buesch, Mike Causer, Mike Teachman,
Mike Wadsten, Ned Konz, NitiKaur, oli, patrick, Patrick Van Oosterwijck,
Peter Boin, Peter Hinch, Peter van der Burg, Philipp Ebensberger, Pooya
Moradi, retsyo, robert-hh, roland van straten, Scott Armitage, Sebastian
Wicki, Seon Rozenblum, Sergei Silnov, Simon Baatz, Stewart Bonnick, stijn,
Tobias Thyrrestrup, Tomas Vanek, YoungJoon Chun.
What follows is a detailed list of changes, generated from the git commit
history, and organised into sections.
Main components
===============
all:
- remove MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE
- update Python formatting to latest Black version 21.12b0
- remove support for FROZEN_DIR and FROZEN_MPY_DIR
py core:
- parse: simplify parse nodes representing a list
- emitnative: ensure load_subscr does not clobber existing REG_RET
- mpconfig.h: define initial templates for "feature levels"
- vm: add a fast path for LOAD_ATTR on instance types
- map: add an optional cache of (map+index) to speed up map lookups
- builtinimport: forward all debug printing to MICROPY_DEBUG_PRINTER
- add wrapper macros so hot VM functions can go in fast code location
- runtime: fix crash when exc __new__ doesn't return an exc instance
- mpconfig.h: define the "extra" feature level
- mpconfig.h: revert MICROPY_REPL_INFO to disabled at all levels
- gc: add hook to run code during time consuming GC operations
- showbc: print unary-op string when dumping bytecode
- modsys: replace non-ASCII quote char with ASCII char
- runtime: allow types to use both .attr and .locals_dict
- lexer: support nested [] and {} characters within f-string params
- objfun.h: remove obsolete comments about entries in extra_args
- builtinimport: refactor module importing
- showbc: fix printing of raw bytecode header on nanbox builds
- modio: remove io.resource_stream function
- only search frozen modules when '.frozen' is found in sys.path
- mkrules.cmake: set frozen preprocessor defs early
- runtime: allow initialising sys.path/argv with defaults
- mpstate.h: only include sys.path/argv objects in state when enabled
- mpz: fix bugs with bitwise of -0 by ensuring all 0's are positive
- qstr: reset mpstate.qstr_last_chunk before raising an error
- modbuiltins: add additional macro for extending builtins
- mpconfig.h: define MICROPY_PY_USSL_FINALISER only if not defined
extmod:
- machine_i2c: make SoftI2C configurable via macro option
- machine_spi: make SoftSPI configurable via macro option
- modonewire: make _onewire module configurable via macro option
- machine_pwm: factor out machine.PWM bindings to common code
- move modnetwork and modusocket from stm32 to extmod
- modnetwork: add STA_IF and AP_IF constants
- modnetwork: add extended socket state
- modusocket: add read/write stream methods to socket object
- modnetwork: define network interfaces in port config files
- network_cyw43: make consistent use of STA and AP constants
- modnetwork: remove STM32 references
- modnetwork: remove modnetwork socket u_state member
- mpbthci.h: add mp_bluetooth_hci_uart_any prototype
- nimble: add nimble CMake fragment file
- add platform module
- moduplatform: improve implementation for PC ports
- vfs_posix_file: support MP_STREAM_POLL in vfs_posix_file_ioctl
- modbluetooth: add connection interval to gap_connect
- nimble: update to NimBLE v1.4
- nimble: remove workaround for OS_ENOMEM
- uasyncio: fix gather returning exceptions from a cancelled task
- uplatform: remove unused definitions
- uplatform: use generic custom platform string
- network_ninaw10: fix scan list order to match other NICs
- modbluetooth: support gap_connect(None) to cancel a connection
- modure: redirect regex debug printing to mp_printf
- network_ninaw10: fix config of AP mode
- network_ninaw10: disable active connections before connecting
- network_ninaw10: make NIC state persistent
- network_ninaw10: return -1 on timeout from recv/send
- network_ninaw10: make recv/recvfrom interchangeable
- moduplatform: detect xtensa arch
- modusocket: allow setting timeout on unbound sockets
- modusocket: initialise accepted socket state
- network_ninaw10: use socket timeout preset in modusocket
- modbluetooth: fix conditional compilation of ringbuf_put_uuid
- modbluetooth: put declaration of connect_cancel in correct place
shared:
- libc/string0: don't include string.h, and provide __memcpy_chk
- runtime/pyexec: cleanup EXEC_FLAG flag constants
drivers:
- ninaw10: add ublox Nina-W10 WiFi/BT module driver
- lsm6dsox: add LSM6DSOX driver and examples
- neopixel: avoid heap alloc in fill()
- ninaw10: fix BSSID byte order, and add null byte to ESSID
- ninaw10/nina_wifi_drv: fix DNS resolution
mpy-cross: no changes specific to this component/port
lib:
- mynewt-nimble: switch to the MicroPython fork of NimBLE
- asf4: point submodule to latest commit on circuitpython branch
- update pico-sdk to 1.3.0 and tinyusb to 0.12.0
- stm32lib: update library for L4 v1.17.0, new G4, WL, and MMC fixes
- stm32lib: update library for fix to F7 USB HS
Support components
==================
docs:
- library/os.rst: clarify littlefs requirements for block erase
- library/bluetooth.rst: update incorrect link to gatts_write
- make.bat: change Windows output dir from '_build' to 'build'
- library/machine.I2S.rst: specify that I2S.shift args are kw-only
- esp32: explain ESP32 PWM modes, timers, and channels
- rp2: add reference for PIO assembly instructions, and PIO tutorial
- library/random.rst: document the random module
- reference/mpremote.rst: add docs for mpremote
- reference/manifest.rst: add docs for manifest.py files
- library/stm.rst: document the stm module
- esp32/tutorial: add an example of peripheral control via regs
- rp2/general.rst: fix typo with missing spaces
- library/framebuf.rst: adjust dimensions in example
- library/rp2.rst: update function asm_pio_encode to add sideset_opt
- reference/filesystem.rst: add detail on how to use littlefs fuse
- rp2/quickref.rst: add section on PIO
- library/sys.rst: add docs for sys.settrace
- esp8266/tutorial: fix comments of FrameBuffer examples
- library/uasyncio.rst: detail exception behaviour in cancel/timeout
- library/machine.Timer.rst: document 'id' as positional-only arg
- library/machine.SPI.rst: add example SPI usage
- library/machine.Timer.rst: document `period` and `callback` args
- library/machine.Pin.rst: add Pin.ANALOG mode constant
- remove trailing spaces and convert tabs to spaces
- library/sys.rst: add note about '.frozen' as an entry in sys.path
- differences: document details of new PEPs/features in Python 3.5+
- update copyright year range to include 2022
- esp32: update RMT quickref example to match latest code
examples: no changes specific to this component/port
tests:
- perf_bench: use math.log instead of math.log2
- basics: add tests for type-checking subclassed exc instances
- micropython/const.py: add comment about required config for test
- cpydiff: clarify f-string diffs regarding concatenation
- basics/int_big_cmp.py: add more tests for big-int comparison
- extmod: skip uselect_poll_udp when poll() is not available
tools:
- autobuild: add auto build for GENERIC_C3_USB
- ci.sh: use IDF v4.4 as part of esp32 CI and build GENERIC_S3
- autobuild: add the MIMXRT1010_EVK board to autobuild
- ci.sh: use a specific ESP IDF v4.4 commit
- autobuild: add script to generate website board metadata
- dfu.py: make tool work with python3 when parsing DFU files
- autobuild: automatically build all mimxrt, rp2 and samd boards
- autobuild: automatically build all stm32 boards
- mpremote: implement seek and flush in ioctl method
- autobuild: automatically build all esp32 boards
- upip.py: support == to specify exact package version
- makemanifest.py: make str conversion compatible with Python 2
- makemanifest.py: merge make-frozen.py
- mpremote: add mkdir and rmdir to RemoteFS
- mpremote: add help command
- mpremote: add link to mpremote docs URL in help message
- upip.py: skip '.frozen' entry in sys.path for install path
- autobuild: build esp8266 OTA image with GENERIC_1M board
- ci.sh: upgrade Zephyr docker image to v0.21.0
- ci.sh: build zephyr nucleo_wb55rg to test zephyr bluetooth build
CI:
- workflows: use Python 3.8 for macos workflow
- workflows: add new workflow to build ports download metadata
The ports
=========
all ports:
- add board.json for all boards
- add images, features and urls to board.json
- add '.frozen' as the first entry in sys.path
- move '.frozen' to second entry in sys.path
bare-arm port:
- mpconfigport.h: use MICROPY_CONFIG_ROM_LEVEL_MINIMUM
- mpconfigport.h: disable remaining optional features
cc3200 port: no changes specific to this component/port
esp8266 port:
- boards/GENERIC: enable f-strings
- extract qstr from object when comparing keys in config()
- etshal.h: remove unneeded function declarations
- allow building a board to any dest directory
esp32 port:
- boards: add new FeatherS2-Neo board definition
- machine_timer: use tx_update member for IDF 4.4 and above
- add support for ESP32-S3 SoCs
- boards: add new GENERIC_S3 board definition
- machine_hw_spi: fix hardware SPI DMA channels for S2/S3
- boards: add board definition for ESP32-S2-WROVER module
- boards: add LOLIN_S2_MINI ESP32-S2 board
- machine_pwm: add support for all PWM timers and channels
- README: updated readme with req IDF vers for ESP32-S2, C3 and S3
- usb: add USB host connection detection for CDC serial output
- machine_pin: block out IO16 and IO17 when using SPIRAM on ESP32
- mpthreadport: fix TCB cleanup function so thread_mutex is ready
- main: add option for a board to hook code into startup sequence
- split out WLAN code from modnetwork.c to network_wlan.c
- enable optimisations and move code to iRAM to boost performance
- usb: improve speed of USB CDC output
- add specific deploy_s2.md instructions for esp32-s2
- boards/LOLIN_S2_MINI: add image to board.json
- boards: update board and deploy metadata for UM_xxx boards
- usb: further improve speed of USB CDC output
- boards/LOLIN_S2_PICO: add LOLIN_S2_PICO board definition files
- boards/ESP32_S2_WROVER: link to specific deploy_s2 instructions
- support building with latest IDF v5
- in machine_i2s, send null samples in underflow situations
- in machine_i2s, make object reference arrays root pointers
- add SDCard support for S3, and a GENERIC_S3_SPIRAM board
- boards/GENERIC_S3: enable BLE on ESP32 S3
- machine_pwm: implement duty_u16() and duty_ns() PWM methods
- extract qstr from object when comparing keys in config()
- machine_pin: make GPIO 26 usable for S2,S3 if SPIRAM not config'd
- machine_hw_spi: fix SPI default pins reordering on ESP32-S2/S3
- machine_hw_spi: set proper default SPI(id=1) pins on S2,S3 and C3
- machine_hw_spi: set proper default SPI(id=2) pins on S2 and S3
- boards: remove SPI pin defaults from GENERIC S2/S3 boards
- modnetwork: synchronize WiFi AUTH_xxx constants with IDF values
- machine_pwm: keep duty constant when changing frequency
- machine_bitstream: replace bit-bang code with RMT-based driver
- machine_i2s: add support for ESP-IDF 4.4
- machine_bitstream: fix signal duplication on output pins
- esp32: enable platform module with IDF version
- boards/GENERIC_D2WD: build with -Os optimisation
- esp32_rmt: install RMT driver on core 1
- machine_bitstream: reinstate bitstream bit-bang implementation
javascript port: no changes specific to this component/port
mimxrt port:
- sdcard: implement SDCard driver
- machine_bitstream: add bitstream function to machine module
- rework flash configuration
- sdram: add SDRAM support
- eth: add LAN support and integrate the network module
- modmachine: implement machine.WDT() and machine.reset_cause()
- boards: fix the D14/D15 pin assignment of MIMXRT1050/60/64_EVK
- hal: remove duplicate definitions from flexspi_hyper_flash.h
- dma_channel: fix the DMA channel management
- fix cycle counter for time.ticks_cpu() and machine.bitstream()
- add dht_readinto() to the mimxrt module, and freeze dht.py
- extend the help() message and README.md
- mpconfigport.h: enable f-strings
- modmachine: implement soft_reset() and unique_id() functions
- boards/make-pins.py: allow empty lines and comments in pins.csv
- optimize the runtime speed
- enable the platform module
- boards: add the Seeed ARCH MIX board
- boards: update the board.json files and add deploy_xx.md files
- fix mp_hal_quiet_timing_enter()/exit() so timer still runs
- support PWM using the FLEXPWM and QTMR modules
- define UART 0 on MIMXRT boards
- support selection of PHY type and address
- re-enable eth checksum creation by HW
- fix a tiny unnoticed bug in sdcard.c
- add a driver for the DP83848 PHY device
- refactor the reading of the machine id
- enable ticks_cpu at boot time for NDEBUG builds only
- use -Og instead of -O0 for DEBUG builds
- tidy up the board flash related files
- hal: allow readSampleClkSrc to be configured by a board
- enable MICROPY_PY_USSL_FINALISER
minimal port:
- mpconfigport.h: use MICROPY_CONFIG_ROM_LEVEL_MINIMUM
- Makefile: don't force a 32-bit build
- mpconfigport.h: disable features that are not needed
nrf port:
- Makefile: improve Black Magic Probe commands
- main: use VFS helper function to mount fs and chdir
pic16bit port: no changes specific to this component/port
powerpc port: no changes specific to this component/port
qemu-arm port: no changes specific to this component/port
rp2 port:
- mpconfigport.h: enable heapq module
- add support for bluetooth module using NimBLE
- add framework for networking
- mpconfigport.h: use the "extra" feature level
- enable optimisations (comp goto, map cache, fast attr)
- machine_i2s: add I2S protocol support
- add support for Nina-W10 WiFi/BT module
- boards: add support for Arduino Nano RP2040
- machine_bitstream: implement the machine.bitstream driver
- boards: add neopixel.py to manifest.py
- rp2_pio: support exec with sideset
- boards/PIMORONI_PICOLIPO_16MB: fix 16MB flash size
- boards: add PYBSTICK26 RP2040 board definition
- machine_uart: handle and clear UART RX timeout IRQ
- boards/ARDUINO_NANO_RP2040_CONNECT: set default I2C pins
- machine_pwm: fix PWM frequency setting
- machine_pwm: keep duty value when changing the frequency
- add support for DHT11 and DHT22 sensors
- CMakeLists.txt: allow a board to override PICO_BOARD
- boards/GARATRONIC_PYBSTICK26_RP2040: use correct pico-sdk board cfg
samd port:
- integrate latest asf4, add help, more time funcs and uPy features
- samd_soc: allow a board to configure the low-level MCU config
- add internal flash block device, filesystem and uos support
- add Pin and LED classes, and machine.unique_id
- boards/ADAFRUIT_FEATHER_M0_EXPRESS: update for flash and pins
- boards/ADAFRUIT_ITSYBITSY_M4_EXPRESS: update for flash and pins
- boards/MINISAM_M4: update for flash and pins
- boards/ADAFRUIT_TRINKET_M0: update for flash and pins
- boards/SAMD21_XPLAINED_PRO: update for flash and pins
- boards/SEEED_WIO_TERMINAL: add new board definition
- boards/SEEED_XIAO: add new board definition
- README.md: update README to reflect new features and boards
stm32 port:
- pin: enable GPIO clock of pin if it's constructed without init
- main: don't unconditionally enable GPIO A,B,C,D clocks
- boards/VCC_GND_H743VI: add board definition for VCC_GND_H743VI
- boards/OLIMEX_E407: add Ethernet RMII support
- boards/LEGO_HUB_NO6: remove user paths from cc2564 init file
- boards: remove trailing spaces, and add newline at end of file
- add basic support for STM32H750
- add support for H7A3(Q)/H7B3(Q), and STM32H73B3I_DK board defn
- suggest putting code in main.py not boot.py
- boards/make-pins.py: allow a CPU pin to be hidden
- boards/make-pins.py: allow empty lines and comments in pins.csv
- dma: add functions for external users of DMA to enable clock
- enable LOAD_ATTR fast path, and map lookup caching on >M0
- boards: add OLIMEX H407 board definition
- enable platform module
- extended flash filesystem space to 512K on H743 boards
- boards/NUCLEO_H743ZI: enable VfsLfs2 on NUCLEO_H743ZI(2) boards
- boards: add PF11-BOOT0 to stm32f091_af.csv
- machine_i2c: use hardware I2C for STM32H7
- sdram: enforce gcc opt, and use volatile and DSB in sdram_test
- usbd_cdc_interface: allow a board to hook into USBD CDC RX events
- mpbthciport: allow a board to hook BT HCI poll functions
- pendsv: allow a board to add entries for pendsv_schedule_dispatch
- boards: add images to board.json for Adafruit and VCC_GND boards
- uart: fix race conditions and clearing status in IRQ handler
- mpconfigport.h: use the "extra" feature level
- in machine_i2s, send null samples in underflow situations
- in machine_i2s, make object reference arrays root pointers
- led: support an extra 2 LEDs in board configuration
- boards/MIKROE_CLICKER2_STM32: add more detail to board.json
- boards: add new board MikroElektronika Quail, and F427 support
- main: run optional frozen module at boot
- sdio: don't explicitly disable DMA2 on deinit of SDIO
- dma: make DMA2_Stream3 exclusive to SDIO when CYW43 enabled
- boards: build NUCLEO_WB55 and STM32F769DISC without mboot enabled
- boards: add PYBSTICK26 F411 board definition
- boards/NADHAT_PYBF405: rename board to GARATRONIC_NADHAT_F405
- usb: use a table of allowed values to simplify usb_mode get/set
- boards/NUCLEO_WB55: update rfcore_firmwre for new WS
- flashbdev: support generic flash storage config via link symbols
- boards: convert F413,F439,H743,L4xx,WB55 to new flash FS config
- add support for F479 MCUs
- include HAL MMC code in F4 builds
- boards/make-pins.py: use cpu pins to define static alt-fun macros
- boards/NUCLEO_WB55: fix LED ordering
- boards/LEGO_HUB_NO6: set filesystem label as HUB_NO6
- boards: remove stray '+' characters at start of lines in ld files
- boards: remove unused MICROPY_HW_ENABLE_TIMER config
- boards: enable MICROPY_HW_ENABLE_SERVO on various boards
- update L4 code to build with latest stm32lib and L4 HAL 1.17.0
- main: call sdcard_init when only MICROPY_HW_ENABLE_MMCARD enabled
- sdcard: support 8-bit wide SDIO bus
- sdcard: add config option to force MM card capacity
- factoryreset: init vfs flags before calling pyb_flash_init_vfs
- qspi: fix typo in address comment
- boards/make-pins.py: generate empty ADC table if needed
- boards/OLIMEX_H407: fix typo in OLIMEX H407 board.json
- network_wiznet5k: fix build error with wiznet5k and lwip enabled
- enable MICROPY_PY_USSL_FINALISER
teensy port:
- switch to use manifest.py instead of FROZEN_DIR
unix port:
- enable LOAD_ATTR fast path, and map lookup caching
- modusocket: support MP_STREAM_POLL in unix socket_ioctl
- modos: add support for uos.urandom(n)
- coverage: change remaining printf to mp_printf
- Makefile: use -Og instead of -O0 for debug builds
windows port:
- README: remove unsupported Python instructions for Cygwin
- mpconfigport.h: enable help and help("modules")
- add support for build variants to windows port
- run tests via Makefile
- appveyor: build both standard and dev variants
- appveyor: build mpy-cross only once for mingw-w64
- msvc: run qstr preprocessing phase in parallel
zephyr port:
- mphalport.h: remove unused and unimplemented C-level pin API
- increase minimum CMake version to 3.20.0
- update include path to reboot.h
- get UART console device from devicetree instead of Kconfig
- use CONFIG_USB_DEVICE_STACK for conditional USB device support
- upgrade to Zephyr v2.7.0
- modbluetooth_zephyr: provide dummy connect_cancel function
1019 lines
35 KiB
Python
Executable File
1019 lines
35 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
|
|
# SPDX-FileCopyrightText: Copyright (c) 2016-2019 Damien P. George
|
|
# SPDX-FileCopyrightText: 2014 MicroPython & CircuitPython contributors (https://github.com/adafruit/circuitpython/graphs/contributors)
|
|
#
|
|
# SPDX-License-Identifier: MIT
|
|
|
|
# Python 2/3 compatibility code
|
|
from __future__ import print_function
|
|
import platform
|
|
|
|
if platform.python_version_tuple()[0] == "2":
|
|
str_cons = lambda val, enc=None: val
|
|
bytes_cons = lambda val, enc=None: bytearray(val)
|
|
is_str_type = lambda o: type(o) is str
|
|
is_bytes_type = lambda o: type(o) is bytearray
|
|
is_int_type = lambda o: type(o) is int or type(o) is long
|
|
else:
|
|
str_cons = str
|
|
bytes_cons = bytes
|
|
is_str_type = lambda o: type(o) is str
|
|
is_bytes_type = lambda o: type(o) is bytes
|
|
is_int_type = lambda o: type(o) is int
|
|
# end compatibility code
|
|
|
|
import sys
|
|
import struct
|
|
from collections import namedtuple
|
|
|
|
sys.path.append(sys.path[0] + "/../py")
|
|
import makeqstrdata as qstrutil
|
|
|
|
|
|
class FreezeError(Exception):
|
|
def __init__(self, rawcode, msg):
|
|
self.rawcode = rawcode
|
|
self.msg = msg
|
|
|
|
def __str__(self):
|
|
return "error while freezing %s: %s" % (self.rawcode.source_file, self.msg)
|
|
|
|
|
|
class Config:
|
|
MPY_VERSION = 5
|
|
MICROPY_LONGINT_IMPL_NONE = 0
|
|
MICROPY_LONGINT_IMPL_LONGLONG = 1
|
|
MICROPY_LONGINT_IMPL_MPZ = 2
|
|
|
|
|
|
config = Config()
|
|
|
|
|
|
class QStrType:
|
|
def __init__(self, str):
|
|
self.str = str
|
|
self.qstr_esc = qstrutil.qstr_escape(self.str)
|
|
self.qstr_id = "MP_QSTR_" + self.qstr_esc
|
|
|
|
|
|
# Initialise global list of qstrs with static qstrs
|
|
global_qstrs = [None] # MP_QSTRnull should never be referenced
|
|
for n in qstrutil.static_qstr_list:
|
|
global_qstrs.append(QStrType(n))
|
|
|
|
|
|
class QStrWindow:
|
|
def __init__(self, size):
|
|
self.window = []
|
|
self.size = size
|
|
|
|
def push(self, val):
|
|
self.window = [val] + self.window[: self.size - 1]
|
|
|
|
def access(self, idx):
|
|
val = self.window[idx]
|
|
self.window = [val] + self.window[:idx] + self.window[idx + 1 :]
|
|
return val
|
|
|
|
|
|
MP_CODE_BYTECODE = 2
|
|
MP_CODE_NATIVE_PY = 3
|
|
MP_CODE_NATIVE_VIPER = 4
|
|
MP_CODE_NATIVE_ASM = 5
|
|
|
|
MP_NATIVE_ARCH_NONE = 0
|
|
MP_NATIVE_ARCH_X86 = 1
|
|
MP_NATIVE_ARCH_X64 = 2
|
|
MP_NATIVE_ARCH_ARMV6 = 3
|
|
MP_NATIVE_ARCH_ARMV6M = 4
|
|
MP_NATIVE_ARCH_ARMV7M = 5
|
|
MP_NATIVE_ARCH_ARMV7EM = 6
|
|
MP_NATIVE_ARCH_ARMV7EMSP = 7
|
|
MP_NATIVE_ARCH_ARMV7EMDP = 8
|
|
MP_NATIVE_ARCH_XTENSA = 9
|
|
MP_NATIVE_ARCH_XTENSAWIN = 10
|
|
|
|
MP_BC_MASK_EXTRA_BYTE = 0x9E
|
|
|
|
MP_BC_FORMAT_BYTE = 0
|
|
MP_BC_FORMAT_QSTR = 1
|
|
MP_BC_FORMAT_VAR_UINT = 2
|
|
MP_BC_FORMAT_OFFSET = 3
|
|
|
|
# extra byte if caching enabled:
|
|
MP_BC_LOAD_NAME = 0x11
|
|
MP_BC_LOAD_GLOBAL = 0x12
|
|
MP_BC_LOAD_ATTR = 0x13
|
|
MP_BC_STORE_ATTR = 0x18
|
|
|
|
# this function mirrors that in py/bc.c
|
|
def mp_opcode_format(bytecode, ip, count_var_uint):
|
|
opcode = bytecode[ip]
|
|
ip_start = ip
|
|
f = (0x000003A4 >> (2 * ((opcode) >> 4))) & 3
|
|
if f == MP_BC_FORMAT_QSTR:
|
|
ip += 3
|
|
else:
|
|
extra_byte = (opcode & MP_BC_MASK_EXTRA_BYTE) == 0
|
|
ip += 1
|
|
if f == MP_BC_FORMAT_VAR_UINT:
|
|
if count_var_uint:
|
|
while bytecode[ip] & 0x80 != 0:
|
|
ip += 1
|
|
ip += 1
|
|
elif f == MP_BC_FORMAT_OFFSET:
|
|
ip += 2
|
|
ip += extra_byte
|
|
return f, ip - ip_start
|
|
|
|
|
|
def read_prelude_sig(read_byte):
|
|
z = read_byte()
|
|
# xSSSSEAA
|
|
S = (z >> 3) & 0xF
|
|
E = (z >> 2) & 0x1
|
|
F = 0
|
|
A = z & 0x3
|
|
K = 0
|
|
D = 0
|
|
n = 0
|
|
while z & 0x80:
|
|
z = read_byte()
|
|
# xFSSKAED
|
|
S |= (z & 0x30) << (2 * n)
|
|
E |= (z & 0x02) << n
|
|
F |= ((z & 0x40) >> 6) << n
|
|
A |= (z & 0x4) << n
|
|
K |= ((z & 0x08) >> 3) << n
|
|
D |= (z & 0x1) << n
|
|
n += 1
|
|
S += 1
|
|
return S, E, F, A, K, D
|
|
|
|
|
|
def read_prelude_size(read_byte):
|
|
I = 0
|
|
C = 0
|
|
n = 0
|
|
while True:
|
|
z = read_byte()
|
|
# xIIIIIIC
|
|
I |= ((z & 0x7E) >> 1) << (6 * n)
|
|
C |= (z & 1) << n
|
|
if not (z & 0x80):
|
|
break
|
|
n += 1
|
|
return I, C
|
|
|
|
|
|
def extract_prelude(bytecode, ip):
|
|
def local_read_byte():
|
|
b = bytecode[ip_ref[0]]
|
|
ip_ref[0] += 1
|
|
return b
|
|
|
|
ip_ref = [ip] # to close over ip in Python 2 and 3
|
|
(
|
|
n_state,
|
|
n_exc_stack,
|
|
scope_flags,
|
|
n_pos_args,
|
|
n_kwonly_args,
|
|
n_def_pos_args,
|
|
) = read_prelude_sig(local_read_byte)
|
|
n_info, n_cell = read_prelude_size(local_read_byte)
|
|
ip = ip_ref[0]
|
|
|
|
ip2 = ip
|
|
ip = ip2 + n_info + n_cell
|
|
# ip now points to first opcode
|
|
# ip2 points to simple_name qstr
|
|
return ip, ip2, (n_state, n_exc_stack, scope_flags, n_pos_args, n_kwonly_args, n_def_pos_args)
|
|
|
|
|
|
class MPFunTable:
|
|
pass
|
|
|
|
|
|
class RawCode(object):
|
|
# a set of all escaped names, to make sure they are unique
|
|
escaped_names = set()
|
|
|
|
# convert code kind number to string
|
|
code_kind_str = {
|
|
MP_CODE_BYTECODE: "MP_CODE_BYTECODE",
|
|
MP_CODE_NATIVE_PY: "MP_CODE_NATIVE_PY",
|
|
MP_CODE_NATIVE_VIPER: "MP_CODE_NATIVE_VIPER",
|
|
MP_CODE_NATIVE_ASM: "MP_CODE_NATIVE_ASM",
|
|
}
|
|
|
|
def __init__(self, code_kind, bytecode, prelude_offset, qstrs, objs, raw_codes):
|
|
# set core variables
|
|
self.code_kind = code_kind
|
|
self.bytecode = bytecode
|
|
self.prelude_offset = prelude_offset
|
|
self.qstrs = qstrs
|
|
self.objs = objs
|
|
self.raw_codes = raw_codes
|
|
|
|
if self.prelude_offset is None:
|
|
# no prelude, assign a dummy simple_name
|
|
self.prelude_offset = 0
|
|
self.simple_name = global_qstrs[1]
|
|
else:
|
|
# extract prelude
|
|
self.ip, self.ip2, self.prelude = extract_prelude(self.bytecode, self.prelude_offset)
|
|
self.simple_name = self._unpack_qstr(self.ip2)
|
|
self.source_file = self._unpack_qstr(self.ip2 + 2)
|
|
self.line_info_offset = self.ip2 + 4
|
|
|
|
def _unpack_qstr(self, ip):
|
|
qst = self.bytecode[ip] | self.bytecode[ip + 1] << 8
|
|
return global_qstrs[qst]
|
|
|
|
def dump(self):
|
|
# dump children first
|
|
for rc in self.raw_codes:
|
|
rc.freeze("")
|
|
# TODO
|
|
|
|
def freeze_children(self, parent_name):
|
|
self.escaped_name = parent_name + self.simple_name.qstr_esc
|
|
|
|
# make sure the escaped name is unique
|
|
i = 2
|
|
while self.escaped_name in RawCode.escaped_names:
|
|
self.escaped_name = parent_name + self.simple_name.qstr_esc + str(i)
|
|
i += 1
|
|
RawCode.escaped_names.add(self.escaped_name)
|
|
|
|
# emit children first
|
|
for rc in self.raw_codes:
|
|
rc.freeze(self.escaped_name + "_")
|
|
|
|
def freeze_constants(self):
|
|
# generate constant objects
|
|
for i, obj in enumerate(self.objs):
|
|
obj_name = "const_obj_%s_%u" % (self.escaped_name, i)
|
|
if obj is MPFunTable:
|
|
pass
|
|
elif obj is Ellipsis:
|
|
print("#define %s mp_const_ellipsis_obj" % obj_name)
|
|
elif is_str_type(obj) or is_bytes_type(obj):
|
|
if is_str_type(obj):
|
|
obj = bytes_cons(obj, "utf8")
|
|
obj_type = "mp_type_str"
|
|
else:
|
|
obj_type = "mp_type_bytes"
|
|
print(
|
|
'STATIC const mp_obj_str_t %s = {{&%s}, %u, %u, (const byte*)"%s"};'
|
|
% (
|
|
obj_name,
|
|
obj_type,
|
|
qstrutil.compute_hash(obj, config.MICROPY_QSTR_BYTES_IN_HASH),
|
|
len(obj),
|
|
"".join(("\\x%02x" % b) for b in obj),
|
|
)
|
|
)
|
|
elif is_int_type(obj):
|
|
if config.MICROPY_LONGINT_IMPL == config.MICROPY_LONGINT_IMPL_NONE:
|
|
# TODO check if we can actually fit this long-int into a small-int
|
|
raise FreezeError(self, "target does not support long int")
|
|
elif config.MICROPY_LONGINT_IMPL == config.MICROPY_LONGINT_IMPL_LONGLONG:
|
|
# TODO
|
|
raise FreezeError(self, "freezing int to long-long is not implemented")
|
|
elif config.MICROPY_LONGINT_IMPL == config.MICROPY_LONGINT_IMPL_MPZ:
|
|
neg = 0
|
|
if obj < 0:
|
|
obj = -obj
|
|
neg = 1
|
|
bits_per_dig = config.MPZ_DIG_SIZE
|
|
digs = []
|
|
z = obj
|
|
while z:
|
|
digs.append(z & ((1 << bits_per_dig) - 1))
|
|
z >>= bits_per_dig
|
|
ndigs = len(digs)
|
|
digs = ",".join(("%#x" % d) for d in digs)
|
|
print(
|
|
"STATIC const mp_obj_int_t %s = {{&mp_type_int}, "
|
|
"{.neg=%u, .fixed_dig=1, .alloc=%u, .len=%u, .dig=(uint%u_t*)(const uint%u_t[]){%s}}};"
|
|
% (obj_name, neg, ndigs, ndigs, bits_per_dig, bits_per_dig, digs)
|
|
)
|
|
elif type(obj) is float:
|
|
print(
|
|
"#if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_A || MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_B"
|
|
)
|
|
print(
|
|
"STATIC const mp_obj_float_t %s = {{&mp_type_float}, (mp_float_t)%.16g};"
|
|
% (obj_name, obj)
|
|
)
|
|
print("#endif")
|
|
elif type(obj) is complex:
|
|
print(
|
|
"STATIC const mp_obj_complex_t %s = {{&mp_type_complex}, (mp_float_t)%.16g, (mp_float_t)%.16g};"
|
|
% (obj_name, obj.real, obj.imag)
|
|
)
|
|
else:
|
|
raise FreezeError(self, "freezing of object %r is not implemented" % (obj,))
|
|
|
|
# generate constant table, if it has any entries
|
|
const_table_len = len(self.qstrs) + len(self.objs) + len(self.raw_codes)
|
|
if const_table_len:
|
|
print(
|
|
"STATIC const mp_rom_obj_t const_table_data_%s[%u] = {"
|
|
% (self.escaped_name, const_table_len)
|
|
)
|
|
for qst in self.qstrs:
|
|
print(" MP_ROM_QSTR(%s)," % global_qstrs[qst].qstr_id)
|
|
for i in range(len(self.objs)):
|
|
if self.objs[i] is MPFunTable:
|
|
print(" &mp_fun_table,")
|
|
elif type(self.objs[i]) is float:
|
|
print(
|
|
"#if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_A || MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_B"
|
|
)
|
|
print(" MP_ROM_PTR(&const_obj_%s_%u)," % (self.escaped_name, i))
|
|
print("#elif MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_C")
|
|
n = struct.unpack("<I", struct.pack("<f", self.objs[i]))[0]
|
|
n = ((n & ~0x3) | 2) + 0x80800000
|
|
print(" (mp_rom_obj_t)(0x%08x)," % (n,))
|
|
print("#elif MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_D")
|
|
n = struct.unpack("<Q", struct.pack("<d", self.objs[i]))[0]
|
|
n += 0x8004000000000000
|
|
print(" (mp_rom_obj_t)(0x%016x)," % (n,))
|
|
print("#endif")
|
|
else:
|
|
print(" MP_ROM_PTR(&const_obj_%s_%u)," % (self.escaped_name, i))
|
|
for rc in self.raw_codes:
|
|
print(" MP_ROM_PTR(&raw_code_%s)," % rc.escaped_name)
|
|
print("};")
|
|
|
|
def freeze_module(self, qstr_links=(), type_sig=0):
|
|
# generate module
|
|
if self.simple_name.str != "<module>":
|
|
print("STATIC ", end="")
|
|
print("const mp_raw_code_t raw_code_%s = {" % self.escaped_name)
|
|
print(" .kind = %s," % RawCode.code_kind_str[self.code_kind])
|
|
print(" .scope_flags = 0x%02x," % self.prelude[2])
|
|
print(" .n_pos_args = %u," % self.prelude[3])
|
|
print(" .fun_data = fun_data_%s," % self.escaped_name)
|
|
if len(self.qstrs) + len(self.objs) + len(self.raw_codes):
|
|
print(" .const_table = (mp_uint_t*)const_table_data_%s," % self.escaped_name)
|
|
else:
|
|
print(" .const_table = NULL,")
|
|
print(" #if MICROPY_PERSISTENT_CODE_SAVE")
|
|
print(" .fun_data_len = %u," % len(self.bytecode))
|
|
print(" .n_obj = %u," % len(self.objs))
|
|
print(" .n_raw_code = %u," % len(self.raw_codes))
|
|
if self.code_kind == MP_CODE_BYTECODE:
|
|
print(" #if MICROPY_PY_SYS_SETTRACE")
|
|
print(" .prelude = {")
|
|
print(" .n_state = %u," % self.prelude[0])
|
|
print(" .n_exc_stack = %u," % self.prelude[1])
|
|
print(" .scope_flags = %u," % self.prelude[2])
|
|
print(" .n_pos_args = %u," % self.prelude[3])
|
|
print(" .n_kwonly_args = %u," % self.prelude[4])
|
|
print(" .n_def_pos_args = %u," % self.prelude[5])
|
|
print(" .qstr_block_name = %s," % self.simple_name.qstr_id)
|
|
print(" .qstr_source_file = %s," % self.source_file.qstr_id)
|
|
print(
|
|
" .line_info = fun_data_%s + %u,"
|
|
% (self.escaped_name, self.line_info_offset)
|
|
)
|
|
print(" .opcodes = fun_data_%s + %u," % (self.escaped_name, self.ip))
|
|
print(" },")
|
|
print(" .line_of_definition = %u," % 0) # TODO
|
|
print(" #endif")
|
|
print(" #if MICROPY_EMIT_MACHINE_CODE")
|
|
print(" .prelude_offset = %u," % self.prelude_offset)
|
|
print(" .n_qstr = %u," % len(qstr_links))
|
|
print(" .qstr_link = NULL,") # TODO
|
|
print(" #endif")
|
|
print(" #endif")
|
|
print(" #if MICROPY_EMIT_MACHINE_CODE")
|
|
print(" .type_sig = %u," % type_sig)
|
|
print(" #endif")
|
|
print("};")
|
|
|
|
|
|
class RawCodeBytecode(RawCode):
|
|
def __init__(self, bytecode, qstrs, objs, raw_codes):
|
|
super(RawCodeBytecode, self).__init__(
|
|
MP_CODE_BYTECODE, bytecode, 0, qstrs, objs, raw_codes
|
|
)
|
|
|
|
def freeze(self, parent_name):
|
|
self.freeze_children(parent_name)
|
|
|
|
# generate bytecode data
|
|
print()
|
|
print(
|
|
"// frozen bytecode for file %s, scope %s%s"
|
|
% (self.source_file.str, parent_name, self.simple_name.str)
|
|
)
|
|
print("STATIC const byte fun_data_%s[%u] = {" % (self.escaped_name, len(self.bytecode)))
|
|
print(" ", end="")
|
|
for i in range(self.ip2):
|
|
print(" 0x%02x," % self.bytecode[i], end="")
|
|
print()
|
|
print(" ", self.simple_name.qstr_id, "& 0xff,", self.simple_name.qstr_id, ">> 8,")
|
|
print(" ", self.source_file.qstr_id, "& 0xff,", self.source_file.qstr_id, ">> 8,")
|
|
print(" ", end="")
|
|
for i in range(self.ip2 + 4, self.ip):
|
|
print(" 0x%02x," % self.bytecode[i], end="")
|
|
print()
|
|
ip = self.ip
|
|
while ip < len(self.bytecode):
|
|
f, sz = mp_opcode_format(self.bytecode, ip, True)
|
|
if f == 1:
|
|
qst = self._unpack_qstr(ip + 1).qstr_id
|
|
extra = "" if sz == 3 else " 0x%02x," % self.bytecode[ip + 3]
|
|
print(" ", "0x%02x," % self.bytecode[ip], qst, "& 0xff,", qst, ">> 8,", extra)
|
|
else:
|
|
print(" ", "".join("0x%02x, " % self.bytecode[ip + i] for i in range(sz)))
|
|
ip += sz
|
|
print("};")
|
|
|
|
self.freeze_constants()
|
|
self.freeze_module()
|
|
|
|
|
|
class RawCodeNative(RawCode):
|
|
def __init__(
|
|
self,
|
|
code_kind,
|
|
fun_data,
|
|
prelude_offset,
|
|
prelude,
|
|
qstr_links,
|
|
qstrs,
|
|
objs,
|
|
raw_codes,
|
|
type_sig,
|
|
):
|
|
super(RawCodeNative, self).__init__(
|
|
code_kind, fun_data, prelude_offset, qstrs, objs, raw_codes
|
|
)
|
|
self.prelude = prelude
|
|
self.qstr_links = qstr_links
|
|
self.type_sig = type_sig
|
|
if config.native_arch in (
|
|
MP_NATIVE_ARCH_X86,
|
|
MP_NATIVE_ARCH_X64,
|
|
MP_NATIVE_ARCH_XTENSA,
|
|
MP_NATIVE_ARCH_XTENSAWIN,
|
|
):
|
|
self.fun_data_attributes = '__attribute__((section(".text,\\"ax\\",@progbits # ")))'
|
|
else:
|
|
self.fun_data_attributes = '__attribute__((section(".text,\\"ax\\",%progbits @ ")))'
|
|
|
|
# Allow single-byte alignment by default for x86/x64.
|
|
# ARM needs word alignment, ARM Thumb needs halfword, due to instruction size.
|
|
# Xtensa needs word alignment due to the 32-bit constant table embedded in the code.
|
|
if config.native_arch in (
|
|
MP_NATIVE_ARCH_ARMV6,
|
|
MP_NATIVE_ARCH_XTENSA,
|
|
MP_NATIVE_ARCH_XTENSAWIN,
|
|
):
|
|
# ARMV6 or Xtensa -- four byte align.
|
|
self.fun_data_attributes += " __attribute__ ((aligned (4)))"
|
|
elif MP_NATIVE_ARCH_ARMV6M <= config.native_arch <= MP_NATIVE_ARCH_ARMV7EMDP:
|
|
# ARMVxxM -- two byte align.
|
|
self.fun_data_attributes += " __attribute__ ((aligned (2)))"
|
|
|
|
def _asm_thumb_rewrite_mov(self, pc, val):
|
|
print(" (%u & 0xf0) | (%s >> 12)," % (self.bytecode[pc], val), end="")
|
|
print(" (%u & 0xfb) | (%s >> 9 & 0x04)," % (self.bytecode[pc + 1], val), end="")
|
|
print(" (%s & 0xff)," % (val,), end="")
|
|
print(" (%u & 0x07) | (%s >> 4 & 0x70)," % (self.bytecode[pc + 3], val))
|
|
|
|
def _link_qstr(self, pc, kind, qst):
|
|
if kind == 0:
|
|
# Generic 16-bit link
|
|
print(" %s & 0xff, %s >> 8," % (qst, qst))
|
|
return 2
|
|
else:
|
|
# Architecture-specific link
|
|
is_obj = kind == 2
|
|
if is_obj:
|
|
qst = "((uintptr_t)MP_OBJ_NEW_QSTR(%s))" % qst
|
|
if config.native_arch in (
|
|
MP_NATIVE_ARCH_X86,
|
|
MP_NATIVE_ARCH_X64,
|
|
MP_NATIVE_ARCH_ARMV6,
|
|
MP_NATIVE_ARCH_XTENSA,
|
|
MP_NATIVE_ARCH_XTENSAWIN,
|
|
):
|
|
print(
|
|
" %s & 0xff, (%s >> 8) & 0xff, (%s >> 16) & 0xff, %s >> 24,"
|
|
% (qst, qst, qst, qst)
|
|
)
|
|
return 4
|
|
elif MP_NATIVE_ARCH_ARMV6M <= config.native_arch <= MP_NATIVE_ARCH_ARMV7EMDP:
|
|
if is_obj:
|
|
# qstr object, movw and movt
|
|
self._asm_thumb_rewrite_mov(pc, qst)
|
|
self._asm_thumb_rewrite_mov(pc + 4, "(%s >> 16)" % qst)
|
|
return 8
|
|
else:
|
|
# qstr number, movw instruction
|
|
self._asm_thumb_rewrite_mov(pc, qst)
|
|
return 4
|
|
else:
|
|
assert 0
|
|
|
|
def freeze(self, parent_name):
|
|
if self.prelude[2] & ~0x0F:
|
|
raise FreezeError("unable to freeze code with relocations")
|
|
|
|
self.freeze_children(parent_name)
|
|
|
|
# generate native code data
|
|
print()
|
|
if self.code_kind == MP_CODE_NATIVE_PY:
|
|
print(
|
|
"// frozen native code for file %s, scope %s%s"
|
|
% (self.source_file.str, parent_name, self.simple_name.str)
|
|
)
|
|
elif self.code_kind == MP_CODE_NATIVE_VIPER:
|
|
print("// frozen viper code for scope %s" % (parent_name,))
|
|
else:
|
|
print("// frozen assembler code for scope %s" % (parent_name,))
|
|
print(
|
|
"STATIC const byte fun_data_%s[%u] %s = {"
|
|
% (self.escaped_name, len(self.bytecode), self.fun_data_attributes)
|
|
)
|
|
|
|
if self.code_kind == MP_CODE_NATIVE_PY:
|
|
i_top = self.prelude_offset
|
|
else:
|
|
i_top = len(self.bytecode)
|
|
i = 0
|
|
qi = 0
|
|
while i < i_top:
|
|
if qi < len(self.qstr_links) and i == self.qstr_links[qi][0]:
|
|
# link qstr
|
|
qi_off, qi_kind, qi_val = self.qstr_links[qi]
|
|
qst = global_qstrs[qi_val].qstr_id
|
|
i += self._link_qstr(i, qi_kind, qst)
|
|
qi += 1
|
|
else:
|
|
# copy machine code (max 16 bytes)
|
|
i16 = min(i + 16, i_top)
|
|
if qi < len(self.qstr_links):
|
|
i16 = min(i16, self.qstr_links[qi][0])
|
|
print(" ", end="")
|
|
for ii in range(i, i16):
|
|
print(" 0x%02x," % self.bytecode[ii], end="")
|
|
print()
|
|
i = i16
|
|
|
|
if self.code_kind == MP_CODE_NATIVE_PY:
|
|
print(" ", end="")
|
|
for i in range(self.prelude_offset, self.ip2):
|
|
print(" 0x%02x," % self.bytecode[i], end="")
|
|
print()
|
|
|
|
print(" ", self.simple_name.qstr_id, "& 0xff,", self.simple_name.qstr_id, ">> 8,")
|
|
print(" ", self.source_file.qstr_id, "& 0xff,", self.source_file.qstr_id, ">> 8,")
|
|
|
|
print(" ", end="")
|
|
for i in range(self.ip2 + 4, self.ip):
|
|
print(" 0x%02x," % self.bytecode[i], end="")
|
|
print()
|
|
|
|
print("};")
|
|
|
|
self.freeze_constants()
|
|
self.freeze_module(self.qstr_links, self.type_sig)
|
|
|
|
|
|
class BytecodeBuffer:
|
|
def __init__(self, size):
|
|
self.buf = bytearray(size)
|
|
self.idx = 0
|
|
|
|
def is_full(self):
|
|
return self.idx == len(self.buf)
|
|
|
|
def append(self, b):
|
|
self.buf[self.idx] = b
|
|
self.idx += 1
|
|
|
|
|
|
def read_byte(f, out=None):
|
|
b = bytes_cons(f.read(1))[0]
|
|
if out is not None:
|
|
out.append(b)
|
|
return b
|
|
|
|
|
|
def read_uint(f, out=None):
|
|
i = 0
|
|
while True:
|
|
b = read_byte(f, out)
|
|
i = (i << 7) | (b & 0x7F)
|
|
if b & 0x80 == 0:
|
|
break
|
|
return i
|
|
|
|
|
|
def read_qstr(f, qstr_win):
|
|
ln = read_uint(f)
|
|
if ln == 0:
|
|
# static qstr
|
|
return bytes_cons(f.read(1))[0]
|
|
if ln & 1:
|
|
# qstr in table
|
|
return qstr_win.access(ln >> 1)
|
|
ln >>= 1
|
|
data = str_cons(f.read(ln), "utf8")
|
|
global_qstrs.append(QStrType(data))
|
|
qstr_win.push(len(global_qstrs) - 1)
|
|
return len(global_qstrs) - 1
|
|
|
|
|
|
def read_obj(f):
|
|
obj_type = f.read(1)
|
|
if obj_type == b"e":
|
|
return Ellipsis
|
|
else:
|
|
buf = f.read(read_uint(f))
|
|
if obj_type == b"s":
|
|
return str_cons(buf, "utf8")
|
|
elif obj_type == b"b":
|
|
return bytes_cons(buf)
|
|
elif obj_type == b"i":
|
|
return int(str_cons(buf, "ascii"), 10)
|
|
elif obj_type == b"f":
|
|
return float(str_cons(buf, "ascii"))
|
|
elif obj_type == b"c":
|
|
return complex(str_cons(buf, "ascii"))
|
|
else:
|
|
assert 0
|
|
|
|
|
|
def read_prelude(f, bytecode, qstr_win):
|
|
(
|
|
n_state,
|
|
n_exc_stack,
|
|
scope_flags,
|
|
n_pos_args,
|
|
n_kwonly_args,
|
|
n_def_pos_args,
|
|
) = read_prelude_sig(lambda: read_byte(f, bytecode))
|
|
n_info, n_cell = read_prelude_size(lambda: read_byte(f, bytecode))
|
|
read_qstr_and_pack(f, bytecode, qstr_win) # simple_name
|
|
read_qstr_and_pack(f, bytecode, qstr_win) # source_file
|
|
for _ in range(n_info - 4 + n_cell):
|
|
read_byte(f, bytecode)
|
|
return n_state, n_exc_stack, scope_flags, n_pos_args, n_kwonly_args, n_def_pos_args
|
|
|
|
|
|
def read_qstr_and_pack(f, bytecode, qstr_win):
|
|
qst = read_qstr(f, qstr_win)
|
|
bytecode.append(qst & 0xFF)
|
|
bytecode.append(qst >> 8)
|
|
|
|
|
|
def read_bytecode(file, bytecode, qstr_win):
|
|
while not bytecode.is_full():
|
|
op = read_byte(file, bytecode)
|
|
f, sz = mp_opcode_format(bytecode.buf, bytecode.idx - 1, False)
|
|
sz -= 1
|
|
if f == MP_BC_FORMAT_QSTR:
|
|
read_qstr_and_pack(file, bytecode, qstr_win)
|
|
sz -= 2
|
|
elif f == MP_BC_FORMAT_VAR_UINT:
|
|
while read_byte(file, bytecode) & 0x80:
|
|
pass
|
|
for _ in range(sz):
|
|
read_byte(file, bytecode)
|
|
|
|
|
|
def read_raw_code(f, qstr_win):
|
|
kind_len = read_uint(f)
|
|
kind = (kind_len & 3) + MP_CODE_BYTECODE
|
|
fun_data_len = kind_len >> 2
|
|
fun_data = BytecodeBuffer(fun_data_len)
|
|
|
|
if kind == MP_CODE_BYTECODE:
|
|
prelude = read_prelude(f, fun_data, qstr_win)
|
|
read_bytecode(f, fun_data, qstr_win)
|
|
else:
|
|
fun_data.buf[:] = f.read(fun_data_len)
|
|
|
|
qstr_links = []
|
|
if kind in (MP_CODE_NATIVE_PY, MP_CODE_NATIVE_VIPER):
|
|
# load qstr link table
|
|
n_qstr_link = read_uint(f)
|
|
for _ in range(n_qstr_link):
|
|
off = read_uint(f)
|
|
qst = read_qstr(f, qstr_win)
|
|
qstr_links.append((off >> 2, off & 3, qst))
|
|
|
|
type_sig = 0
|
|
if kind == MP_CODE_NATIVE_PY:
|
|
prelude_offset = read_uint(f)
|
|
_, name_idx, prelude = extract_prelude(fun_data.buf, prelude_offset)
|
|
fun_data.idx = name_idx # rewind to where qstrs are in prelude
|
|
read_qstr_and_pack(f, fun_data, qstr_win) # simple_name
|
|
read_qstr_and_pack(f, fun_data, qstr_win) # source_file
|
|
else:
|
|
prelude_offset = None
|
|
scope_flags = read_uint(f)
|
|
n_pos_args = 0
|
|
if kind == MP_CODE_NATIVE_ASM:
|
|
n_pos_args = read_uint(f)
|
|
type_sig = read_uint(f)
|
|
prelude = (None, None, scope_flags, n_pos_args, 0)
|
|
|
|
qstrs = []
|
|
objs = []
|
|
raw_codes = []
|
|
if kind != MP_CODE_NATIVE_ASM:
|
|
# load constant table
|
|
n_obj = read_uint(f)
|
|
n_raw_code = read_uint(f)
|
|
qstrs = [read_qstr(f, qstr_win) for _ in range(prelude[3] + prelude[4])]
|
|
if kind != MP_CODE_BYTECODE:
|
|
objs.append(MPFunTable)
|
|
objs.extend([read_obj(f) for _ in range(n_obj)])
|
|
raw_codes = [read_raw_code(f, qstr_win) for _ in range(n_raw_code)]
|
|
|
|
if kind == MP_CODE_BYTECODE:
|
|
return RawCodeBytecode(fun_data.buf, qstrs, objs, raw_codes)
|
|
else:
|
|
return RawCodeNative(
|
|
kind,
|
|
fun_data.buf,
|
|
prelude_offset,
|
|
prelude,
|
|
qstr_links,
|
|
qstrs,
|
|
objs,
|
|
raw_codes,
|
|
type_sig,
|
|
)
|
|
|
|
|
|
def read_mpy(filename):
|
|
with open(filename, "rb") as f:
|
|
header = bytes_cons(f.read(4))
|
|
if header[0] != ord("C"):
|
|
raise Exception("not a valid CircuitPython .mpy file")
|
|
if header[1] != config.MPY_VERSION:
|
|
raise Exception("incompatible .mpy version")
|
|
feature_byte = header[2]
|
|
qw_size = read_uint(f)
|
|
config.MICROPY_PY_BUILTINS_STR_UNICODE = (feature_byte & 2) != 0
|
|
mpy_native_arch = feature_byte >> 2
|
|
if mpy_native_arch != MP_NATIVE_ARCH_NONE:
|
|
if config.native_arch == MP_NATIVE_ARCH_NONE:
|
|
config.native_arch = mpy_native_arch
|
|
elif config.native_arch != mpy_native_arch:
|
|
raise Exception("native architecture mismatch")
|
|
config.mp_small_int_bits = header[3]
|
|
qstr_win = QStrWindow(qw_size)
|
|
rc = read_raw_code(f, qstr_win)
|
|
rc.mpy_source_file = filename
|
|
rc.qstr_win_size = qw_size
|
|
return rc
|
|
|
|
|
|
def dump_mpy(raw_codes):
|
|
for rc in raw_codes:
|
|
rc.dump()
|
|
|
|
|
|
def freeze_mpy(base_qstrs, raw_codes):
|
|
# add to qstrs
|
|
new = {}
|
|
for q in global_qstrs:
|
|
# don't add duplicates
|
|
if q is None or q.qstr_esc in base_qstrs or q.qstr_esc in new:
|
|
continue
|
|
new[q.qstr_esc] = (len(new), q.qstr_esc, q.str)
|
|
new = sorted(new.values(), key=lambda x: x[0])
|
|
|
|
print('#include "py/bc0.h"')
|
|
print('#include "py/mpconfig.h"')
|
|
print('#include "py/objint.h"')
|
|
print('#include "py/objstr.h"')
|
|
print('#include "py/emitglue.h"')
|
|
print('#include "py/nativeglue.h"')
|
|
print()
|
|
|
|
print("#if MICROPY_LONGINT_IMPL != %u" % config.MICROPY_LONGINT_IMPL)
|
|
print('#error "incompatible MICROPY_LONGINT_IMPL"')
|
|
print("#endif")
|
|
print()
|
|
|
|
if config.MICROPY_LONGINT_IMPL == config.MICROPY_LONGINT_IMPL_MPZ:
|
|
print("#if MPZ_DIG_SIZE != %u" % config.MPZ_DIG_SIZE)
|
|
print('#error "incompatible MPZ_DIG_SIZE"')
|
|
print("#endif")
|
|
print()
|
|
|
|
print("#if MICROPY_PY_BUILTINS_FLOAT")
|
|
print("typedef struct _mp_obj_float_t {")
|
|
print(" mp_obj_base_t base;")
|
|
print(" mp_float_t value;")
|
|
print("} mp_obj_float_t;")
|
|
print("#endif")
|
|
print()
|
|
|
|
print("#if MICROPY_PY_BUILTINS_COMPLEX")
|
|
print("typedef struct _mp_obj_complex_t {")
|
|
print(" mp_obj_base_t base;")
|
|
print(" mp_float_t real;")
|
|
print(" mp_float_t imag;")
|
|
print("} mp_obj_complex_t;")
|
|
print("#endif")
|
|
print()
|
|
|
|
if new:
|
|
print("enum {")
|
|
for i in range(len(new)):
|
|
if i == 0:
|
|
print(" MP_QSTR_%s = MP_QSTRnumber_of," % new[i][1])
|
|
else:
|
|
print(" MP_QSTR_%s," % new[i][1])
|
|
print("};")
|
|
|
|
print()
|
|
print("const qstr_attr_t mp_qstr_frozen_const_attr[] = {")
|
|
qstr_size = {"metadata": 0, "data": 0}
|
|
for _, _, qstr in new:
|
|
qbytes = qstrutil.bytes_cons(qstr, "utf8")
|
|
print(
|
|
" {%d, %d},"
|
|
% (qstrutil.compute_hash(qbytes, config.MICROPY_QSTR_BYTES_IN_HASH), len(qbytes))
|
|
)
|
|
qstr_size["metadata"] += (
|
|
config.MICROPY_QSTR_BYTES_IN_LEN + config.MICROPY_QSTR_BYTES_IN_HASH
|
|
)
|
|
qstr_size["data"] += len(qbytes)
|
|
print("};")
|
|
|
|
# As in qstr.c, set so that the first dynamically allocated pool is twice this size; must be <= the len
|
|
qstr_pool_alloc = min(len(new), 10)
|
|
|
|
print()
|
|
print("extern const qstr_pool_t mp_qstr_const_pool;")
|
|
print("const qstr_pool_t mp_qstr_frozen_const_pool = {")
|
|
print(" &mp_qstr_const_pool, // previous pool")
|
|
print(" MP_QSTRnumber_of, // previous pool size")
|
|
print(" %u, // allocated entries" % qstr_pool_alloc)
|
|
print(" %u, // used entries" % len(new))
|
|
print(" (qstr_attr_t *)mp_qstr_frozen_const_attr,")
|
|
print(" {")
|
|
for _, _, qstr in new:
|
|
print(' "%s",' % qstrutil.escape_bytes(qstr))
|
|
print(" },")
|
|
print("};")
|
|
|
|
for rc in raw_codes:
|
|
rc.freeze(rc.source_file.str.replace("/", "_")[:-3] + "_")
|
|
|
|
print()
|
|
print("const char mp_frozen_names[] = {")
|
|
print("#ifdef MP_FROZEN_STR_NAMES")
|
|
# makemanifest.py might also include some frozen string content.
|
|
print("MP_FROZEN_STR_NAMES")
|
|
print("#endif")
|
|
for rc in raw_codes:
|
|
module_name = rc.source_file.str
|
|
print('"%s\\0"' % module_name)
|
|
print('"\\0"};')
|
|
|
|
print("const mp_raw_code_t *const mp_frozen_mpy_content[] = {")
|
|
for rc in raw_codes:
|
|
print(" &raw_code_%s," % rc.escaped_name)
|
|
print("};")
|
|
|
|
# If a port defines MICROPY_FROZEN_LIST_ITEM then list all modules wrapped in that macro.
|
|
print("#ifdef MICROPY_FROZEN_LIST_ITEM")
|
|
for rc in raw_codes:
|
|
module_name = rc.source_file.str
|
|
if module_name.endswith("/__init__.py"):
|
|
short_name = module_name[: -len("/__init__.py")]
|
|
else:
|
|
short_name = module_name[: -len(".py")]
|
|
print('MICROPY_FROZEN_LIST_ITEM("%s", "%s")' % (short_name, module_name))
|
|
print("#endif")
|
|
|
|
|
|
def merge_mpy(raw_codes, output_file):
|
|
assert len(raw_codes) <= 31 # so var-uints all fit in 1 byte
|
|
merged_mpy = bytearray()
|
|
|
|
if len(raw_codes) == 1:
|
|
with open(raw_codes[0].mpy_source_file, "rb") as f:
|
|
merged_mpy.extend(f.read())
|
|
else:
|
|
header = bytearray(5)
|
|
header[0] = ord("C")
|
|
header[1] = config.MPY_VERSION
|
|
header[2] = config.native_arch << 2 | config.MICROPY_PY_BUILTINS_STR_UNICODE << 1
|
|
header[3] = config.mp_small_int_bits
|
|
header[4] = 32 # qstr_win_size
|
|
merged_mpy.extend(header)
|
|
|
|
bytecode = bytearray()
|
|
bytecode_len = 6 + len(raw_codes) * 5 + 2
|
|
bytecode.append(bytecode_len << 2) # kind and length
|
|
bytecode.append(0b00000000) # signature prelude
|
|
bytecode.append(0b00001000) # size prelude
|
|
bytecode.extend(b"\x00\x01") # MP_QSTR_
|
|
bytecode.extend(b"\x00\x01") # MP_QSTR_
|
|
for idx in range(len(raw_codes)):
|
|
bytecode.append(0x32) # MP_BC_MAKE_FUNCTION
|
|
bytecode.append(idx) # index raw code
|
|
bytecode.extend(b"\x34\x00\x59") # MP_BC_CALL_FUNCTION, 0 args, MP_BC_POP_TOP
|
|
bytecode.extend(b"\x51\x63") # MP_BC_LOAD_NONE, MP_BC_RETURN_VALUE
|
|
|
|
bytecode.append(0) # n_obj
|
|
bytecode.append(len(raw_codes)) # n_raw_code
|
|
|
|
merged_mpy.extend(bytecode)
|
|
|
|
for rc in raw_codes:
|
|
with open(rc.mpy_source_file, "rb") as f:
|
|
f.read(4) # skip header
|
|
read_uint(f) # skip qstr_win_size
|
|
data = f.read() # read rest of mpy file
|
|
merged_mpy.extend(data)
|
|
|
|
if output_file is None:
|
|
sys.stdout.buffer.write(merged_mpy)
|
|
else:
|
|
with open(output_file, "wb") as f:
|
|
f.write(merged_mpy)
|
|
|
|
|
|
def main():
|
|
import argparse
|
|
|
|
cmd_parser = argparse.ArgumentParser(description="A tool to work with MicroPython .mpy files.")
|
|
cmd_parser.add_argument("-d", "--dump", action="store_true", help="dump contents of files")
|
|
cmd_parser.add_argument("-f", "--freeze", action="store_true", help="freeze files")
|
|
cmd_parser.add_argument(
|
|
"--merge", action="store_true", help="merge multiple .mpy files into one"
|
|
)
|
|
cmd_parser.add_argument("-q", "--qstr-header", help="qstr header file to freeze against")
|
|
cmd_parser.add_argument(
|
|
"-mlongint-impl",
|
|
choices=["none", "longlong", "mpz"],
|
|
default="mpz",
|
|
help="long-int implementation used by target (default mpz)",
|
|
)
|
|
cmd_parser.add_argument(
|
|
"-mmpz-dig-size",
|
|
metavar="N",
|
|
type=int,
|
|
default=16,
|
|
help="mpz digit size used by target (default 16)",
|
|
)
|
|
cmd_parser.add_argument("-o", "--output", default=None, help="output file")
|
|
cmd_parser.add_argument("files", nargs="+", help="input .mpy files")
|
|
args = cmd_parser.parse_args()
|
|
|
|
# set config values relevant to target machine
|
|
config.MICROPY_LONGINT_IMPL = {
|
|
"none": config.MICROPY_LONGINT_IMPL_NONE,
|
|
"longlong": config.MICROPY_LONGINT_IMPL_LONGLONG,
|
|
"mpz": config.MICROPY_LONGINT_IMPL_MPZ,
|
|
}[args.mlongint_impl]
|
|
config.MPZ_DIG_SIZE = args.mmpz_dig_size
|
|
config.native_arch = MP_NATIVE_ARCH_NONE
|
|
|
|
# set config values for qstrs, and get the existing base set of qstrs
|
|
if args.qstr_header:
|
|
qcfgs, base_qstrs, _ = qstrutil.parse_input_headers([args.qstr_header])
|
|
config.MICROPY_QSTR_BYTES_IN_LEN = int(qcfgs["BYTES_IN_LEN"])
|
|
config.MICROPY_QSTR_BYTES_IN_HASH = int(qcfgs["BYTES_IN_HASH"])
|
|
else:
|
|
config.MICROPY_QSTR_BYTES_IN_LEN = 1
|
|
config.MICROPY_QSTR_BYTES_IN_HASH = 1
|
|
base_qstrs = {}
|
|
|
|
raw_codes = [read_mpy(file) for file in args.files]
|
|
|
|
if args.dump:
|
|
dump_mpy(raw_codes)
|
|
elif args.freeze:
|
|
try:
|
|
freeze_mpy(base_qstrs, raw_codes)
|
|
except FreezeError as er:
|
|
print(er, file=sys.stderr)
|
|
sys.exit(1)
|
|
elif args.merge:
|
|
merged_mpy = merge_mpy(raw_codes, args.output)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|