Add Cortex-M glue/support code

improve-install-script
Gregor Peach 6 years ago
parent c138a148d1
commit 8e96818b08

4
.gitignore vendored

@ -4,6 +4,7 @@
a.out*
**/*.o
**/*.elf
input.wasm
output.bc
@ -13,3 +14,6 @@ code_benches/benchmarks.csv
silverfish.iml
.idea
.vagrant
Vagrantfile

@ -0,0 +1,12 @@
ENTRY(_start)
MEMORY
{
ram : ORIGIN = 0x00010000, LENGTH = 0x1000
}
SECTIONS
{
.text : { *(.text*) } > ram
.rodata : { *(.rodata*) } > ram
.bss : { *(.bss*) } > ram
}

@ -0,0 +1,914 @@
///////////////////////////////////////////////////////////////////////////////
// \author (c) Marco Paland (info@paland.com)
// 2014-2019, PALANDesign Hannover, Germany
//
// \license The MIT License (MIT)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// \brief Tiny printf, sprintf and (v)snprintf implementation, optimized for speed on
// embedded systems with a very limited resources. These routines are thread
// safe and reentrant!
// Use this instead of the bloated standard/newlib printf cause these use
// malloc for printf (and may not be thread safe).
//
///////////////////////////////////////////////////////////////////////////////
#include <stdbool.h>
#include <stdint.h>
#include "printf.h"
// define this globally (e.g. gcc -DPRINTF_INCLUDE_CONFIG_H ...) to include the
// printf_config.h header file
// default: undefined
#ifdef PRINTF_INCLUDE_CONFIG_H
#include "printf_config.h"
#endif
// 'ntoa' conversion buffer size, this must be big enough to hold one converted
// numeric number including padded zeros (dynamically created on stack)
// default: 32 byte
#ifndef PRINTF_NTOA_BUFFER_SIZE
#define PRINTF_NTOA_BUFFER_SIZE 32U
#endif
// 'ftoa' conversion buffer size, this must be big enough to hold one converted
// float number including padded zeros (dynamically created on stack)
// default: 32 byte
#ifndef PRINTF_FTOA_BUFFER_SIZE
#define PRINTF_FTOA_BUFFER_SIZE 32U
#endif
// support for the floating point type (%f)
// default: activated
#ifndef PRINTF_DISABLE_SUPPORT_FLOAT
#define PRINTF_SUPPORT_FLOAT
#endif
// support for exponential floating point notation (%e/%g)
// default: activated
#ifndef PRINTF_DISABLE_SUPPORT_EXPONENTIAL
#define PRINTF_SUPPORT_EXPONENTIAL
#endif
// define the default floating point precision
// default: 6 digits
#ifndef PRINTF_DEFAULT_FLOAT_PRECISION
#define PRINTF_DEFAULT_FLOAT_PRECISION 6U
#endif
// define the largest float suitable to print with %f
// default: 1e9
#ifndef PRINTF_MAX_FLOAT
#define PRINTF_MAX_FLOAT 1e9
#endif
// support for the long long types (%llu or %p)
// default: activated
#ifndef PRINTF_DISABLE_SUPPORT_LONG_LONG
#define PRINTF_SUPPORT_LONG_LONG
#endif
// support for the ptrdiff_t type (%t)
// ptrdiff_t is normally defined in <stddef.h> as long or long long type
// default: activated
#ifndef PRINTF_DISABLE_SUPPORT_PTRDIFF_T
#define PRINTF_SUPPORT_PTRDIFF_T
#endif
///////////////////////////////////////////////////////////////////////////////
// internal flag definitions
#define FLAGS_ZEROPAD (1U << 0U)
#define FLAGS_LEFT (1U << 1U)
#define FLAGS_PLUS (1U << 2U)
#define FLAGS_SPACE (1U << 3U)
#define FLAGS_HASH (1U << 4U)
#define FLAGS_UPPERCASE (1U << 5U)
#define FLAGS_CHAR (1U << 6U)
#define FLAGS_SHORT (1U << 7U)
#define FLAGS_LONG (1U << 8U)
#define FLAGS_LONG_LONG (1U << 9U)
#define FLAGS_PRECISION (1U << 10U)
#define FLAGS_ADAPT_EXP (1U << 11U)
// import float.h for DBL_MAX
#if defined(PRINTF_SUPPORT_FLOAT)
#include <float.h>
#endif
// output function type
typedef void (*out_fct_type)(char character, void* buffer, size_t idx, size_t maxlen);
// wrapper (used as buffer) for output function type
typedef struct {
void (*fct)(char character, void* arg);
void* arg;
} out_fct_wrap_type;
// internal buffer output
static inline void _out_buffer(char character, void* buffer, size_t idx, size_t maxlen)
{
if (idx < maxlen) {
((char*)buffer)[idx] = character;
}
}
// internal null output
static inline void _out_null(char character, void* buffer, size_t idx, size_t maxlen)
{
(void)character; (void)buffer; (void)idx; (void)maxlen;
}
// internal _putchar wrapper
static inline void _out_char(char character, void* buffer, size_t idx, size_t maxlen)
{
(void)buffer; (void)idx; (void)maxlen;
if (character) {
_putchar(character);
}
}
// internal output function wrapper
static inline void _out_fct(char character, void* buffer, size_t idx, size_t maxlen)
{
(void)idx; (void)maxlen;
if (character) {
// buffer is the output fct pointer
((out_fct_wrap_type*)buffer)->fct(character, ((out_fct_wrap_type*)buffer)->arg);
}
}
// internal secure strlen
// \return The length of the string (excluding the terminating 0) limited by 'maxsize'
static inline unsigned int _strnlen_s(const char* str, size_t maxsize)
{
const char* s;
for (s = str; *s && maxsize--; ++s);
return (unsigned int)(s - str);
}
// internal test if char is a digit (0-9)
// \return true if char is a digit
static inline bool _is_digit(char ch)
{
return (ch >= '0') && (ch <= '9');
}
// internal ASCII string to unsigned int conversion
static unsigned int _atoi(const char** str)
{
unsigned int i = 0U;
while (_is_digit(**str)) {
i = i * 10U + (unsigned int)(*((*str)++) - '0');
}
return i;
}
// output the specified string in reverse, taking care of any zero-padding
static size_t _out_rev(out_fct_type out, char* buffer, size_t idx, size_t maxlen, const char* buf, size_t len, unsigned int width, unsigned int flags)
{
const size_t start_idx = idx;
// pad spaces up to given width
if (!(flags & FLAGS_LEFT) && !(flags & FLAGS_ZEROPAD)) {
for (size_t i = len; i < width; i++) {
out(' ', buffer, idx++, maxlen);
}
}
// reverse string
while (len) {
out(buf[--len], buffer, idx++, maxlen);
}
// append pad spaces up to given width
if (flags & FLAGS_LEFT) {
while (idx - start_idx < width) {
out(' ', buffer, idx++, maxlen);
}
}
return idx;
}
// internal itoa format
static size_t _ntoa_format(out_fct_type out, char* buffer, size_t idx, size_t maxlen, char* buf, size_t len, bool negative, unsigned int base, unsigned int prec, unsigned int width, unsigned int flags)
{
// pad leading zeros
if (!(flags & FLAGS_LEFT)) {
if (width && (flags & FLAGS_ZEROPAD) && (negative || (flags & (FLAGS_PLUS | FLAGS_SPACE)))) {
width--;
}
while ((len < prec) && (len < PRINTF_NTOA_BUFFER_SIZE)) {
buf[len++] = '0';
}
while ((flags & FLAGS_ZEROPAD) && (len < width) && (len < PRINTF_NTOA_BUFFER_SIZE)) {
buf[len++] = '0';
}
}
// handle hash
if (flags & FLAGS_HASH) {
if (!(flags & FLAGS_PRECISION) && len && ((len == prec) || (len == width))) {
len--;
if (len && (base == 16U)) {
len--;
}
}
if ((base == 16U) && !(flags & FLAGS_UPPERCASE) && (len < PRINTF_NTOA_BUFFER_SIZE)) {
buf[len++] = 'x';
}
else if ((base == 16U) && (flags & FLAGS_UPPERCASE) && (len < PRINTF_NTOA_BUFFER_SIZE)) {
buf[len++] = 'X';
}
else if ((base == 2U) && (len < PRINTF_NTOA_BUFFER_SIZE)) {
buf[len++] = 'b';
}
if (len < PRINTF_NTOA_BUFFER_SIZE) {
buf[len++] = '0';
}
}
if (len < PRINTF_NTOA_BUFFER_SIZE) {
if (negative) {
buf[len++] = '-';
}
else if (flags & FLAGS_PLUS) {
buf[len++] = '+'; // ignore the space if the '+' exists
}
else if (flags & FLAGS_SPACE) {
buf[len++] = ' ';
}
}
return _out_rev(out, buffer, idx, maxlen, buf, len, width, flags);
}
// internal itoa for 'long' type
static size_t _ntoa_long(out_fct_type out, char* buffer, size_t idx, size_t maxlen, unsigned long value, bool negative, unsigned long base, unsigned int prec, unsigned int width, unsigned int flags)
{
char buf[PRINTF_NTOA_BUFFER_SIZE];
size_t len = 0U;
// no hash for 0 values
if (!value) {
flags &= ~FLAGS_HASH;
}
// write if precision != 0 and value is != 0
if (!(flags & FLAGS_PRECISION) || value) {
do {
const char digit = (char)(value % base);
buf[len++] = digit < 10 ? '0' + digit : (flags & FLAGS_UPPERCASE ? 'A' : 'a') + digit - 10;
value /= base;
} while (value && (len < PRINTF_NTOA_BUFFER_SIZE));
}
return _ntoa_format(out, buffer, idx, maxlen, buf, len, negative, (unsigned int)base, prec, width, flags);
}
// internal itoa for 'long long' type
#if defined(PRINTF_SUPPORT_LONG_LONG)
static size_t _ntoa_long_long(out_fct_type out, char* buffer, size_t idx, size_t maxlen, unsigned long long value, bool negative, unsigned long long base, unsigned int prec, unsigned int width, unsigned int flags)
{
char buf[PRINTF_NTOA_BUFFER_SIZE];
size_t len = 0U;
// no hash for 0 values
if (!value) {
flags &= ~FLAGS_HASH;
}
// write if precision != 0 and value is != 0
if (!(flags & FLAGS_PRECISION) || value) {
do {
const char digit = (char)(value % base);
buf[len++] = digit < 10 ? '0' + digit : (flags & FLAGS_UPPERCASE ? 'A' : 'a') + digit - 10;
value /= base;
} while (value && (len < PRINTF_NTOA_BUFFER_SIZE));
}
return _ntoa_format(out, buffer, idx, maxlen, buf, len, negative, (unsigned int)base, prec, width, flags);
}
#endif // PRINTF_SUPPORT_LONG_LONG
#if defined(PRINTF_SUPPORT_FLOAT)
#if defined(PRINTF_SUPPORT_EXPONENTIAL)
// forward declaration so that _ftoa can switch to exp notation for values > PRINTF_MAX_FLOAT
static size_t _etoa(out_fct_type out, char* buffer, size_t idx, size_t maxlen, double value, unsigned int prec, unsigned int width, unsigned int flags);
#endif
// internal ftoa for fixed decimal floating point
static size_t _ftoa(out_fct_type out, char* buffer, size_t idx, size_t maxlen, double value, unsigned int prec, unsigned int width, unsigned int flags)
{
char buf[PRINTF_FTOA_BUFFER_SIZE];
size_t len = 0U;
double diff = 0.0;
// powers of 10
static const double pow10[] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 };
// test for special values
if (value != value)
return _out_rev(out, buffer, idx, maxlen, "nan", 3, width, flags);
if (value < -DBL_MAX)
return _out_rev(out, buffer, idx, maxlen, "fni-", 4, width, flags);
if (value > DBL_MAX)
return _out_rev(out, buffer, idx, maxlen, (flags & FLAGS_PLUS) ? "fni+" : "fni", (flags & FLAGS_PLUS) ? 4U : 3U, width, flags);
// test for very large values
// standard printf behavior is to print EVERY whole number digit -- which could be 100s of characters overflowing your buffers == bad
if ((value > PRINTF_MAX_FLOAT) || (value < -PRINTF_MAX_FLOAT)) {
#if defined(PRINTF_SUPPORT_EXPONENTIAL)
return _etoa(out, buffer, idx, maxlen, value, prec, width, flags);
#else
return 0U;
#endif
}
// test for negative
bool negative = false;
if (value < 0) {
negative = true;
value = 0 - value;
}
// set default precision, if not set explicitly
if (!(flags & FLAGS_PRECISION)) {
prec = PRINTF_DEFAULT_FLOAT_PRECISION;
}
// limit precision to 9, cause a prec >= 10 can lead to overflow errors
while ((len < PRINTF_FTOA_BUFFER_SIZE) && (prec > 9U)) {
buf[len++] = '0';
prec--;
}
int whole = (int)value;
double tmp = (value - whole) * pow10[prec];
unsigned long frac = (unsigned long)tmp;
diff = tmp - frac;
if (diff > 0.5) {
++frac;
// handle rollover, e.g. case 0.99 with prec 1 is 1.0
if (frac >= pow10[prec]) {
frac = 0;
++whole;
}
}
else if (diff < 0.5) {
}
else if ((frac == 0U) || (frac & 1U)) {
// if halfway, round up if odd OR if last digit is 0
++frac;
}
if (prec == 0U) {
diff = value - (double)whole;
if ((!(diff < 0.5) || (diff > 0.5)) && (whole & 1)) {
// exactly 0.5 and ODD, then round up
// 1.5 -> 2, but 2.5 -> 2
++whole;
}
}
else {
unsigned int count = prec;
// now do fractional part, as an unsigned number
while (len < PRINTF_FTOA_BUFFER_SIZE) {
--count;
buf[len++] = (char)(48U + (frac % 10U));
if (!(frac /= 10U)) {
break;
}
}
// add extra 0s
while ((len < PRINTF_FTOA_BUFFER_SIZE) && (count-- > 0U)) {
buf[len++] = '0';
}
if (len < PRINTF_FTOA_BUFFER_SIZE) {
// add decimal
buf[len++] = '.';
}
}
// do whole part, number is reversed
while (len < PRINTF_FTOA_BUFFER_SIZE) {
buf[len++] = (char)(48 + (whole % 10));
if (!(whole /= 10)) {
break;
}
}
// pad leading zeros
if (!(flags & FLAGS_LEFT) && (flags & FLAGS_ZEROPAD)) {
if (width && (negative || (flags & (FLAGS_PLUS | FLAGS_SPACE)))) {
width--;
}
while ((len < width) && (len < PRINTF_FTOA_BUFFER_SIZE)) {
buf[len++] = '0';
}
}
if (len < PRINTF_FTOA_BUFFER_SIZE) {
if (negative) {
buf[len++] = '-';
}
else if (flags & FLAGS_PLUS) {
buf[len++] = '+'; // ignore the space if the '+' exists
}
else if (flags & FLAGS_SPACE) {
buf[len++] = ' ';
}
}
return _out_rev(out, buffer, idx, maxlen, buf, len, width, flags);
}
#if defined(PRINTF_SUPPORT_EXPONENTIAL)
// internal ftoa variant for exponential floating-point type, contributed by Martijn Jasperse <m.jasperse@gmail.com>
static size_t _etoa(out_fct_type out, char* buffer, size_t idx, size_t maxlen, double value, unsigned int prec, unsigned int width, unsigned int flags)
{
// check for NaN and special values
if ((value != value) || (value > DBL_MAX) || (value < -DBL_MAX)) {
return _ftoa(out, buffer, idx, maxlen, value, prec, width, flags);
}
// determine the sign
const bool negative = value < 0;
if (negative) {
value = -value;
}
// default precision
if (!(flags & FLAGS_PRECISION)) {
prec = PRINTF_DEFAULT_FLOAT_PRECISION;
}
// determine the decimal exponent
// based on the algorithm by David Gay (https://www.ampl.com/netlib/fp/dtoa.c)
union {
uint64_t U;
double F;
} conv;
conv.F = value;
int exp2 = (int)((conv.U >> 52U) & 0x07FFU) - 1023; // effectively log2
conv.U = (conv.U & ((1ULL << 52U) - 1U)) | (1023ULL << 52U); // drop the exponent so conv.F is now in [1,2)
// now approximate log10 from the log2 integer part and an expansion of ln around 1.5
int expval = (int)(0.1760912590558 + exp2 * 0.301029995663981 + (conv.F - 1.5) * 0.289529654602168);
// now we want to compute 10^expval but we want to be sure it won't overflow
exp2 = (int)(expval * 3.321928094887362 + 0.5);
const double z = expval * 2.302585092994046 - exp2 * 0.6931471805599453;
const double z2 = z * z;
conv.U = (uint64_t)(exp2 + 1023) << 52U;
// compute exp(z) using continued fractions, see https://en.wikipedia.org/wiki/Exponential_function#Continued_fractions_for_ex
conv.F *= 1 + 2 * z / (2 - z + (z2 / (6 + (z2 / (10 + z2 / 14)))));
// correct for rounding errors
if (value < conv.F) {
expval--;
conv.F /= 10;
}
// the exponent format is "%+03d" and largest value is "307", so set aside 4-5 characters
unsigned int minwidth = ((expval < 100) && (expval > -100)) ? 4U : 5U;
// in "%g" mode, "prec" is the number of *significant figures* not decimals
if (flags & FLAGS_ADAPT_EXP) {
// do we want to fall-back to "%f" mode?
if ((value >= 1e-4) && (value < 1e6)) {
if ((int)prec > expval) {
prec = (unsigned)((int)prec - expval - 1);
}
else {
prec = 0;
}
flags |= FLAGS_PRECISION; // make sure _ftoa respects precision
// no characters in exponent
minwidth = 0U;
expval = 0;
}
else {
// we use one sigfig for the whole part
if ((prec > 0) && (flags & FLAGS_PRECISION)) {
--prec;
}
}
}
// will everything fit?
unsigned int fwidth = width;
if (width > minwidth) {
// we didn't fall-back so subtract the characters required for the exponent
fwidth -= minwidth;
} else {
// not enough characters, so go back to default sizing
fwidth = 0U;
}
if ((flags & FLAGS_LEFT) && minwidth) {
// if we're padding on the right, DON'T pad the floating part
fwidth = 0U;
}
// rescale the float value
if (expval) {
value /= conv.F;
}
// output the floating part
const size_t start_idx = idx;
idx = _ftoa(out, buffer, idx, maxlen, negative ? -value : value, prec, fwidth, flags & ~FLAGS_ADAPT_EXP);
// output the exponent part
if (minwidth) {
// output the exponential symbol
out((flags & FLAGS_UPPERCASE) ? 'E' : 'e', buffer, idx++, maxlen);
// output the exponent value
idx = _ntoa_long(out, buffer, idx, maxlen, (expval < 0) ? -expval : expval, expval < 0, 10, 0, minwidth-1, FLAGS_ZEROPAD | FLAGS_PLUS);
// might need to right-pad spaces
if (flags & FLAGS_LEFT) {
while (idx - start_idx < width) out(' ', buffer, idx++, maxlen);
}
}
return idx;
}
#endif // PRINTF_SUPPORT_EXPONENTIAL
#endif // PRINTF_SUPPORT_FLOAT
// internal vsnprintf
static int _vsnprintf(out_fct_type out, char* buffer, const size_t maxlen, const char* format, va_list va)
{
unsigned int flags, width, precision, n;
size_t idx = 0U;
if (!buffer) {
// use null output function
out = _out_null;
}
while (*format)
{
// format specifier? %[flags][width][.precision][length]
if (*format != '%') {
// no
out(*format, buffer, idx++, maxlen);
format++;
continue;
}
else {
// yes, evaluate it
format++;
}
// evaluate flags
flags = 0U;
do {
switch (*format) {
case '0': flags |= FLAGS_ZEROPAD; format++; n = 1U; break;
case '-': flags |= FLAGS_LEFT; format++; n = 1U; break;
case '+': flags |= FLAGS_PLUS; format++; n = 1U; break;
case ' ': flags |= FLAGS_SPACE; format++; n = 1U; break;
case '#': flags |= FLAGS_HASH; format++; n = 1U; break;
default : n = 0U; break;
}
} while (n);
// evaluate width field
width = 0U;
if (_is_digit(*format)) {
width = _atoi(&format);
}
else if (*format == '*') {
const int w = va_arg(va, int);
if (w < 0) {
flags |= FLAGS_LEFT; // reverse padding
width = (unsigned int)-w;
}
else {
width = (unsigned int)w;
}
format++;
}
// evaluate precision field
precision = 0U;
if (*format == '.') {
flags |= FLAGS_PRECISION;
format++;
if (_is_digit(*format)) {
precision = _atoi(&format);
}
else if (*format == '*') {
const int prec = (int)va_arg(va, int);
precision = prec > 0 ? (unsigned int)prec : 0U;
format++;
}
}
// evaluate length field
switch (*format) {
case 'l' :
flags |= FLAGS_LONG;
format++;
if (*format == 'l') {
flags |= FLAGS_LONG_LONG;
format++;
}
break;
case 'h' :
flags |= FLAGS_SHORT;
format++;
if (*format == 'h') {
flags |= FLAGS_CHAR;
format++;
}
break;
#if defined(PRINTF_SUPPORT_PTRDIFF_T)
case 't' :
flags |= (sizeof(ptrdiff_t) == sizeof(long) ? FLAGS_LONG : FLAGS_LONG_LONG);
format++;
break;
#endif
case 'j' :
flags |= (sizeof(intmax_t) == sizeof(long) ? FLAGS_LONG : FLAGS_LONG_LONG);
format++;
break;
case 'z' :
flags |= (sizeof(size_t) == sizeof(long) ? FLAGS_LONG : FLAGS_LONG_LONG);
format++;
break;
default :
break;
}
// evaluate specifier
switch (*format) {
case 'd' :
case 'i' :
case 'u' :
case 'x' :
case 'X' :
case 'o' :
case 'b' : {
// set the base
unsigned int base;
if (*format == 'x' || *format == 'X') {
base = 16U;
}
else if (*format == 'o') {
base = 8U;
}
else if (*format == 'b') {
base = 2U;
}
else {
base = 10U;
flags &= ~FLAGS_HASH; // no hash for dec format
}
// uppercase
if (*format == 'X') {
flags |= FLAGS_UPPERCASE;
}
// no plus or space flag for u, x, X, o, b
if ((*format != 'i') && (*format != 'd')) {
flags &= ~(FLAGS_PLUS | FLAGS_SPACE);
}
// ignore '0' flag when precision is given
if (flags & FLAGS_PRECISION) {
flags &= ~FLAGS_ZEROPAD;
}
// convert the integer
if ((*format == 'i') || (*format == 'd')) {
// signed
if (flags & FLAGS_LONG_LONG) {
#if defined(PRINTF_SUPPORT_LONG_LONG)
const long long value = va_arg(va, long long);
idx = _ntoa_long_long(out, buffer, idx, maxlen, (unsigned long long)(value > 0 ? value : 0 - value), value < 0, base, precision, width, flags);
#endif
}
else if (flags & FLAGS_LONG) {
const long value = va_arg(va, long);
idx = _ntoa_long(out, buffer, idx, maxlen, (unsigned long)(value > 0 ? value : 0 - value), value < 0, base, precision, width, flags);
}
else {
const int value = (flags & FLAGS_CHAR) ? (char)va_arg(va, int) : (flags & FLAGS_SHORT) ? (short int)va_arg(va, int) : va_arg(va, int);
idx = _ntoa_long(out, buffer, idx, maxlen, (unsigned int)(value > 0 ? value : 0 - value), value < 0, base, precision, width, flags);
}
}
else {
// unsigned
if (flags & FLAGS_LONG_LONG) {
#if defined(PRINTF_SUPPORT_LONG_LONG)
idx = _ntoa_long_long(out, buffer, idx, maxlen, va_arg(va, unsigned long long), false, base, precision, width, flags);
#endif
}
else if (flags & FLAGS_LONG) {
idx = _ntoa_long(out, buffer, idx, maxlen, va_arg(va, unsigned long), false, base, precision, width, flags);
}
else {
const unsigned int value = (flags & FLAGS_CHAR) ? (unsigned char)va_arg(va, unsigned int) : (flags & FLAGS_SHORT) ? (unsigned short int)va_arg(va, unsigned int) : va_arg(va, unsigned int);
idx = _ntoa_long(out, buffer, idx, maxlen, value, false, base, precision, width, flags);
}
}
format++;
break;
}
#if defined(PRINTF_SUPPORT_FLOAT)
case 'f' :
case 'F' :
if (*format == 'F') flags |= FLAGS_UPPERCASE;
idx = _ftoa(out, buffer, idx, maxlen, va_arg(va, double), precision, width, flags);
format++;
break;
#if defined(PRINTF_SUPPORT_EXPONENTIAL)
case 'e':
case 'E':
case 'g':
case 'G':
if ((*format == 'g')||(*format == 'G')) flags |= FLAGS_ADAPT_EXP;
if ((*format == 'E')||(*format == 'G')) flags |= FLAGS_UPPERCASE;
idx = _etoa(out, buffer, idx, maxlen, va_arg(va, double), precision, width, flags);
format++;
break;
#endif // PRINTF_SUPPORT_EXPONENTIAL
#endif // PRINTF_SUPPORT_FLOAT
case 'c' : {
unsigned int l = 1U;
// pre padding
if (!(flags & FLAGS_LEFT)) {
while (l++ < width) {
out(' ', buffer, idx++, maxlen);
}
}
// char output
out((char)va_arg(va, int), buffer, idx++, maxlen);
// post padding
if (flags & FLAGS_LEFT) {
while (l++ < width) {
out(' ', buffer, idx++, maxlen);
}
}
format++;
break;
}
case 's' : {
const char* p = va_arg(va, char*);
unsigned int l = _strnlen_s(p, precision ? precision : (size_t)-1);
// pre padding
if (flags & FLAGS_PRECISION) {
l = (l < precision ? l : precision);
}
if (!(flags & FLAGS_LEFT)) {
while (l++ < width) {
out(' ', buffer, idx++, maxlen);
}
}
// string output
while ((*p != 0) && (!(flags & FLAGS_PRECISION) || precision--)) {
out(*(p++), buffer, idx++, maxlen);
}
// post padding
if (flags & FLAGS_LEFT) {
while (l++ < width) {
out(' ', buffer, idx++, maxlen);
}
}
format++;
break;
}
case 'p' : {
width = sizeof(void*) * 2U;
flags |= FLAGS_ZEROPAD | FLAGS_UPPERCASE;
#if defined(PRINTF_SUPPORT_LONG_LONG)
const bool is_ll = sizeof(uintptr_t) == sizeof(long long);
if (is_ll) {
idx = _ntoa_long_long(out, buffer, idx, maxlen, (uintptr_t)va_arg(va, void*), false, 16U, precision, width, flags);
}
else {
#endif
idx = _ntoa_long(out, buffer, idx, maxlen, (unsigned long)((uintptr_t)va_arg(va, void*)), false, 16U, precision, width, flags);
#if defined(PRINTF_SUPPORT_LONG_LONG)
}
#endif
format++;
break;
}
case '%' :
out('%', buffer, idx++, maxlen);
format++;
break;
default :
out(*format, buffer, idx++, maxlen);
format++;
break;
}
}
// termination
out((char)0, buffer, idx < maxlen ? idx : maxlen - 1U, maxlen);
// return written chars without terminating \0
return (int)idx;
}
///////////////////////////////////////////////////////////////////////////////
int printf_(const char* format, ...)
{
va_list va;
va_start(va, format);
char buffer[1];
const int ret = _vsnprintf(_out_char, buffer, (size_t)-1, format, va);
va_end(va);
return ret;
}
int sprintf_(char* buffer, const char* format, ...)
{
va_list va;
va_start(va, format);
const int ret = _vsnprintf(_out_buffer, buffer, (size_t)-1, format, va);
va_end(va);
return ret;
}
int snprintf_(char* buffer, size_t count, const char* format, ...)
{
va_list va;
va_start(va, format);
const int ret = _vsnprintf(_out_buffer, buffer, count, format, va);
va_end(va);
return ret;
}
int vprintf_(const char* format, va_list va)
{
char buffer[1];
return _vsnprintf(_out_char, buffer, (size_t)-1, format, va);
}
int vsnprintf_(char* buffer, size_t count, const char* format, va_list va)
{
return _vsnprintf(_out_buffer, buffer, count, format, va);
}
int fctprintf(void (*out)(char character, void* arg), void* arg, const char* format, ...)
{
va_list va;
va_start(va, format);
const out_fct_wrap_type out_fct_wrap = { out, arg };
const int ret = _vsnprintf(_out_fct, (char*)(uintptr_t)&out_fct_wrap, (size_t)-1, format, va);
va_end(va);
return ret;
}

