diff --git a/Makefile.boardloader b/Makefile.boardloader index 769404f9..0f6f88fe 100644 --- a/Makefile.boardloader +++ b/Makefile.boardloader @@ -77,6 +77,7 @@ OBJ_TREZORHAL += $(addprefix $(BUILD_FW)/, \ trezorhal/common.o \ trezorhal/image.o \ trezorhal/flash.o \ + trezorhal/mini_printf.o \ trezorhal/sdcard.o \ trezorhal/stm32_it.o \ trezorhal/stm32_system.o \ diff --git a/Makefile.bootloader b/Makefile.bootloader index 0a1af41b..ec312e36 100644 --- a/Makefile.bootloader +++ b/Makefile.bootloader @@ -86,6 +86,7 @@ OBJ_TREZORHAL += $(addprefix $(BUILD_FW)/, \ trezorhal/common.o \ trezorhal/image.o \ trezorhal/flash.o \ + trezorhal/mini_printf.o \ trezorhal/stm32_it.o \ trezorhal/stm32_system.o \ trezorhal/touch.o \ diff --git a/Makefile.firmware b/Makefile.firmware index ee4f4c60..e237b0e2 100644 --- a/Makefile.firmware +++ b/Makefile.firmware @@ -317,6 +317,7 @@ OBJ_FIRMWARE += $(addprefix $(BUILD_FW)/, \ OBJ_TREZORHAL += $(addprefix $(BUILD_FW)/, \ trezorhal/common.o \ trezorhal/flash.o \ + trezorhal/mini_printf.o \ trezorhal/rng.o \ trezorhal/sdcard.o \ trezorhal/stm32_it.o \ diff --git a/micropython/boardloader/main.c b/micropython/boardloader/main.c index c0d290c8..d8b6fe00 100644 --- a/micropython/boardloader/main.c +++ b/micropython/boardloader/main.c @@ -18,20 +18,20 @@ void pendsv_isr_handler(void) { bool check_sdcard(void) { - DPRINTLN("checking for SD card"); + display_printf("checking for SD card\n"); if (!sdcard_is_present()) { - DPRINTLN("no SD card found"); + display_printf("no SD card found\n"); return false; } - DPRINTLN("SD card found"); + display_printf("SD card found\n"); sdcard_power_on(); uint64_t cap = sdcard_get_capacity_in_bytes(); if (cap < 1024 * 1024) { - DPRINTLN("SD card too small"); + display_printf("SD card too small\n"); sdcard_power_off(); return false; } @@ -43,18 +43,17 @@ bool check_sdcard(void) sdcard_power_off(); if (image_parse_header((const uint8_t *)buf, IMAGE_MAGIC, IMAGE_MAXSIZE, NULL)) { - DPRINTLN("SD card header is valid"); + display_printf("SD card header is valid\n"); return true; } else { - DPRINTLN("SD card header is invalid"); + display_printf("SD card header is invalid\n"); return false; } } bool copy_sdcard(void) { - - DPRINT("erasing flash "); + display_printf("erasing flash "); // erase flash (except boardloader) HAL_FLASH_Unlock(); @@ -69,14 +68,14 @@ bool copy_sdcard(void) EraseInitStruct.Sector = i; if (HAL_FLASHEx_Erase(&EraseInitStruct, &SectorError) != HAL_OK) { HAL_FLASH_Lock(); - DPRINTLN(" failed"); + display_printf(" failed\n"); return false; } - DPRINT("."); + display_printf("."); } - DPRINTLN(" done"); + display_printf(" done\n"); - DPRINTLN("copying new bootloader from SD card"); + display_printf("copying new bootloader from SD card\n"); sdcard_power_on(); @@ -86,7 +85,7 @@ bool copy_sdcard(void) image_header hdr; if (!image_parse_header((const uint8_t *)buf, IMAGE_MAGIC, IMAGE_MAXSIZE, &hdr)) { - DPRINTLN("invalid header"); + display_printf("invalid header\n"); sdcard_power_off(); HAL_FLASH_Lock(); return false; @@ -96,7 +95,7 @@ bool copy_sdcard(void) sdcard_read_blocks((uint8_t *)buf, i, 1); for (int j = 0; j < SDCARD_BLOCK_SIZE / sizeof(uint32_t); j++) { if (HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, BOOTLOADER_START + i * SDCARD_BLOCK_SIZE + j * sizeof(uint32_t), buf[j]) != HAL_OK) { - DPRINTLN("copy failed"); + display_printf("copy failed\n"); sdcard_power_off(); HAL_FLASH_Lock(); return false; @@ -107,36 +106,36 @@ bool copy_sdcard(void) sdcard_power_off(); HAL_FLASH_Lock(); - DPRINTLN("done"); + display_printf("done\n"); return true; } void check_and_jump(void) { - DPRINTLN("checking bootloader"); + display_printf("checking bootloader\n"); image_header hdr; if (image_parse_header((const uint8_t *)BOOTLOADER_START, IMAGE_MAGIC, IMAGE_MAXSIZE, &hdr)) { - DPRINTLN("valid bootloader header"); + display_printf("valid bootloader header\n"); } else { - DPRINTLN("invalid bootloader header"); + display_printf("invalid bootloader header\n"); return; } if (image_check_signature((const uint8_t *)BOOTLOADER_START, &hdr, NULL)) { - DPRINTLN("valid bootloader signature"); + display_printf("valid bootloader signature\n"); // TODO: remove debug wait - DPRINTLN("waiting 1 second"); + display_printf("waiting 1 second\n"); HAL_Delay(1000); // end - DPRINTLN("JUMP!"); + display_printf("JUMP!\n"); jump_to(BOOTLOADER_START + HEADER_SIZE); } else { - DPRINTLN("invalid bootloader signature"); + display_printf("invalid bootloader signature\n"); } } @@ -160,9 +159,9 @@ int main(void) display_clear(); display_backlight(255); - DPRINTLN("TREZOR Boardloader " VERSION_STR); - DPRINTLN("=================="); - DPRINTLN("starting boardloader"); + display_printf("TREZOR Boardloader %d.%d.%d.%d\n", VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH, VERSION_BUILD); + display_printf("==================\n"); + display_printf("starting boardloader\n"); if (check_sdcard()) { if (!copy_sdcard()) { diff --git a/micropython/boardloader/version.h b/micropython/boardloader/version.h index cb1e4a09..a62341fe 100644 --- a/micropython/boardloader/version.h +++ b/micropython/boardloader/version.h @@ -2,8 +2,3 @@ #define VERSION_MINOR 1 #define VERSION_PATCH 0 #define VERSION_BUILD 0 - -#define STR_HELPER(X) #X -#define STRINGIZE(X) STR_HELPER(X) - -#define VERSION_STR STRINGIZE(VERSION_MAJOR) "." STRINGIZE(VERSION_MINOR) "." STRINGIZE(VERSION_PATCH) "." STRINGIZE(VERSION_BUILD) diff --git a/micropython/bootloader/main.c b/micropython/bootloader/main.c index 5a594463..da5c8120 100644 --- a/micropython/bootloader/main.c +++ b/micropython/bootloader/main.c @@ -11,6 +11,7 @@ #include "touch.h" #include "usb.h" #include "version.h" +#include "mini_printf.h" #include "messages.h" #include "protobuf.h" @@ -36,55 +37,56 @@ void display_vendor(const uint8_t *vimg, const char *vstr, uint32_t vstr_len, ui uint32_t datalen = *(uint32_t *)(vimg + 8); display_image(60, 32, w, h, vimg + 12, datalen); display_text_center(120, 192, vstr, vstr_len, FONT_BOLD, COLOR_WHITE, COLOR_BLACK); - char ver_str[] = "0.0.0.0"; - // TODO: fixme - the following does not work for values >= 10 - ver_str[0] += fw_version & 0xFF; - ver_str[2] += (fw_version >> 8) & 0xFF; - ver_str[4] += (fw_version >> 16) & 0xFF; - ver_str[6] += (fw_version >> 24) & 0xFF; + char ver_str[32]; + mini_snprintf(ver_str, sizeof(ver_str), "%d.%d.%d.%d", + fw_version & 0xFF, + (fw_version >> 8) & 0xFF, + (fw_version >> 16) & 0xFF, + (fw_version >> 24) & 0xFF + ); display_text_center(120, 215, ver_str, -1, FONT_BOLD, COLOR_GRAY64, COLOR_BLACK); display_refresh(); } void check_and_jump(void) { - DPRINTLN("checking vendor header"); + display_printf("checking vendor header\n"); vendor_header vhdr; if (vendor_parse_header((const uint8_t *)FIRMWARE_START, &vhdr)) { - DPRINTLN("valid vendor header"); + display_printf("valid vendor header\n"); } else { - DPRINTLN("invalid vendor header"); + display_printf("invalid vendor header\n"); return; } if (vendor_check_signature((const uint8_t *)FIRMWARE_START, &vhdr)) { - DPRINTLN("valid vendor header signature"); + display_printf("valid vendor header signature\n"); } else { - DPRINTLN("invalid vendor header signature"); + display_printf("invalid vendor header signature\n"); return; } - DPRINTLN("checking firmware header"); + display_printf("checking firmware header\n"); image_header hdr; if (image_parse_header((const uint8_t *)(FIRMWARE_START + vhdr.hdrlen), IMAGE_MAGIC, IMAGE_MAXSIZE, &hdr)) { - DPRINTLN("valid firmware header"); + display_printf("valid firmware header\n"); } else { - DPRINTLN("invalid firmware header"); + display_printf("invalid firmware header\n"); return; } if (image_check_signature((const uint8_t *)(FIRMWARE_START + vhdr.hdrlen), &hdr, &vhdr)) { - DPRINTLN("valid firmware signature"); + display_printf("valid firmware signature\n"); display_vendor(vhdr.vimg, (const char *)vhdr.vstr, vhdr.vstr_len, hdr.version); HAL_Delay(1000); // TODO: remove? - DPRINTLN("JUMP!"); + display_printf("JUMP!\n"); jump_to(FIRMWARE_START + vhdr.hdrlen + HEADER_SIZE); } else { - DPRINTLN("invalid firmware signature"); + display_printf("invalid firmware signature\n"); } } @@ -175,7 +177,7 @@ uint32_t process_upload_message(uint32_t msg_size, const uint8_t *initbuf, uint3 process_upload_chunk(buf, 63); remains -= USB_PACKET_SIZE; } - DPRINTLN("done"); + display_printf("done\n"); return 0; // should return >0 if more data required } @@ -205,19 +207,19 @@ void mainloop(void) } switch (msg_id) { case 0: // Initialize - DPRINTLN("received Initialize"); + display_printf("received Initialize\n"); send_msg_Features(USB_IFACE_NUM, false); break; case 1: // Ping - DPRINTLN("received Ping"); + display_printf("received Ping\n"); send_msg_Success(USB_IFACE_NUM); break; case 6: // FirmwareErase - DPRINTLN("received FirmwareErase"); + display_printf("received FirmwareErase\n"); send_msg_FirmwareRequest(USB_IFACE_NUM, 0, UPLOAD_CHUNK_SIZE); break; case 7: // FirmwareUpload - DPRINTLN("received FirmwareUpload"); + display_printf("received FirmwareUpload\n"); uint32_t req_offset = process_upload_message(msg_size, buf + PB_HEADER_LEN, USB_PACKET_SIZE - PB_HEADER_LEN); if (req_offset > 0) { send_msg_FirmwareRequest(USB_IFACE_NUM, req_offset, UPLOAD_CHUNK_SIZE); @@ -226,7 +228,7 @@ void mainloop(void) } break; default: - DPRINTLN("received unknown message"); + display_printf("received unknown message\n"); send_msg_Failure(USB_IFACE_NUM); break; } @@ -248,9 +250,9 @@ int main(void) display_clear(); display_backlight(255); - DPRINTLN("TREZOR Bootloader " VERSION_STR); - DPRINTLN("================="); - DPRINTLN("starting bootloader"); + display_printf("TREZOR Bootloader %d.%d.%d.%d\n", VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH, VERSION_BUILD); + display_printf("=================\n"); + display_printf("starting bootloader\n"); if (touch_read() != 0) { mainloop(); diff --git a/micropython/bootloader/version.h b/micropython/bootloader/version.h index 51e009d9..a62341fe 100644 --- a/micropython/bootloader/version.h +++ b/micropython/bootloader/version.h @@ -2,12 +2,3 @@ #define VERSION_MINOR 1 #define VERSION_PATCH 0 #define VERSION_BUILD 0 - -#define VERSION_MAJOR_CHAR "\x00" -#define VERSION_MINOR_CHAR "\x01" -#define VERSION_PATCH_CHAR "\x00" - -#define STR_HELPER(X) #X -#define STRINGIZE(X) STR_HELPER(X) - -#define VERSION_STR STRINGIZE(VERSION_MAJOR) "." STRINGIZE(VERSION_MINOR) "." STRINGIZE(VERSION_PATCH) "." STRINGIZE(VERSION_BUILD) diff --git a/micropython/extmod/modtrezorui/display.c b/micropython/extmod/modtrezorui/display.c index a5377c36..7c72d7f0 100644 --- a/micropython/extmod/modtrezorui/display.c +++ b/micropython/extmod/modtrezorui/display.c @@ -20,7 +20,9 @@ #include "trezor-qrenc/qr_encode.h" #include "display.h" + #include +#include static int DISPLAY_BACKLIGHT = 0; static int DISPLAY_ORIENTATION = 0; @@ -29,6 +31,7 @@ static int DISPLAY_OFFSET[2] = {0, 0}; #if defined TREZOR_STM32 #include "display-stm32.h" #elif defined TREZOR_UNIX +#include #include "display-unix.h" #else #error Unsupported TREZOR port. Only STM32 and UNIX ports are supported. @@ -240,11 +243,21 @@ static const uint8_t *get_glyph(uint8_t font, uint8_t c) return 0; } +#ifndef TREZOR_PRINT_DISABLE + #define DISPLAY_PRINT_COLS (DISPLAY_RESX / 6) #define DISPLAY_PRINT_ROWS (DISPLAY_RESY / 8) static char display_print_buf[DISPLAY_PRINT_ROWS][DISPLAY_PRINT_COLS]; +static uint16_t display_print_fgcolor = COLOR_WHITE, display_print_bgcolor = COLOR_BLACK; -// display text using bitmap font - print to internal buffer +// set colors for display_print function +void display_print_color(uint16_t fgcolor, uint16_t bgcolor) +{ + display_print_fgcolor = fgcolor; + display_print_bgcolor = bgcolor; +} + +// display text using bitmap font void display_print(const char *text, int textlen) { static uint8_t row = 0, col = 0; @@ -254,23 +267,27 @@ void display_print(const char *text, int textlen) textlen = strlen(text); } + // print characters to internal buffer (display_print_buf) for (int i = 0; i < textlen; i++) { + switch (text[i]) { - case '\r': - break; - case '\n': - row++; - col = 0; - break; - default: - display_print_buf[row][col] = text[i]; - col++; - break; + case '\r': + break; + case '\n': + row++; + col = 0; + break; + default: + display_print_buf[row][col] = text[i]; + col++; + break; } + if (col >= DISPLAY_PRINT_COLS) { col = 0; row++; } + if (row >= DISPLAY_PRINT_ROWS) { for (int j = 0; j < DISPLAY_PRINT_ROWS - 1; j++) { memcpy(display_print_buf[j], display_print_buf[j + 1], DISPLAY_PRINT_COLS); @@ -278,11 +295,10 @@ void display_print(const char *text, int textlen) memset(display_print_buf[DISPLAY_PRINT_ROWS - 1], 0x00, DISPLAY_PRINT_COLS); row = DISPLAY_PRINT_ROWS - 1; } - } -} -// display text using bitmap font - send internal buffer to display -void display_print_out(uint16_t fgcolor, uint16_t bgcolor) { + } + + // render buffer to display display_set_window(0, 0, DISPLAY_RESX - 1, DISPLAY_RESY - 1); for (int i = 0; i < DISPLAY_RESX * DISPLAY_RESY; i++) { int x = (i % DISPLAY_RESX); @@ -294,15 +310,41 @@ void display_print_out(uint16_t fgcolor, uint16_t bgcolor) { if (c < ' ') c = ' '; const uint8_t *g = Font_Bitmap + (5 * (c - ' ')); if (k < 5 && (g[k] & (1 << j))) { - DATA(fgcolor >> 8); - DATA(fgcolor & 0xFF); + DATA(display_print_fgcolor >> 8); + DATA(display_print_fgcolor & 0xFF); } else { - DATA(bgcolor >> 8); - DATA(bgcolor & 0xFF); + DATA(display_print_bgcolor >> 8); + DATA(display_print_bgcolor & 0xFF); } } + display_refresh(); } +#ifndef TREZOR_UNIX +extern int mini_vsnprintf(char* buffer, unsigned int buffer_len, const char *fmt, va_list va); +#endif + +// variadic display_print +void display_printf(const char *fmt, ...) +{ + if (!strchr(fmt, '%')) { + display_print(fmt, strlen(fmt)); + } else { + va_list va; + va_start(va, fmt); + char buf[256]; +#ifndef TREZOR_UNIX + int len = mini_vsnprintf(buf, sizeof(buf), fmt, va); +#else + int len = vsnprintf(buf, sizeof(buf), fmt, va); +#endif + display_print(buf, len); + va_end(va); + } +} + +#endif // TREZOR_PRINT_DISABLE + // first two bytes are width and height of the glyph // third, fourth and fifth bytes are advance, bearingX and bearingY of the horizontal metrics of the glyph // rest is packed 4-bit glyph data diff --git a/micropython/extmod/modtrezorui/display.h b/micropython/extmod/modtrezorui/display.h index 42e2fc78..2803865a 100644 --- a/micropython/extmod/modtrezorui/display.h +++ b/micropython/extmod/modtrezorui/display.h @@ -51,8 +51,11 @@ void display_bar_radius(int x, int y, int w, int h, uint16_t c, uint16_t b, uint void display_image(int x, int y, int w, int h, const void *data, int datalen); void display_icon(int x, int y, int w, int h, const void *data, int datalen, uint16_t fgcolor, uint16_t bgcolor); +#ifndef TREZOR_PRINT_DISABLE +void display_print_color(uint16_t fgcolor, uint16_t bgcolor); void display_print(const char *text, int textlen); -void display_print_out(uint16_t fgcolor, uint16_t bgcolor); +void display_printf(const char *fmt, ...); +#endif void display_text(int x, int y, const char *text, int textlen, uint8_t font, uint16_t fgcolor, uint16_t bgcolor); void display_text_center(int x, int y, const char *text, int textlen, uint8_t font, uint16_t fgcolor, uint16_t bgcolor); diff --git a/micropython/extmod/modtrezorui/modtrezorui-display.h b/micropython/extmod/modtrezorui/modtrezorui-display.h index 169f5531..5ee08bb6 100644 --- a/micropython/extmod/modtrezorui/modtrezorui-display.h +++ b/micropython/extmod/modtrezorui/modtrezorui-display.h @@ -126,22 +126,19 @@ STATIC mp_obj_t mod_TrezorUi_Display_icon(size_t n_args, const mp_obj_t *args) { } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_TrezorUi_Display_icon_obj, 6, 6, mod_TrezorUi_Display_icon); -/// def trezor.ui.display.print(text: str, fgcolor: int, bgcolor: int) -> None: +/// def trezor.ui.display.print(text: str) -> None: /// ''' /// Renders text using 5x8 bitmap font (using special text mode) /// ''' -STATIC mp_obj_t mod_TrezorUi_Display_print(size_t n_args, const mp_obj_t *args) { +STATIC mp_obj_t mod_TrezorUi_Display_print(mp_obj_t self, mp_obj_t text) { mp_buffer_info_t buf; - mp_get_buffer_raise(args[1], &buf, MP_BUFFER_READ); - mp_int_t fgcolor = mp_obj_get_int(args[2]); - mp_int_t bgcolor = mp_obj_get_int(args[3]); + mp_get_buffer_raise(text, &buf, MP_BUFFER_READ); if (buf.len > 0) { display_print(buf.buf, buf.len); } - display_print_out(fgcolor, bgcolor); return mp_const_none; } -STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_TrezorUi_Display_print_obj, 4, 4, mod_TrezorUi_Display_print); +STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_TrezorUi_Display_print_obj, mod_TrezorUi_Display_print); /// def trezor.ui.display.text(x: int, y: int, text: str, font: int, fgcolor: int, bgcolor: int) -> None: /// ''' diff --git a/micropython/trezorhal/common.c b/micropython/trezorhal/common.c index 4a668710..820d927d 100644 --- a/micropython/trezorhal/common.c +++ b/micropython/trezorhal/common.c @@ -4,18 +4,15 @@ #include "display.h" void __attribute__((noreturn)) __fatal_error(const char *msg, const char *file, int line, const char *func) { - for (volatile uint32_t delay = 0; delay < 10000000; delay++) { - } - display_print("\nFATAL ERROR:\n", -1); - display_print(msg, -1); + for (volatile uint32_t delay = 0; delay < 10000000; delay++) {} + display_print_color(COLOR_WHITE, COLOR_RED128); + display_printf("\nFATAL ERROR:\n%s\n", msg); if (file) { - display_print("\nFile: ", -1); display_print(file, -1); (void)line; + display_printf("File: %s:%d\n", file, line); } if (func) { - display_print("\nFunc: ", -1); display_print(func, -1); + display_printf("Func: %s\n", func); } - display_print("\n", 1); - display_print_out(COLOR_WHITE, COLOR_RED128); for (;;) { display_backlight(255); HAL_Delay(950); @@ -26,9 +23,7 @@ void __attribute__((noreturn)) __fatal_error(const char *msg, const char *file, #ifndef NDEBUG void __assert_func(const char *file, int line, const char *func, const char *expr) { - display_print("\nassert(", -1); - display_print(expr, -1); - display_print(")\n", 2); + display_printf("\nassert(%s)\n", expr); __fatal_error("Assertion failed", file, line, func); } #endif diff --git a/micropython/trezorhal/common.h b/micropython/trezorhal/common.h index 03cc5e99..c6888942 100644 --- a/micropython/trezorhal/common.h +++ b/micropython/trezorhal/common.h @@ -16,9 +16,4 @@ void __attribute__((noreturn)) nlr_jump_fail(void *val); void jump_to(uint32_t address); -// common helper macros - -#define DPRINT(X) do { display_print(X, -1); display_print_out(COLOR_WHITE, COLOR_BLACK); } while(0) -#define DPRINTLN(X) do { display_print(X "\n", -1); display_print_out(COLOR_WHITE, COLOR_BLACK); } while(0) - #endif diff --git a/micropython/trezorhal/mini_printf.c b/micropython/trezorhal/mini_printf.c new file mode 100644 index 00000000..69a5848e --- /dev/null +++ b/micropython/trezorhal/mini_printf.c @@ -0,0 +1,199 @@ +/* + * The Minimal snprintf() implementation + * + * Copyright (c) 2013,2014 Michal Ludvig + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the auhor nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * ---- + * + * This is a minimal snprintf() implementation optimised + * for embedded systems with a very limited program memory. + * mini_snprintf() doesn't support _all_ the formatting + * the glibc does but on the other hand is a lot smaller. + * Here are some numbers from my STM32 project (.bin file size): + * no snprintf(): 10768 bytes + * mini snprintf(): 11420 bytes (+ 652 bytes) + * glibc snprintf(): 34860 bytes (+24092 bytes) + * Wasting nearly 24kB of memory just for snprintf() on + * a chip with 32kB flash is crazy. Use mini_snprintf() instead. + * + */ + +#include +#include +#include "mini_printf.h" + +static unsigned int +mini_strlen(const char *s) +{ + unsigned int len = 0; + while (s[len] != '\0') len++; + return len; +} + +static unsigned int +mini_itoa(int value, unsigned int radix, unsigned int uppercase, unsigned int unsig, + char *buffer, unsigned int zero_pad) +{ + char *pbuffer = buffer; + int negative = 0; + unsigned int i, len; + + /* No support for unusual radixes. */ + if (radix > 16) + return 0; + + if (value < 0 && !unsig) { + negative = 1; + value = -value; + } + + /* This builds the string back to front ... */ + do { + int digit = value % radix; + *(pbuffer++) = (digit < 10 ? '0' + digit : (uppercase ? 'A' : 'a') + digit - 10); + value /= radix; + } while (value > 0); + + for (i = (pbuffer - buffer); i < zero_pad; i++) + *(pbuffer++) = '0'; + + if (negative) + *(pbuffer++) = '-'; + + *(pbuffer) = '\0'; + + /* ... now we reverse it (could do it recursively but will + * conserve the stack space) */ + len = (pbuffer - buffer); + for (i = 0; i < len / 2; i++) { + char j = buffer[i]; + buffer[i] = buffer[len-i-1]; + buffer[len-i-1] = j; + } + + return len; +} + +int +mini_vsnprintf(char *buffer, unsigned int buffer_len, const char *fmt, va_list va) +{ + char *pbuffer = buffer; + char bf[24]; + char ch; + + int _putc(char ch) + { + if ((unsigned int)((pbuffer - buffer) + 1) >= buffer_len) + return 0; + *(pbuffer++) = ch; + *(pbuffer) = '\0'; + return 1; + } + + int _puts(char *s, unsigned int len) + { + unsigned int i; + + if (buffer_len - (pbuffer - buffer) - 1 < len) + len = buffer_len - (pbuffer - buffer) - 1; + + /* Copy to buffer */ + for (i = 0; i < len; i++) + *(pbuffer++) = s[i]; + *(pbuffer) = '\0'; + + return len; + } + + while ((ch=*(fmt++))) { + if ((unsigned int)((pbuffer - buffer) + 1) >= buffer_len) + break; + if (ch!='%') + _putc(ch); + else { + char zero_pad = 0; + char *ptr; + unsigned int len; + + ch=*(fmt++); + + /* Zero padding requested */ + if (ch=='0') { + ch=*(fmt++); + if (ch == '\0') + goto end; + if (ch >= '0' && ch <= '9') + zero_pad = ch - '0'; + ch=*(fmt++); + } + + switch (ch) { + case 0: + goto end; + + case 'u': + case 'd': + len = mini_itoa(va_arg(va, unsigned int), 10, 0, (ch=='u'), bf, zero_pad); + _puts(bf, len); + break; + + case 'x': + case 'X': + len = mini_itoa(va_arg(va, unsigned int), 16, (ch=='X'), 1, bf, zero_pad); + _puts(bf, len); + break; + + case 'c' : + _putc((char)(va_arg(va, int))); + break; + + case 's' : + ptr = va_arg(va, char*); + _puts(ptr, mini_strlen(ptr)); + break; + + default: + _putc(ch); + break; + } + } + } +end: + return pbuffer - buffer; +} + + +int +mini_snprintf(char* buffer, unsigned int buffer_len, const char *fmt, ...) +{ + int ret; + va_list va; + va_start(va, fmt); + ret = mini_vsnprintf(buffer, buffer_len, fmt, va); + va_end(va); + + return ret; +} diff --git a/micropython/trezorhal/mini_printf.h b/micropython/trezorhal/mini_printf.h new file mode 100644 index 00000000..97e7c117 --- /dev/null +++ b/micropython/trezorhal/mini_printf.h @@ -0,0 +1,47 @@ +/* + * The Minimal snprintf() implementation + * + * Copyright (c) 2013 Michal Ludvig + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the auhor nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + + +#ifndef __MINI_PRINTF__ +#define __MINI_PRINTF__ + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +int mini_vsnprintf(char* buffer, unsigned int buffer_len, const char *fmt, va_list va); +int mini_snprintf(char* buffer, unsigned int buffer_len, const char *fmt, ...); + +#ifdef __cplusplus +} +#endif + +#endif