cscg22-gearboy

CSCG 2022 Challenge 'Gearboy'
git clone https://git.sinitax.com/sinitax/cscg22-gearboy
Log | Files | Refs | sfeed.txt

ram_fn.c (1996B)


      1#include <gb/gb.h>
      2#include <stdint.h>
      3#include <stdio.h>
      4#include <string.h>
      5
      6uint16_t counter = 0;
      7
      8// inc() must be a relocatable function, be careful!
      9void inc() {
     10    counter++;
     11}
     12// dummy function, needed to calculate inc() size, must be after it
     13void inc_end() {} 
     14
     15// calculate the distance between objects 
     16#define object_distance(a, b) ((void *)&(b) - (void *)&(a))
     17
     18// variables at an absolute addresses which are defined by passing parameters to compiler
     19unsigned char __at _inc_ram   ram_buffer[];
     20unsigned char __at _inc_hiram hiram_buffer[];
     21
     22// those are function pointer variables, we can initialize them right here
     23typedef void (*inc_t)(void);
     24inc_t inc_ram_var   = (inc_t)ram_buffer;
     25inc_t inc_hiram_var = (inc_t)hiram_buffer;
     26
     27// those are defined by passing parameters to the linker, they must be located at the same 
     28// addresses where ram_buffer and hiram_buffer are located
     29extern void inc_ram();
     30extern void inc_hiram();
     31
     32void print_counter() {
     33    printf(" Counter is %u\n", counter);
     34}
     35
     36void main() {
     37    // copy inc() function to it's new destinations: hiram_buffer and ram_buffer
     38    hiramcpy((uint8_t)&hiram_buffer, (void *)&inc, (uint8_t)object_distance(inc, inc_end));
     39    memcpy(&ram_buffer, (void *)&inc, (uint16_t)object_distance(inc, inc_end));
     40
     41    // print initial counter state
     42    puts("Program Start...");
     43    print_counter();
     44
     45    // Call function in ROM
     46    puts("Call ROM");
     47    inc();
     48    print_counter();
     49
     50    // Call function in RAM using link-time address
     51    puts("Call RAM direct");
     52    inc_ram();
     53    print_counter();
     54
     55    // Call function in RAM using pointer-to-function variable
     56    puts("Call RAM indirect");
     57    inc_ram_var();
     58    print_counter();
     59
     60    // Call function in HIRAM using link-time address
     61    puts("Call HIRAM direct");
     62    inc_hiram();
     63    print_counter();
     64
     65    // Call function in HIRAM using pointer-to-function variable
     66    puts("Call HIRAM indirect");
     67    inc_hiram_var();
     68    print_counter();
     69
     70    puts("The End...");
     71}