@ -0,0 +1,117 @@
///////////////////////////////////////////////////////////////////////////////
// \author (c) Marco Paland (info@paland.com)
// 2014-2019, PALANDesign Hannover, Germany
//
// \license The MIT License (MIT)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// \brief Tiny printf, sprintf and snprintf implementation, optimized for speed on
// embedded systems with a very limited resources.
// Use this instead of bloated standard/newlib printf.
// These routines are thread safe and reentrant.
//
///////////////////////////////////////////////////////////////////////////////
#ifndef _PRINTF_H_
#define _PRINTF_H_
#include <stdarg.h>
#include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* Output a character to a custom device like UART, used by the printf() function
* This function is declared here only. You have to write your custom implementation somewhere
* \param character Character to output
*/
void _putchar(char character);
/**
* Tiny printf implementation
* You have to implement _putchar if you use printf()
* To avoid conflicts with the regular printf() API it is overridden by macro defines
* and internal underscore-appended functions like printf_() are used
* \param format A string that specifies the format of the output
* \return The number of characters that are written into the array, not counting the terminating null character
*/
#define printf printf_
int printf_(const char* format, ...);
/**
* Tiny sprintf implementation
* Due to security reasons (buffer overflow) YOU SHOULD CONSIDER USING (V)SNPRINTF INSTEAD!
* \param buffer A pointer to the buffer where to store the formatted string. MUST be big enough to store the output!
* \param format A string that specifies the format of the output
* \return The number of characters that are WRITTEN into the buffer, not counting the terminating null character
*/
#define sprintf sprintf_
int sprintf_(char* buffer, const char* format, ...);
/**
* Tiny snprintf/vsnprintf implementation
* \param buffer A pointer to the buffer where to store the formatted string
* \param count The maximum number of characters to store in the buffer, including a terminating null character
* \param format A string that specifies the format of the output
* \param va A value identifying a variable arguments list
* \return The number of characters that COULD have been written into the buffer, not counting the terminating
* null character. A value equal or larger than count indicates truncation. Only when the returned value
* is non-negative and less than count, the string has been completely written.
*/
#define snprintf snprintf_
#define vsnprintf vsnprintf_
int snprintf_(char* buffer, size_t count, const char* format, ...);
int vsnprintf_(char* buffer, size_t count, const char* format, va_list va);
/**
* Tiny vprintf implementation
* \param format A string that specifies the format of the output
* \param va A value identifying a variable arguments list
* \return The number of characters that are WRITTEN into the buffer, not counting the terminating null character
*/
#define vprintf vprintf_
int vprintf_(const char* format, va_list va);
/**
* printf with output function
* You may use this as dynamic alternative to printf() with its fixed _putchar() output
* \param out An output function which takes one character and an argument pointer
* \param arg An argument pointer for user data passed to output function
* \param format A string that specifies the format of the output
* \return The number of characters that are sent to the output function, not counting the terminating null character
*/
int fctprintf(void (*out)(char character, void* arg), void* arg, const char* format, ...);
#ifdef __cplusplus
}
#endif
#endif // _PRINTF_H_

