Skip to content

Commit

Permalink
wutnewlib: implement abort, assert and assert_func (#337)
Browse files Browse the repository at this point in the history
* wutnewlib: implement abort, assert and assert_func

* wut_newlib: Trigger trap instruction on assert/abort

* wut_newlib: Replace snprintf with cafe-os equivalent.
  • Loading branch information
Maschell authored Jan 15, 2024
1 parent f1019f6 commit 1adf474
Showing 1 changed file with 68 additions and 0 deletions.
68 changes: 68 additions & 0 deletions libraries/wutnewlib/wut_newlib.c
Original file line number Diff line number Diff line change
@@ -1,9 +1,77 @@
#include "wut_newlib.h"
#include <coreinit/exit.h>
#include <coreinit/debug.h>
#include <coreinit/internal.h>
#include <stdio.h>
#include <string.h>

void(*__wut_exit)(int rc);
extern void __fini_wut(void);

void __attribute__((weak))
abort(void) {
const char *error_text = "Abort called.\n";
if (OSIsDebuggerPresent()) {
__asm__ __volatile__("mr 3, %0\n" // load 'tmp' into r3
"tw 0x1f, 31, 31" // DBGSTR_INSTRUCTION
:
: "r"(error_text)
: "r3");
}
OSFatal(error_text);
/* NOTREACHED */
while (1);
}

void __attribute__((weak))
__assert_func(const char *file,
int line,
const char *func,
const char *failedexpr)
{
char tmp[512] = {};
char buffer[512] = {};

__os_snprintf(tmp, sizeof(tmp), "assertion \"%s\" failed:\n file \"%s\", line %d%s%s",
failedexpr, file, line,
func ? ", function: " : "", func ? func : "");

// make sure to add a \n every 64 characters to fit on the DRC screen.
char *target_ptr = buffer;
int i = 0, j = 0, lineLength = 0;
while (tmp[i] != '\0' && j < sizeof(buffer) - 2) {
if (tmp[i] == '\n') {
lineLength = 0;
} else if (lineLength >= 64) {
target_ptr[j++] = '\n';
lineLength = 0;
}
target_ptr[j++] = tmp[i++];
lineLength++;
}

if (OSIsDebuggerPresent()) {
__asm__ __volatile__("mr 3, %0\n" // load 'tmp' into r3
"tw 0x1f, 31, 31" // DBGSTR_INSTRUCTION
:
: "r"(tmp)
: "r3");
}

OSFatal(buffer);
/* NOTREACHED */
while (1);
}

void __attribute__((weak))
__assert(const char *file,
int line,
const char *failedexpr)
{
__assert_func(file, line, NULL, failedexpr);
/* NOTREACHED */
}

void *_sbrk_r(struct _reent *ptr, ptrdiff_t incr) {
return __wut_sbrk_r(ptr, incr);
}
Expand Down

0 comments on commit 1adf474

Please sign in to comment.