From b6e716ddc51cf1bd7b30ead2c98ef6ef3bf9877b Mon Sep 17 00:00:00 2001
From: Sergiusz Bazanski <q3k@q3k.org>
Date: Sat, 27 Jul 2019 15:09:02 +0200
Subject: [PATCH] l0dables/lib: implement stdout and heap via newlib

---
 l0dables/lib/hardware.c  | 38 ++++++++++++++++++++++++++++++++++++++
 l0dables/lib/l0dable.ld  |  3 +++
 l0dables/lib/meson.build |  2 +-
 3 files changed, 42 insertions(+), 1 deletion(-)

diff --git a/l0dables/lib/hardware.c b/l0dables/lib/hardware.c
index 7a481afac..e9325a1c6 100644
--- a/l0dables/lib/hardware.c
+++ b/l0dables/lib/hardware.c
@@ -9,6 +9,9 @@
  * initialization before main() gets called.
  */
 
+#include <stddef.h>
+#include "epicardium.h"
+
 #include "max32665.h"
 #include "mxc_sys.h"
 #include "gcr_regs.h"
@@ -72,3 +75,38 @@ __weak void SystemInit() {
 
 	SystemCoreClockUpdate();
 }
+
+// newlib syscall to allow printf to work.
+long _write(int fd, const char *buf, size_t cnt)
+{
+	/*
+	 * Only print one line at a time.  Insert `\r` between lines so
+	 * they are properly displayed on the serial console.
+	 */
+	size_t i, last = 0;
+	for (i = 0; i < cnt; i++) {
+		if (buf[i] == '\n') {
+			epic_uart_write_str(&buf[last], i - last);
+			epic_uart_write_str("\r", 1);
+			last = i;
+		}
+	}
+	if (last != i) {
+		epic_uart_write_str(&buf[last], cnt - last);
+	}
+	return cnt;
+}
+
+// newlib syscall to allow for a heap
+extern uint32_t __heap_start;
+uint32_t _sbrk(int incr)
+{
+	static char *brk = NULL;
+	if (brk == NULL) {
+		brk = (char *)&__heap_start;
+	}
+
+	char *prev_brk = brk;
+	brk += incr;
+	return (uint32_t)prev_brk;
+}
diff --git a/l0dables/lib/l0dable.ld b/l0dables/lib/l0dable.ld
index c1c392153..25f1a818b 100644
--- a/l0dables/lib/l0dable.ld
+++ b/l0dables/lib/l0dable.ld
@@ -71,6 +71,9 @@ SECTIONS {
         *(COMMON)
     } :data
 
+    /* Used by hardware.c as start of heap. */
+    __heap_start = .;
+
     /* Limit based on current limitations of l0dable setup - only uses core1 RAM. */
     ASSERT(. < 0x40000, "Exceeded available RAM")
 
diff --git a/l0dables/lib/meson.build b/l0dables/lib/meson.build
index c9d81c080..60d557d4e 100644
--- a/l0dables/lib/meson.build
+++ b/l0dables/lib/meson.build
@@ -2,7 +2,7 @@ l0dable_startup_lib = static_library(
   'l0dable-startup',
   'crt.s',
   'hardware.c',
-  dependencies: periphdriver,
+  dependencies: [periphdriver, api_caller],
   pic: true,
 )
 
-- 
GitLab