@ -0,0 +1,431 @@
/******************************************************************************
Filename : sections.ld
Author : eclipse-arm-gcc team, pry(modified)
Date : 27/02/2017
Description : Default linker script for Cortex-M (it includes specifics for STM32F[34]xx).
To make use of the multi-region initialisations, define
OS_INCLUDE_STARTUP_INIT_MULTIPLE_RAM_SECTIONS for the _startup.c file.
******************************************************************************/
/* Memory Definitions *********************************************************
Description : This section will define the memory layout of the sytem. This section
requires modifying for a specific board. Typical settings for different
chips are listed below:
DTCM 64K, SRAM1 240K, SRAM2 16K, Flash 512k (R320/F512) - STM32F746
DTCM 128K, SRAM1 368K, SRAM2 16K, Flash 1024k (R512/F1024) - STM32F767
DTCM 128K, SRAM1 368K, SRAM2 16K, Flash 2048k (R1024/F2048) - STM32Hxxx
Component : .ORIGIN - Starting address of the memory region.
.LENGTH - Length of the region.
******************************************************************************/
MEMORY
{
RAM (xrw) : ORIGIN = 0x20000000, LENGTH = 512K
FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 1024K
EROMEM0 (rx) : ORIGIN = 0x00000000, LENGTH = 0
ERWMEM0 (xrw) : ORIGIN = 0xC0000000, LENGTH = 32768K
}
_Privileged_Functions_Region_Size = 32K;
_Privileged_Data_Region_Size = 512;
__FLASH_segment_start__ = ORIGIN( FLASH );
__FLASH_segment_end__ = __FLASH_segment_start__ + LENGTH( FLASH );
__privileged_functions_start__ = ORIGIN( FLASH );
__privileged_functions_end__ = __privileged_functions_start__ + _Privileged_Functions_Region_Size;
__SRAM_segment_start__ = ORIGIN( RAM );
__SRAM_segment_end__ = __SRAM_segment_start__ + LENGTH( RAM );
__privileged_data_start__ = ORIGIN( RAM );
__privileged_data_end__ = ORIGIN( RAM ) + _Privileged_Data_Region_Size;
/* End Memory Definitions ****************************************************/
/* Stack Definitions *********************************************************/
/* The '__stack' definition is required by crt0, do not remove it. */
__stack = ORIGIN(RAM) + LENGTH(RAM);
/* STM specific definition */
_estack = __stack;
/* Default stack sizes. These are used by the startup in order to allocate stacks for the different modes */
__Main_Stack_Size = 1024 ;
/* "PROVIDE" allows to easily override these values from an object file or the command line */
PROVIDE ( _Main_Stack_Size = __Main_Stack_Size );
__Main_Stack_Limit = __stack - __Main_Stack_Size ;
PROVIDE ( _Main_Stack_Limit = __Main_Stack_Limit ) ;
/* The default stack - There will be a link error if there is not this amount of RAM free at the end */
_Minimum_Stack_Size = 256 ;
/* End Stack Definitions *****************************************************/
/* Heap Definitions **********************************************************/
/* Default heap definitions.
* The heap start immediately after the last statically allocated
* .sbss/.noinit section, and extends up to the main stack limit.
*/
PROVIDE ( _Heap_Begin = _end_noinit ) ;
PROVIDE ( _Heap_Limit = __stack - __Main_Stack_Size ) ;
/* End Heap Definitions ******************************************************/
/* Entry Point Definitions ***************************************************/
/* The entry point is informative, for debuggers and simulators,
* since the Cortex-M vector points to it anyway.
*/
ENTRY(_start);
/* End Entry Point Definitions ***********************************************/
/* Section Definitions *******************************************************/
SECTIONS
{
/* Begin Section:.isr_vector **************************************************
Description : The interrupt section for Cortex-M devices.
Location : Flash
Component : .isr_vector - The ISR vector section.
.cfmconfig - The Freescale configuration words.
.after_vectors - The startup code and ISR.
******************************************************************************/
.isr_vector : ALIGN(4)
{
FILL(0xFF)
__vectors_start = ABSOLUTE(.) ;
/* STM specific definition */
__vectors_start__ = ABSOLUTE(.) ;
KEEP(*(.isr_vector))
*(privileged_functions)
/* Non privileged code is after _Privileged_Functions_Region_Size. */
__privileged_functions_actual_end__ = .;
. = _Privileged_Functions_Region_Size;
KEEP(*(.cfmconfig))
/* This section is here for convenience, to store the
* startup code at the beginning of the flash area, hoping that
* this will increase the readability of the listing.
*/
*(.after_vectors .after_vectors.*) /* Startup code and ISR */
} >FLASH
/* End Section:.isr_vector ***************************************************/
/* Begin Section:.inits *******************************************************
Description : Memory regions initialisation arrays. There are two kinds of arrays
for each RAM region, one for data and one for bss. Each is iterrated
at startup and the region initialisation is performed.
The data array includes:
- from (LOADADDR())
- region_begin (ADDR())
- region_end (ADDR()+SIZEOF())
The bss array includes:
- region_begin (ADDR())
- region_end (ADDR()+SIZEOF())
WARNING: It is mandatory that the regions are word aligned,
since the initialisation code works only on words.
Location : Flash
Component : .data.* - The data section initialization section.
.bss.* - The bss section initialization section.
.preinit_array - The preinit code to run before constructors.
.init_array - The constructor code for global C++ objects.
.fini_array - The destructor code for global C++ objects.
******************************************************************************/
.inits : ALIGN(4)
{
/* The data array */
__data_regions_array_start = .;
LONG(LOADADDR(.data));
LONG(ADDR(.data));
LONG(ADDR(.data)+SIZEOF(.data));
__data_regions_array_end = .;
/* The bss array */
__bss_regions_array_start = .;
LONG(ADDR(.bss));
LONG(ADDR(.bss)+SIZEOF(.bss));
__bss_regions_array_end = .;
/* These are the old initialisation sections, intended to contain
* naked code, with the prologue/epilogue added by crti.o/crtn.o
* when linking with startup files. The standalone startup code
* currently does not run these, better use the init arrays below.
*/
KEEP(*(.init))
KEEP(*(.fini))
. = ALIGN(4);
/* The preinit code, i.e. an array of pointers to initialisation
* functions to be performed before constructors.
*/
PROVIDE_HIDDEN (__preinit_array_start = .);
/* Used to run the SystemInit() before anything else. */
KEEP(*(.preinit_array_sysinit .preinit_array_sysinit.*))
/* Used for other platform inits. */
KEEP(*(.preinit_array_platform .preinit_array_platform.*))
/* The application inits. If you need to enforce some order in execution, create new sections, as before. */
KEEP(*(.preinit_array .preinit_array.*))
PROVIDE_HIDDEN (__preinit_array_end = .);
. = ALIGN(4);
/* The init code, i.e. an array of pointers to static constructors. */
PROVIDE_HIDDEN (__init_array_start = .);
KEEP(*(SORT(.init_array.*)))
KEEP(*(.init_array))
PROVIDE_HIDDEN (__init_array_end = .);
. = ALIGN(4);
/* The fini code, i.e. an array of pointers to static destructors. */
PROVIDE_HIDDEN (__fini_array_start = .);
KEEP(*(SORT(.fini_array.*)))
KEEP(*(.fini_array))
PROVIDE_HIDDEN (__fini_array_end = .);
} >FLASH
/* End Section:.inits ********************************************************/
/* Begin Section:.flashtext ***************************************************
Description : For some STRx devices, the beginning of the startup code is stored
in the .flashtext section, which goes to FLASH.
Location : Flash
Component : .flashtext - The STRx devices startup code.
******************************************************************************/
.flashtext : ALIGN(4)
{
*(.flashtext .flashtext.*)
} >FLASH
/* End Section:.flashtext ****************************************************/
/* Begin Section:.text ********************************************************
Description : The program code is stored in the .text section, which goes to FLASH.
Location : Flash
Component : .text - The code segment.
.rodata.* - The reaad-only data segment.
vtable - C++ vtable segment.
******************************************************************************/
.text : ALIGN(4)
{
/* All remaining code */
*(.text .text.*)
/* Read-only data (constants) */
*(.rodata .rodata.* .constdata .constdata.*)
/* C++ virtual tables */
*(vtable)
KEEP(*(.eh_frame*))
/* Stub sections generated by the linker, to glue together
* ARM and Thumb code. .glue_7 is used for ARM code calling
* Thumb code, and .glue_7t is used for Thumb code calling
* ARM code. Apparently always generated by the linker, for some
* architectures, so better leave them here.
*/
*(.glue_7)
*(.glue_7t)
} >FLASH
/* End Section:.text *********************************************************/
/* Begin Section:.ARM.extab,.ARM.exidx ****************************************
Description : ARM magic sections. You don't need them if you don't care about unwinding
(unwinding is useful for C++ exception and for debugging).
Location : Flash
Component : .ARM.extab - The ARM external tab for unwinding.
.ARM.exidx - The ARM external index for unwinding.
******************************************************************************/
.ARM.extab : ALIGN(4)
{
*(.ARM.extab* .gnu.linkonce.armextab.*)
} >FLASH
. = ALIGN(4);
__exidx_start = .;
.ARM.exidx : ALIGN(4)
{
*(.ARM.exidx* .gnu.linkonce.armexidx.*)
} >FLASH
__exidx_end = .;
. = ALIGN(4);
_etext = .;
__etext = .;
/* End Section:.ARM.extab,.ARM.exidx *****************************************/
/* Begin Section:.data ********************************************************
Description : The main initialized data section. The program executes knowing that
the data is in the RAM but the loader puts the initial values in the
FLASH (inidata). It is one task of the startup to copy the initial
values from FLASH to RAM.
Location : RAM
Component : .data - The sections to put into the RAM.
******************************************************************************/
/* Used by the startup code to initialise the .data section */
_sidata = LOADADDR(.data);
.data : ALIGN(8192)
{
FILL(0xFF)
/* This is used by the startup code to initialise the .data section */
_sdata = . ; /* STM specific definition */
__data_start__ = . ;
*(privileged_data)
/* Non kernel data is kept out of the first _Privileged_Data_Region_Size bytes of SRAM. */
__privileged_data_actual_end__ = .;
. = _Privileged_Data_Region_Size;
*(.data_begin .data_begin.*)
*(.data .data.*)
*(.data_end .data_end.*)
. = ALIGN(4);
/* This is used by the startup code to initialise the .data section */
_edata = . ; /* STM specific definition */
__data_end__ = . ;
} >RAM AT>FLASH
/* End Section:.data *********************************************************/
/* Begin Section:.bss *********************************************************
Description : The initialised-to-0 data sections. NOLOAD is used to avoid
the "section `.bss' type changed to PROGBITS" warning. This is the
main region which is placed in RAM.
Location : RAM
Component : .bss - The sections to put into the RAM, and initialized to 0.
******************************************************************************/
.bss (NOLOAD) : ALIGN(4)
{
__bss_start__ = .; /* standard newlib definition */
_sbss = .; /* STM specific definition */
*(.bss_begin .bss_begin.*)
*(.bss .bss.*)
*(COMMON)
*(.bss_end .bss_end.*)
. = ALIGN(4);
__bss_end__ = .; /* standard newlib definition */
_ebss = . ; /* STM specific definition */
} >RAM
/* End Section:.bss **********************************************************/
/* Begin Section:.noinit ******************************************************
Description : The uninitialised data sections. NOLOAD is used to avoid
the "section `.noinit' type changed to PROGBITS" warning.
Location : RAM
Component : .noinit - The sections to put into the RAM, and not initialized.
******************************************************************************/
.noinit (NOLOAD) : ALIGN(4)
{
_noinit = .;
*(.noinit .noinit.*)
. = ALIGN(4) ;
_end_noinit = .;
} >RAM
/* Mandatory to be word aligned, _sbrk assumes this */
PROVIDE ( end = _end_noinit ); /* was _ebss */
PROVIDE ( _end = _end_noinit );
PROVIDE ( __end = _end_noinit );
PROVIDE ( __end__ = _end_noinit );
/* End Section:.noinit *******************************************************/
/* Begin Section:._check_stack ************************************************
Description : Used for validation only, do not allocate anything here!
This is just to check that there is enough RAM left for the Main
stack. It should generate an error if it's full. This stack,
in composite, is the section for kernel stack. All the component
related layouts will be in the component sections that follow.
Location : RAM
Component : Padding of size "_Minimum_Stack_Size" - The stack location.
******************************************************************************/
._check_stack : ALIGN(4)
{
. = . + _Minimum_Stack_Size ;
} >RAM
/* End Section:._check_stack *************************************************/
/* Begin Section:.eromem0 *****************************************************
Description : This section should only be used when there is external read-only
direct-executable memory, such as Quad SPI Flash, Nor Flash, etc.
(Nand flash does not count!)
When there is no such sections, this can be commented out. When this
is used, use the section attribute to explicitly place the code/data.
Location : EROMEM0
Component : .ero0text - The code section in this area.
.ero0rodata - The ro-data section in this area.
******************************************************************************/
/*
.eromem0 : ALIGN(4)
{
*(.ero0text)
*(.ero0rodata)
*(.ero0rodata.*)
} >EROMEM0
*/
/* End Section:.eromem0 ******************************************************/
/* Begin Section:.erwmem0 *****************************************************
Description : This section should only be used when there is external read-write
direct-executable memory, such as SRAM, FRAM, SDRAM, etc.
When there is no such sections, this can be commented out. When this
is used, use the section attribute to explicitly place the code/data.
This section is not initialized in the init code. Thus, this area will
not be initialized at the startup. It is the user's duty to initialize
this area manually.
Location : EROMEM0
Component : .ero0text - The code section in this area.
.ero0rodata - The ro-data section in this area.
******************************************************************************/
.erwmem0 : ALIGN(4)
{
*(.erw0text)
*(.erw0data)
} >ERWMEM0
/* End Section:.erwmem0 ******************************************************/
/* Begin Section:.debugging ***************************************************
Description : These are debuggingsections.
Location : None.
Component : None.
******************************************************************************/
/* This can remove the debugging information from the standard libraries */
/*
DISCARD :
{
libc.a ( * )
libm.a ( * )
libgcc.a ( * )
}
*/
/* Stabs debugging sections. */
.stab 0 : { *(.stab) }
.stabstr 0 : { *(.stabstr) }
.stab.excl 0 : { *(.stab.excl) }
.stab.exclstr 0 : { *(.stab.exclstr) }
.stab.index 0 : { *(.stab.index) }
.stab.indexstr 0 : { *(.stab.indexstr) }
.comment 0 : { *(.comment) }
/*
* DWARF debug sections.
* Symbols in the DWARF debugging sections are relative to the beginning
* of the section so we begin them at 0.
*/
/* DWARF 1 */
.debug 0 : { *(.debug) }
.line 0 : { *(.line) }
/* GNU DWARF 1 extensions */
.debug_srcinfo 0 : { *(.debug_srcinfo) }
.debug_sfnames 0 : { *(.debug_sfnames) }
/* DWARF 1.1 and DWARF 2 */
.debug_aranges 0 : { *(.debug_aranges) }
.debug_pubnames 0 : { *(.debug_pubnames) }
/* DWARF 2 */
.debug_info 0 : { *(.debug_info .gnu.linkonce.wi.*) }
.debug_abbrev 0 : { *(.debug_abbrev) }
.debug_line 0 : { *(.debug_line) }
.debug_frame 0 : { *(.debug_frame) }
.debug_str 0 : { *(.debug_str) }
.debug_loc 0 : { *(.debug_loc) }
.debug_macinfo 0 : { *(.debug_macinfo) }
/* SGI/MIPS DWARF 2 extensions */
.debug_weaknames 0 : { *(.debug_weaknames) }
.debug_funcnames 0 : { *(.debug_funcnames) }
.debug_typenames 0 : { *(.debug_typenames) }
.debug_varnames 0 : { *(.debug_varnames) }
/* End Section:.debugging ****************************************************/
}
/* End Section Definitions ***************************************************/

@ -0,0 +1,41 @@
.thumb
.thumb_func
.global _start
_start:
@mov r0,=0x10000
@mov sp,r0
bl cortexm_entry
mov r7,#0x1
mov r0,#0
swi #0
.word 0xFFFFFFFF
b .
.thumb_func
.globl PUT32
PUT32:
str r1,[r0]
bx lr
.thumb_func
.globl GET32
GET32:
ldr r0,[r0]
bx lr
.thumb_func
.globl dummy
dummy:
bx lr
.thumb_func
.globl write
write:
push {r7,lr}
mov r7,#0x04
swi 0
pop {r7,pc}
b .
.end

File diff suppressed because it is too large Load Diff

@ -1,5 +1,26 @@
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <math.h>
#include <printf.h>
#include <setjmp.h>
#include <signal.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/uio.h>
#include "../runtime.h"
int main(int argc, char* argv[]) {
runtime_main(argc, argv);
}
// What should we tell the child program its UID and GID are?
#define UID 0xFF
#define GID 0xFE
@ -354,6 +375,12 @@ i32 wasm_lseek(i32 filedes, i32 file_offset, i32 whence) {
}
#define SYS_MMAP 9
#define MMAP_GRANULARITY 128
u32 last_expansion_final_index = 0;
u32 bump_ptr = 0;
u32 wasm_mmap(i32 addr, i32 len, i32 prot, i32 flags, i32 fd, i32 offset) {
if (addr != 0) {
printf("parameter void *addr is not supported!\n");
@ -365,15 +392,24 @@ u32 wasm_mmap(i32 addr, i32 len, i32 prot, i32 flags, i32 fd, i32 offset) {
assert(0);
}
assert(len % WASM_PAGE_SIZE == 0);
assert(len % MMAP_GRANULARITY == 0);
assert(WASM_PAGE_SIZE % MMAP_GRANULARITY == 0);
// Check if someone else has messed with the memory
// If so start bumping from the end
if (memory_size != last_expansion_final_index) {
bump_ptr = memory_size;
}
i32 result = memory_size;
for (int i = 0; i < len / WASM_PAGE_SIZE; i++) {
switch_out_of_runtime();
u32 result = bump_ptr;
bump_ptr += len;
while (bump_ptr > memory_size) {
expand_memory();
switch_into_runtime();
}
last_expansion_final_index = memory_size;
return result;
}

@ -24,7 +24,7 @@ void alloc_linear_memory() {
void expand_memory() {
// max_pages = 0 => no limit
assert(max_pages == 0 || (memory_size / WASM_PAGE_SIZE < max_pages));
silverfish_assert(max_pages == 0 || (memory_size / WASM_PAGE_SIZE < max_pages));
// Remap the relevant wasm page to readable
char* mem_as_chars = memory;
char* page_address = &mem_as_chars[memory_size];

@ -0,0 +1,159 @@
#include "../runtime.h"
void PUT32 ( unsigned int, unsigned int );
unsigned int GET32 ( unsigned int );
void dummy ( unsigned int );
void write ( unsigned int, char *, unsigned int );
void* memory;
u32 memory_size;
#define TOTAL_PAGES 6
char CORTEX_M_MEM[WASM_PAGE_SIZE * TOTAL_PAGES];
int printf_(const char* format, ...);
void alloc_linear_memory() {
printf_("8 = (%d %d) 16 = (%d %d) 32 = (%d %d) 64 = (%d %d)\n", sizeof(u8), sizeof(i8), sizeof(u16), sizeof(i16), sizeof(u32), sizeof(i32), sizeof(u64), sizeof(i64));
silverfish_assert(TOTAL_PAGES >= starting_pages);
memory = &CORTEX_M_MEM[0];
memory_size = starting_pages * WASM_PAGE_SIZE;
}
void expand_memory() {
// max_pages = 0 => no limit
silverfish_assert(max_pages == 0 || (memory_size / WASM_PAGE_SIZE < max_pages));
memory_size += WASM_PAGE_SIZE;
silverfish_assert(memory_size <= sizeof(CORTEX_M_MEM));
char* mem_as_chars = memory;
memset(&mem_as_chars[memory_size], 0, WASM_PAGE_SIZE);
memory_size += WASM_PAGE_SIZE;
}
INLINE char* get_memory_ptr_for_runtime(u32 offset, u32 bounds_check) {
char* mem_as_chars = (char *) memory;
char* address = &mem_as_chars[offset];
return address;
}
// All of these are pretty generic
INLINE float get_f32(i32 offset) {
silverfish_assert(offset <= memory_size - sizeof(float));
char* mem_as_chars = (char *) memory;
void* address = &mem_as_chars[offset];
return *(float *) address;
}
INLINE double get_f64(i32 offset) {
silverfish_assert(offset <= memory_size - sizeof(double));
char* mem_as_chars = (char *) memory;
void* address = &mem_as_chars[offset];
return *(double *) address;
}
INLINE i8 get_i8(i32 offset) {
// printf_("get %d <= %d - %d\n", offset, memory_size, sizeof(i8));
silverfish_assert(offset <= memory_size - sizeof(i8));
char* mem_as_chars = (char *) memory;
void* address = &mem_as_chars[offset];
return *(i8 *) address;
}
INLINE i16 get_i16(i32 offset) {
silverfish_assert(offset <= memory_size - sizeof(i16));
char* mem_as_chars = (char *) memory;
void* address = &mem_as_chars[offset];
return *(i16 *) address;
}
INLINE i32 get_i32(i32 offset) {
silverfish_assert(offset <= memory_size - sizeof(i32));
char* mem_as_chars = (char *) memory;
void* address = &mem_as_chars[offset];
return *(i32 *) address;
}
INLINE i64 get_i64(i32 offset) {
silverfish_assert(offset <= memory_size - sizeof(i64));
char* mem_as_chars = (char *) memory;
void* address = &mem_as_chars[offset];
return *(i64 *) address;
}
// Now setting routines
INLINE void set_f32(i32 offset, float v) {
silverfish_assert(offset <= memory_size - sizeof(float));
char* mem_as_chars = (char *) memory;
void* address = &mem_as_chars[offset];
*(float *) address = v;
}
INLINE void set_f64(i32 offset, double v) {
silverfish_assert(offset <= memory_size - sizeof(double));
char* mem_as_chars = (char *) memory;
void* address = &mem_as_chars[offset];
*(double *) address = v;
}
INLINE void set_i8(i32 offset, i8 v) {
// printf_("set %d <= %d - %d\n", offset, memory_size, sizeof(i8));
silverfish_assert(offset <= memory_size - sizeof(i8));
char* mem_as_chars = (char *) memory;
void* address = &mem_as_chars[offset];
*(i8 *) address = v;
}
INLINE void set_i16(i32 offset, i16 v) {
silverfish_assert(offset <= memory_size - sizeof(i16));
char* mem_as_chars = (char *) memory;
void* address = &mem_as_chars[offset];
*(i16 *) address = v;
}
INLINE void set_i32(i32 offset, i32 v) {
silverfish_assert(offset <= memory_size - sizeof(i32));
char* mem_as_chars = (char *) memory;
void* address = &mem_as_chars[offset];
*(i32 *) address = v;
}
INLINE void set_i64(i32 offset, i64 v) {
silverfish_assert(offset <= memory_size - sizeof(i64));
char* mem_as_chars = (char *) memory;
void* address = &mem_as_chars[offset];
*(i64 *) address = v;
}
INLINE char* get_function_from_table(u32 idx, u32 type_id) {
silverfish_assert(idx < INDIRECT_TABLE_SIZE);
struct indirect_table_entry f = indirect_table[idx];
silverfish_assert(f.type_id == type_id && f.func_pointer);
return f.func_pointer;
}
// Functions that aren't useful for this runtime
INLINE void switch_into_runtime() { return; }
INLINE void switch_out_of_runtime() { return; }

@ -10,10 +10,10 @@ void alloc_linear_memory() {
void expand_memory() {
// max_pages = 0 => no limit
assert(max_pages == 0 || (memory_size / WASM_PAGE_SIZE < max_pages));
silverfish_assert(max_pages == 0 || (memory_size / WASM_PAGE_SIZE < max_pages));
memory = realloc(memory, memory_size + WASM_PAGE_SIZE);
assert(memory);
silverfish_assert(memory);
char* mem_as_chars = memory;
memset(&mem_as_chars[memory_size], 0, WASM_PAGE_SIZE);
@ -21,7 +21,7 @@ void expand_memory() {
}
INLINE char* get_memory_ptr_for_runtime(u32 offset, u32 bounds_check) {
assert(memory_size > bounds_check && offset <= memory_size - bounds_check);
silverfish_assert(memory_size > bounds_check && offset <= memory_size - bounds_check);
char* mem_as_chars = (char *) memory;
char* address = &mem_as_chars[offset];
@ -31,7 +31,7 @@ INLINE char* get_memory_ptr_for_runtime(u32 offset, u32 bounds_check) {
// All of these are pretty generic
INLINE float get_f32(i32 offset) {
assert(offset <= memory_size - sizeof(float));
silverfish_assert(offset <= memory_size - sizeof(float));
char* mem_as_chars = (char *) memory;
void* address = &mem_as_chars[offset];
@ -40,7 +40,7 @@ INLINE float get_f32(i32 offset) {
}
INLINE double get_f64(i32 offset) {
assert(offset <= memory_size - sizeof(double));
silverfish_assert(offset <= memory_size - sizeof(double));
char* mem_as_chars = (char *) memory;
void* address = &mem_as_chars[offset];
@ -48,7 +48,7 @@ INLINE double get_f64(i32 offset) {
}
INLINE i8 get_i8(i32 offset) {
assert(offset <= memory_size - sizeof(i8));
silverfish_assert(offset <= memory_size - sizeof(i8));
char* mem_as_chars = (char *) memory;
void* address = &mem_as_chars[offset];
@ -56,7 +56,7 @@ INLINE i8 get_i8(i32 offset) {
}
INLINE i16 get_i16(i32 offset) {
assert(offset <= memory_size - sizeof(i16));
silverfish_assert(offset <= memory_size - sizeof(i16));
char* mem_as_chars = (char *) memory;
void* address = &mem_as_chars[offset];
@ -64,7 +64,7 @@ INLINE i16 get_i16(i32 offset) {
}
INLINE i32 get_i32(i32 offset) {
assert(offset <= memory_size - sizeof(i32));
silverfish_assert(offset <= memory_size - sizeof(i32));
char* mem_as_chars = (char *) memory;
void* address = &mem_as_chars[offset];
@ -72,7 +72,7 @@ INLINE i32 get_i32(i32 offset) {
}
INLINE i64 get_i64(i32 offset) {
assert(offset <= memory_size - sizeof(i64));
silverfish_assert(offset <= memory_size - sizeof(i64));
char* mem_as_chars = (char *) memory;
void* address = &mem_as_chars[offset];
@ -81,7 +81,7 @@ INLINE i64 get_i64(i32 offset) {
// Now setting routines
INLINE void set_f32(i32 offset, float v) {
assert(offset <= memory_size - sizeof(float));
silverfish_assert(offset <= memory_size - sizeof(float));
char* mem_as_chars = (char *) memory;
void* address = &mem_as_chars[offset];
@ -89,7 +89,7 @@ INLINE void set_f32(i32 offset, float v) {
}
INLINE void set_f64(i32 offset, double v) {
assert(offset <= memory_size - sizeof(double));
silverfish_assert(offset <= memory_size - sizeof(double));
char* mem_as_chars = (char *) memory;
void* address = &mem_as_chars[offset];
@ -97,7 +97,7 @@ INLINE void set_f64(i32 offset, double v) {
}
INLINE void set_i8(i32 offset, i8 v) {
assert(offset <= memory_size - sizeof(i8));
silverfish_assert(offset <= memory_size - sizeof(i8));
char* mem_as_chars = (char *) memory;
void* address = &mem_as_chars[offset];
@ -105,7 +105,7 @@ INLINE void set_i8(i32 offset, i8 v) {
}
INLINE void set_i16(i32 offset, i16 v) {
assert(offset <= memory_size - sizeof(i16));
silverfish_assert(offset <= memory_size - sizeof(i16));
char* mem_as_chars = (char *) memory;
void* address = &mem_as_chars[offset];
@ -113,7 +113,7 @@ INLINE void set_i16(i32 offset, i16 v) {
}
INLINE void set_i32(i32 offset, i32 v) {
assert(offset <= memory_size - sizeof(i32));
silverfish_assert(offset <= memory_size - sizeof(i32));
char* mem_as_chars = (char *) memory;
void* address = &mem_as_chars[offset];
@ -121,7 +121,7 @@ INLINE void set_i32(i32 offset, i32 v) {
}
INLINE void set_i64(i32 offset, i64 v) {
assert(offset <= memory_size - sizeof(i64));
silverfish_assert(offset <= memory_size - sizeof(i64));
char* mem_as_chars = (char *) memory;
void* address = &mem_as_chars[offset];
@ -129,11 +129,11 @@ INLINE void set_i64(i32 offset, i64 v) {
}
INLINE char* get_function_from_table(u32 idx, u32 type_id) {
assert(idx < INDIRECT_TABLE_SIZE);
silverfish_assert(idx < INDIRECT_TABLE_SIZE);
struct indirect_table_entry f = indirect_table[idx];
assert(f.type_id == type_id && f.func_pointer);
silverfish_assert(f.type_id == type_id && f.func_pointer);
return f.func_pointer;
}

@ -5,8 +5,9 @@
// Region initialization helper function
EXPORT void initialize_region(u32 offset, u32 data_count, char* data) {
assert(memory_size >= data_count);
assert(offset < memory_size - data_count);
silverfish_assert(memory_size >= data_count);
silverfish_assert(offset < memory_size - data_count);
// silverfish_assert(offset <= memory_size - data_count);
// FIXME: Hack around segmented and unsegmented access
memcpy(get_memory_ptr_for_runtime(offset, data_count), data, data_count);
@ -15,7 +16,7 @@ EXPORT void initialize_region(u32 offset, u32 data_count, char* data) {
struct indirect_table_entry indirect_table[INDIRECT_TABLE_SIZE];
void add_function_to_table(u32 idx, u32 type_id, char* pointer) {
assert(idx < INDIRECT_TABLE_SIZE);
silverfish_assert(idx < INDIRECT_TABLE_SIZE);
indirect_table[idx] = (struct indirect_table_entry) { .type_id = type_id, .func_pointer = pointer };
}
@ -60,42 +61,42 @@ INLINE u64 rotr_u64(u64 n, u64 c_u64) {
// Now safe division and remainder
INLINE u32 u32_div(u32 a, u32 b) {
assert(b);
silverfish_assert(b);
return a / b;
}
INLINE u32 u32_rem(u32 a, u32 b) {
assert(b);
silverfish_assert(b);
return a % b;
}
INLINE i32 i32_div(i32 a, i32 b) {
assert(b && (a != INT32_MIN || b != -1));
silverfish_assert(b && (a != INT32_MIN || b != -1));
return a / b;
}
INLINE i32 i32_rem(i32 a, i32 b) {
assert(b && (a != INT32_MIN || b != -1));
silverfish_assert(b && (a != INT32_MIN || b != -1));
return a % b;
}
INLINE u64 u64_div(u64 a, u64 b) {
assert(b);
silverfish_assert(b);
return a / b;
}
INLINE u64 u64_rem(u64 a, u64 b) {
assert(b);
silverfish_assert(b);
return a % b;
}
INLINE i64 i64_div(i64 a, i64 b) {
assert(b && (a != INT64_MIN || b != -1));
silverfish_assert(b && (a != INT64_MIN || b != -1));
return a / b;
}
INLINE i64 i64_rem(i64 a, i64 b) {
assert(b && (a != INT64_MIN || b != -1));
silverfish_assert(b && (a != INT64_MIN || b != -1));
return a % b;
}
@ -105,42 +106,42 @@ INLINE i64 i64_rem(i64 a, i64 b) {
// In C, float => int conversions always truncate
// If a int2float(int::min_value) <= float <= int2float(int::max_value), it must always be safe to truncate it
u32 u32_trunc_f32(float f) {
assert(0 <= f && f <= UINT32_MAX);
silverfish_assert(0 <= f && f <= UINT32_MAX);
return (u32) f;
}
i32 i32_trunc_f32(float f) {
assert(INT32_MIN <= f && f <= INT32_MAX );
silverfish_assert(INT32_MIN <= f && f <= INT32_MAX );
return (i32) f;
}
u32 u32_trunc_f64(double f) {
assert(0 <= f && f <= UINT32_MAX);
silverfish_assert(0 <= f && f <= UINT32_MAX);
return (u32) f;
}
i32 i32_trunc_f64(double f) {
assert(INT32_MIN <= f && f <= INT32_MAX );
silverfish_assert(INT32_MIN <= f && f <= INT32_MAX );
return (i32) f;
}
u64 u64_trunc_f32(float f) {
assert(0 <= f && f <= UINT64_MAX);
silverfish_assert(0 <= f && f <= UINT64_MAX);
return (u64) f;
}
i64 i64_trunc_f32(float f) {
assert(INT64_MIN <= f && f <= INT64_MAX);
silverfish_assert(INT64_MIN <= f && f <= INT64_MAX);
return (i64) f;
}
u64 u64_trunc_f64(double f) {
assert(0 <= f && f <= UINT64_MAX);
silverfish_assert(0 <= f && f <= UINT64_MAX);
return (u64) f;
}
i64 i64_trunc_f64(double f) {
assert(INT64_MIN <= f && f <= INT64_MAX);
silverfish_assert(INT64_MIN <= f && f <= INT64_MAX);
return (i64) f;
}
@ -166,27 +167,28 @@ INLINE double f64_max(double a, double b) {
}
// FIXME: Currently the timer support stuff is disabled, pending cortex_m results
// this provides a way to add a timeout for wasm execution, and support for that
// TODO: Add a way for silverfish to give us this value
WEAK unsigned int wasm_execution_timeout_ms = 0;
sigjmp_buf timeout_jump;
#define JUMPING_BACK 0xBACC
//WEAK unsigned int wasm_execution_timeout_ms = 0;
//sigjmp_buf timeout_jump;
//#define JUMPING_BACK 0xBACC
// Precondition: you've already loaded timeout_jump with where we should jump after the timeout
void handle_sigalarm(int sig) {
// TODO: We use siglongjmp which resets signal stuff, so perhaps this call is unnessesary
signal(sig, SIG_IGN);
siglongjmp(timeout_jump, JUMPING_BACK);
}
void schedule_timeout() {
signal(SIGALRM, handle_sigalarm);
ualarm(wasm_execution_timeout_ms * 1000, 0);
}
void cancel_timeout() {
ualarm(0, 0);
}
//void handle_sigalarm(int sig) {
// // TODO: We use siglongjmp which resets signal stuff, so perhaps this call is unnessesary
// signal(sig, SIG_IGN);
// siglongjmp(timeout_jump, JUMPING_BACK);
//}
//
//void schedule_timeout() {
// signal(SIGALRM, handle_sigalarm);
// ualarm(wasm_execution_timeout_ms * 1000, 0);
//}
//
//void cancel_timeout() {
// ualarm(0, 0);
//}
// If we are using runtime globals, we need to populate them
WEAK void populate_globals() {}
@ -194,7 +196,7 @@ WEAK void populate_globals() {}
// Code that actually runs the wasm code
IMPORT i32 wasmf_main(i32 a, i32 b);
int main(int argc, char* argv[]) {
int runtime_main(int argc, char** argv) {
// Setup the linear memory and function table
alloc_linear_memory();
populate_table();
@ -206,16 +208,16 @@ int main(int argc, char* argv[]) {
populate_memory();
// In the case of a real timeout being compiled in, handle that
if (wasm_execution_timeout_ms) {
// Set the jumpoint to here, and save the signal mask
int res = sigsetjmp(timeout_jump, 1);
if (res != 0) {
assert(res == JUMPING_BACK);
printf("WE DECIDED TO GIVE UP\n");
return -JUMPING_BACK;
}
schedule_timeout();
}
// if (wasm_execution_timeout_ms) {
// // Set the jumpoint to here, and save the signal mask
// int res = sigsetjmp(timeout_jump, 1);
// if (res != 0) {
// assert(res == JUMPING_BACK);
// printf("WE DECIDED TO GIVE UP\n");
// return -JUMPING_BACK;
// }
// schedule_timeout();
// }
// What follows is a huge cludge
@ -249,9 +251,8 @@ int main(int argc, char* argv[]) {
switch_into_runtime();
// Cancel any pending timeout
if (wasm_execution_timeout_ms) {
cancel_timeout();
}
// if (wasm_execution_timeout_ms) {
// cancel_timeout();
// }
return ret;
}

@ -1,37 +1,80 @@
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <math.h>
#include <printf.h>
#include <setjmp.h>
#include <signal.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/uio.h>
#define EXPORT __attribute__ ((visibility ("default")))
#define IMPORT __attribute__ ((visibility ("default")))
#define INLINE __attribute__((always_inline))
#define WEAK __attribute__((weak))
#if __has_include("assert.h")
#include <assert.h>
#define silverfish_assert assert
#else
void write ( unsigned int, char *, unsigned int );
#define silverfish_assert(x) do { if(!(x)) { char msg[] = "" #x ""; write(1, msg, sizeof(msg)); while(1); } } while(0);
#endif
// Type alias's so I don't have to write uint32_t a million times
typedef signed char i8;
typedef unsigned char u8;
#if __has_include("stdint.h")
#include <stdint.h>
typedef int16_t i16;
typedef uint16_t u16;
typedef int32_t i32;
typedef uint32_t u32;
typedef int64_t i64;
typedef uint64_t u64;
#else
// FIXME: Cortex-m specific hack
typedef signed short i16;
typedef unsigned short u16;
typedef signed int i32;
typedef unsigned int u32;
typedef signed long long i64;
typedef unsigned long long u64;
#endif
#if __has_include("string.h") && __has_include("math.h") && __has_include("stdio.h") && __has_include("stdlib.h")
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#else
#define size_t u32
#define CORTEX_M
void* memcpy(void *dest, const void *src, size_t len);
void *memset(void *s, int c, size_t n);
char* strcpy(char* dest, const char* src);
size_t strlen(const char* str);
double trunc(double x);
float truncf(float x);
#endif
#if __has_include("limits.h")
#include <limits.h>
#else
#define CHAR_BIT 8
#define INT8_MIN (-1-0x7f)
#define INT16_MIN (-1-0x7fff)
#define INT32_MIN (-1-0x7fffffff)
#define INT64_MIN (-1-0x7fffffffffffffff)
#define INT8_MAX (0x7f)
#define INT16_MAX (0x7fff)
#define INT32_MAX (0x7fffffff)
#define INT64_MAX (0x7fffffffffffffff)
#define UINT8_MAX (0xff)
#define UINT16_MAX (0xffff)
#define UINT32_MAX (0xffffffff)
#define UINT64_MAX (0xffffffffffffffff)
#endif
#define WASM_PAGE_SIZE (1024 * 64)
@ -88,3 +131,6 @@ INLINE char* get_function_from_table(u32 idx, u32 type_id);
// libc/* might need to do some setup for the libc setup
void stub_init(i32 offset);
// The runtime entrypoint must be called
int runtime_main(int argc, char** argv);

@ -0,0 +1,431 @@
/******************************************************************************
Filename : sections.ld
Author : eclipse-arm-gcc team, pry(modified)
Date : 27/02/2017
Description : Default linker script for Cortex-M (it includes specifics for STM32F[34]xx).
To make use of the multi-region initialisations, define
OS_INCLUDE_STARTUP_INIT_MULTIPLE_RAM_SECTIONS for the _startup.c file.
******************************************************************************/
/* Memory Definitions *********************************************************
Description : This section will define the memory layout of the sytem. This section
requires modifying for a specific board. Typical settings for different
chips are listed below:
DTCM 64K, SRAM1 240K, SRAM2 16K, Flash 512k (R320/F512) - STM32F746
DTCM 128K, SRAM1 368K, SRAM2 16K, Flash 1024k (R512/F1024) - STM32F767
DTCM 128K, SRAM1 368K, SRAM2 16K, Flash 2048k (R1024/F2048) - STM32Hxxx
Component : .ORIGIN - Starting address of the memory region.
.LENGTH - Length of the region.
******************************************************************************/
MEMORY
{
RAM (xrw) : ORIGIN = 0x20000000, LENGTH = 512K
FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 1024K
EROMEM0 (rx) : ORIGIN = 0x00000000, LENGTH = 0
ERWMEM0 (xrw) : ORIGIN = 0xC0000000, LENGTH = 32768K
}
_Privileged_Functions_Region_Size = 32K;
_Privileged_Data_Region_Size = 512;
__FLASH_segment_start__ = ORIGIN( FLASH );
__FLASH_segment_end__ = __FLASH_segment_start__ + LENGTH( FLASH );
__privileged_functions_start__ = ORIGIN( FLASH );
__privileged_functions_end__ = __privileged_functions_start__ + _Privileged_Functions_Region_Size;
__SRAM_segment_start__ = ORIGIN( RAM );
__SRAM_segment_end__ = __SRAM_segment_start__ + LENGTH( RAM );
__privileged_data_start__ = ORIGIN( RAM );
__privileged_data_end__ = ORIGIN( RAM ) + _Privileged_Data_Region_Size;
/* End Memory Definitions ****************************************************/
/* Stack Definitions *********************************************************/
/* The '__stack' definition is required by crt0, do not remove it. */
__stack = ORIGIN(RAM) + LENGTH(RAM);
/* STM specific definition */
_estack = __stack;
/* Default stack sizes. These are used by the startup in order to allocate stacks for the different modes */
__Main_Stack_Size = 1024 ;
/* "PROVIDE" allows to easily override these values from an object file or the command line */
PROVIDE ( _Main_Stack_Size = __Main_Stack_Size );
__Main_Stack_Limit = __stack - __Main_Stack_Size ;
PROVIDE ( _Main_Stack_Limit = __Main_Stack_Limit ) ;
/* The default stack - There will be a link error if there is not this amount of RAM free at the end */
_Minimum_Stack_Size = 256 ;
/* End Stack Definitions *****************************************************/
/* Heap Definitions **********************************************************/
/* Default heap definitions.
* The heap start immediately after the last statically allocated
* .sbss/.noinit section, and extends up to the main stack limit.
*/
PROVIDE ( _Heap_Begin = _end_noinit ) ;
PROVIDE ( _Heap_Limit = __stack - __Main_Stack_Size ) ;
/* End Heap Definitions ******************************************************/
/* Entry Point Definitions ***************************************************/
/* The entry point is informative, for debuggers and simulators,
* since the Cortex-M vector points to it anyway.
*/
ENTRY(_start);
/* End Entry Point Definitions ***********************************************/
/* Section Definitions *******************************************************/
SECTIONS
{
/* Begin Section:.isr_vector **************************************************
Description : The interrupt section for Cortex-M devices.
Location : Flash
Component : .isr_vector - The ISR vector section.
.cfmconfig - The Freescale configuration words.
.after_vectors - The startup code and ISR.
******************************************************************************/
.isr_vector : ALIGN(4)
{
FILL(0xFF)
__vectors_start = ABSOLUTE(.) ;
/* STM specific definition */
__vectors_start__ = ABSOLUTE(.) ;
KEEP(*(.isr_vector))
*(privileged_functions)
/* Non privileged code is after _Privileged_Functions_Region_Size. */
__privileged_functions_actual_end__ = .;
. = _Privileged_Functions_Region_Size;
KEEP(*(.cfmconfig))
/* This section is here for convenience, to store the
* startup code at the beginning of the flash area, hoping that
* this will increase the readability of the listing.
*/
*(.after_vectors .after_vectors.*) /* Startup code and ISR */
} >FLASH
/* End Section:.isr_vector ***************************************************/
/* Begin Section:.inits *******************************************************
Description : Memory regions initialisation arrays. There are two kinds of arrays
for each RAM region, one for data and one for bss. Each is iterrated
at startup and the region initialisation is performed.
The data array includes:
- from (LOADADDR())
- region_begin (ADDR())
- region_end (ADDR()+SIZEOF())
The bss array includes:
- region_begin (ADDR())
- region_end (ADDR()+SIZEOF())
WARNING: It is mandatory that the regions are word aligned,
since the initialisation code works only on words.
Location : Flash
Component : .data.* - The data section initialization section.
.bss.* - The bss section initialization section.
.preinit_array - The preinit code to run before constructors.
.init_array - The constructor code for global C++ objects.
.fini_array - The destructor code for global C++ objects.
******************************************************************************/
.inits : ALIGN(4)
{
/* The data array */
__data_regions_array_start = .;
LONG(LOADADDR(.data));
LONG(ADDR(.data));
LONG(ADDR(.data)+SIZEOF(.data));
__data_regions_array_end = .;
/* The bss array */
__bss_regions_array_start = .;
LONG(ADDR(.bss));
LONG(ADDR(.bss)+SIZEOF(.bss));
__bss_regions_array_end = .;
/* These are the old initialisation sections, intended to contain
* naked code, with the prologue/epilogue added by crti.o/crtn.o
* when linking with startup files. The standalone startup code
* currently does not run these, better use the init arrays below.
*/
KEEP(*(.init))
KEEP(*(.fini))
. = ALIGN(4);
/* The preinit code, i.e. an array of pointers to initialisation
* functions to be performed before constructors.
*/
PROVIDE_HIDDEN (__preinit_array_start = .);
/* Used to run the SystemInit() before anything else. */
KEEP(*(.preinit_array_sysinit .preinit_array_sysinit.*))
/* Used for other platform inits. */
KEEP(*(.preinit_array_platform .preinit_array_platform.*))
/* The application inits. If you need to enforce some order in execution, create new sections, as before. */
KEEP(*(.preinit_array .preinit_array.*))
PROVIDE_HIDDEN (__preinit_array_end = .);
. = ALIGN(4);
/* The init code, i.e. an array of pointers to static constructors. */
PROVIDE_HIDDEN (__init_array_start = .);
KEEP(*(SORT(.init_array.*)))
KEEP(*(.init_array))
PROVIDE_HIDDEN (__init_array_end = .);
. = ALIGN(4);
/* The fini code, i.e. an array of pointers to static destructors. */
PROVIDE_HIDDEN (__fini_array_start = .);
KEEP(*(SORT(.fini_array.*)))
KEEP(*(.fini_array))
PROVIDE_HIDDEN (__fini_array_end = .);
} >FLASH
/* End Section:.inits ********************************************************/
/* Begin Section:.flashtext ***************************************************
Description : For some STRx devices, the beginning of the startup code is stored
in the .flashtext section, which goes to FLASH.
Location : Flash
Component : .flashtext - The STRx devices startup code.
******************************************************************************/
.flashtext : ALIGN(4)
{
*(.flashtext .flashtext.*)
} >FLASH
/* End Section:.flashtext ****************************************************/
/* Begin Section:.text ********************************************************
Description : The program code is stored in the .text section, which goes to FLASH.
Location : Flash
Component : .text - The code segment.
.rodata.* - The reaad-only data segment.
vtable - C++ vtable segment.
******************************************************************************/
.text : ALIGN(4)
{
/* All remaining code */
*(.text .text.*)
/* Read-only data (constants) */
*(.rodata .rodata.* .constdata .constdata.*)
/* C++ virtual tables */
*(vtable)
KEEP(*(.eh_frame*))
/* Stub sections generated by the linker, to glue together
* ARM and Thumb code. .glue_7 is used for ARM code calling
* Thumb code, and .glue_7t is used for Thumb code calling
* ARM code. Apparently always generated by the linker, for some
* architectures, so better leave them here.
*/
*(.glue_7)
*(.glue_7t)
} >FLASH
/* End Section:.text *********************************************************/
/* Begin Section:.ARM.extab,.ARM.exidx ****************************************
Description : ARM magic sections. You don't need them if you don't care about unwinding
(unwinding is useful for C++ exception and for debugging).
Location : Flash
Component : .ARM.extab - The ARM external tab for unwinding.
.ARM.exidx - The ARM external index for unwinding.
******************************************************************************/
.ARM.extab : ALIGN(4)
{
*(.ARM.extab* .gnu.linkonce.armextab.*)
} >FLASH
. = ALIGN(4);
__exidx_start = .;
.ARM.exidx : ALIGN(4)
{
*(.ARM.exidx* .gnu.linkonce.armexidx.*)
} >FLASH
__exidx_end = .;
. = ALIGN(4);
_etext = .;
__etext = .;
/* End Section:.ARM.extab,.ARM.exidx *****************************************/
/* Begin Section:.data ********************************************************
Description : The main initialized data section. The program executes knowing that
the data is in the RAM but the loader puts the initial values in the
FLASH (inidata). It is one task of the startup to copy the initial
values from FLASH to RAM.
Location : RAM
Component : .data - The sections to put into the RAM.
******************************************************************************/
/* Used by the startup code to initialise the .data section */
_sidata = LOADADDR(.data);
.data : ALIGN(8192)
{
FILL(0xFF)
/* This is used by the startup code to initialise the .data section */
_sdata = . ; /* STM specific definition */
__data_start__ = . ;
*(privileged_data)
/* Non kernel data is kept out of the first _Privileged_Data_Region_Size bytes of SRAM. */
__privileged_data_actual_end__ = .;
. = _Privileged_Data_Region_Size;
*(.data_begin .data_begin.*)
*(.data .data.*)
*(.data_end .data_end.*)
. = ALIGN(4);
/* This is used by the startup code to initialise the .data section */
_edata = . ; /* STM specific definition */
__data_end__ = . ;
} >RAM AT>FLASH
/* End Section:.data *********************************************************/
/* Begin Section:.bss *********************************************************
Description : The initialised-to-0 data sections. NOLOAD is used to avoid
the "section `.bss' type changed to PROGBITS" warning. This is the
main region which is placed in RAM.
Location : RAM
Component : .bss - The sections to put into the RAM, and initialized to 0.
******************************************************************************/
.bss (NOLOAD) : ALIGN(4)
{
__bss_start__ = .; /* standard newlib definition */
_sbss = .; /* STM specific definition */
*(.bss_begin .bss_begin.*)
*(.bss .bss.*)
*(COMMON)
*(.bss_end .bss_end.*)
. = ALIGN(4);
__bss_end__ = .; /* standard newlib definition */
_ebss = . ; /* STM specific definition */
} >RAM
/* End Section:.bss **********************************************************/
/* Begin Section:.noinit ******************************************************
Description : The uninitialised data sections. NOLOAD is used to avoid
the "section `.noinit' type changed to PROGBITS" warning.
Location : RAM
Component : .noinit - The sections to put into the RAM, and not initialized.
******************************************************************************/
.noinit (NOLOAD) : ALIGN(4)
{
_noinit = .;
*(.noinit .noinit.*)
. = ALIGN(4) ;
_end_noinit = .;
} >RAM
/* Mandatory to be word aligned, _sbrk assumes this */
PROVIDE ( end = _end_noinit ); /* was _ebss */
PROVIDE ( _end = _end_noinit );
PROVIDE ( __end = _end_noinit );
PROVIDE ( __end__ = _end_noinit );
/* End Section:.noinit *******************************************************/
/* Begin Section:._check_stack ************************************************
Description : Used for validation only, do not allocate anything here!
This is just to check that there is enough RAM left for the Main
stack. It should generate an error if it's full. This stack,
in composite, is the section for kernel stack. All the component
related layouts will be in the component sections that follow.
Location : RAM
Component : Padding of size "_Minimum_Stack_Size" - The stack location.
******************************************************************************/
._check_stack : ALIGN(4)
{
. = . + _Minimum_Stack_Size ;
} >RAM
/* End Section:._check_stack *************************************************/
/* Begin Section:.eromem0 *****************************************************
Description : This section should only be used when there is external read-only
direct-executable memory, such as Quad SPI Flash, Nor Flash, etc.
(Nand flash does not count!)
When there is no such sections, this can be commented out. When this
is used, use the section attribute to explicitly place the code/data.
Location : EROMEM0
Component : .ero0text - The code section in this area.
.ero0rodata - The ro-data section in this area.
******************************************************************************/
/*
.eromem0 : ALIGN(4)
{
*(.ero0text)
*(.ero0rodata)
*(.ero0rodata.*)
} >EROMEM0
*/
/* End Section:.eromem0 ******************************************************/
/* Begin Section:.erwmem0 *****************************************************
Description : This section should only be used when there is external read-write
direct-executable memory, such as SRAM, FRAM, SDRAM, etc.
When there is no such sections, this can be commented out. When this
is used, use the section attribute to explicitly place the code/data.
This section is not initialized in the init code. Thus, this area will
not be initialized at the startup. It is the user's duty to initialize
this area manually.
Location : EROMEM0
Component : .ero0text - The code section in this area.
.ero0rodata - The ro-data section in this area.
******************************************************************************/
.erwmem0 : ALIGN(4)
{
*(.erw0text)
*(.erw0data)
} >ERWMEM0
/* End Section:.erwmem0 ******************************************************/
/* Begin Section:.debugging ***************************************************
Description : These are debuggingsections.
Location : None.
Component : None.
******************************************************************************/
/* This can remove the debugging information from the standard libraries */
/*
DISCARD :
{
libc.a ( * )
libm.a ( * )
libgcc.a ( * )
}
*/
/* Stabs debugging sections. */
.stab 0 : { *(.stab) }
.stabstr 0 : { *(.stabstr) }
.stab.excl 0 : { *(.stab.excl) }
.stab.exclstr 0 : { *(.stab.exclstr) }
.stab.index 0 : { *(.stab.index) }
.stab.indexstr 0 : { *(.stab.indexstr) }
.comment 0 : { *(.comment) }
/*
* DWARF debug sections.
* Symbols in the DWARF debugging sections are relative to the beginning
* of the section so we begin them at 0.
*/
/* DWARF 1 */
.debug 0 : { *(.debug) }
.line 0 : { *(.line) }
/* GNU DWARF 1 extensions */
.debug_srcinfo 0 : { *(.debug_srcinfo) }
.debug_sfnames 0 : { *(.debug_sfnames) }
/* DWARF 1.1 and DWARF 2 */
.debug_aranges 0 : { *(.debug_aranges) }
.debug_pubnames 0 : { *(.debug_pubnames) }
/* DWARF 2 */
.debug_info 0 : { *(.debug_info .gnu.linkonce.wi.*) }
.debug_abbrev 0 : { *(.debug_abbrev) }
.debug_line 0 : { *(.debug_line) }
.debug_frame 0 : { *(.debug_frame) }
.debug_str 0 : { *(.debug_str) }
.debug_loc 0 : { *(.debug_loc) }
.debug_macinfo 0 : { *(.debug_macinfo) }
/* SGI/MIPS DWARF 2 extensions */
.debug_weaknames 0 : { *(.debug_weaknames) }
.debug_funcnames 0 : { *(.debug_funcnames) }
.debug_typenames 0 : { *(.debug_typenames) }
.debug_varnames 0 : { *(.debug_varnames) }
/* End Section:.debugging ****************************************************/
}
/* End Section Definitions ***************************************************/

@ -55,7 +55,8 @@ pub fn process_to_llvm(
// Setup to compile to the local target
// FIXME: Should be able to use the local default target, but that doesn't work properly on OSX
llvm_module.set_target("x86_64-apple-macosx10.14.0");
llvm_module.set_target("x86_64-apple-macosx10.15.0");
// llvm_module.set_target("thumbv7m-none-unknown-eabi");
// llvm_module.set_target("i686-pc-linux-gnu");
// Remap WASM generated names to exported names

Loading…
Cancel
Save