r/Assembly_language • • 4d ago

Solved! Can't call subroutine from a linked in object file in GBA assembly

Hello, I recently decided to start learning assembly by programming the game boy advance. Most of the information about programming the gba I've found are for C programming so I'm trying to learn assembly by translating them to assembly. I'm specifically following the tonc turorials, with a development environment I mostly copied from the gba-bootstrap repository.

I got the first example from the tonc tutorial running on mgba (a gba emulator), but I did it with a unity build. The tonc book strongly advises against this and instead recommends you assemble the files separately and link them together instead.

Right now my working code looks something like this (shortened for brevity):

// src/header.s
// copied almost verbetim from gba-bootstrap
    
    .section .gba_crt0, "ax"
    .global entrypoint
    .cpu arm7tdmi
    
    .arm
    
entrypoint:
    /*
     * gba header boilerplate
     * initialize the cpu and switch to thumb mode
     */
    bl  main

    // If main returns, reboot GBA using SoftReset
    swi  #0x00



// src/main.s

.include "src/header.s"

.section	.text
.global		main

main:
    /*
     * Draw colors on the screen
     */ 

    // while(1)
1:
    b    1b

    // unreachable
    bx   lr

Here's the Makefile in it's entirety because I suspect the problem is there:

NAME		:= main
GAME_TITLE	:= "GBA_TEMPLATE"
GAME_CODE	:= "00"

UNAME_S		:= $(shell uname -s)
MAKEFLAGS += --no-print-directory

PREFIX		:= arm-none-eabi-
AS		:= $(PREFIX)as
LD		:= $(PREFIX)ld
CC		:= $(PREFIX)gcc
CXX		:= $(PREFIX)g++
OBJDUMP		:= $(PREFIX)objdump
OBJCOPY		:= $(PREFIX)objcopy
MKDIR		:= mkdir
RM		:= rm -rf

ELF	:= $(NAME).elf
ROM	:= $(NAME).gba
MAP	:= $(NAME).map

GBAFIX	:= gbafix/gbafix

ASFLAGS		:= -x assembler-with-cpp \
		   -mthumb -mthumb-interwork \
		   -ffunction-sections -fdata-sections

LDFLAGS		:= -mthumb -mthumb-interwork \
		   -Wl,-Map,$(MAP) -Wl,--gc-sections \
		   -specs=nano.specs -T src/gba.ld \


SOURCEDIR	:= src
BUILDDIR	:= build

SOURCES		:= $(wildcard $(SOURCEDIR)/*.s $(SOURCEDIR)/**/*.s)
OBJS		:= $(patsubst $(SOURCEDIR)/%.s,$(BUILDDIR)/%.s.o,$(SOURCES)) 

$(BUILDDIR)/%.s.o : $(SOURCEDIR)/%.s
	@echo "	AS	$<"
	@$(MKDIR) -p $(BUILDDIR)
	@$(CC) $(ASFLAGS) -MMD -MP -c -g -o $@ $<


$(ROM) : $(ELF) $(GBAFIX)
	@$(OBJCOPY) -O binary $< $@
	@echo "	GBAFIX	$@"
	@$(GBAFIX) $@ -t$(GAME_TITLE) -c$(GAME_CODE)

$(ELF) : $(OBJS) src/gba.ld
	@echo "	LD	$@"
	@$(CC) -o $@ $(BUILDDIR)/main.s.o $(LDFLAGS)
	@#$(CC) -o $@ $(OBJS) $(LDFLAGS)	#DOESN'T WORK

$(GBAFIX) : gbafix/gbafix.c
	@echo "	building GBAFIX"
	@cd gbafix && make

.PHONEY: clean dump

clean:
	@echo "	clean"
	@$(RM) $(ROM) $(ELF) $(MAP) $(BUILDDIR)
	@cd gbafix && make clean

dump: $(ELF)
	@$(OBJDUMP) -S $(ELF)

ifeq ($(UNAME_S), Darwin)

.PHONEY: run
run: $(ROM)
	@echo "	RUNNING	$(ROM)"
	@open -a "mgba" $(ROM)

endif

The linker script is copied verbatim from gba-bootstrap because I don't really understand linkers.

When I switch to linking together all the object files and don't include header in main I still get a main.gba file that runs in the emulator, but it doesn't run the code at my main label.

I don't know if I'm doing something wrong with assembly or if this is a game boy specific problem. What confuses me though is when I objdump my linked file I see the bl main call from the header file has the same address as where my main label ended up.

Any help at all with this would be appreciated! Thanks

4 Upvotes

13 comments sorted by

1

u/MagicWolfEye 4d ago edited 4d ago

It's been more than a year I guess, so I don't quite remember everything probably.

I too am too lazy to learn about makefiles or whatever, so I build every program I write with a simple build.bat

This is the one I have here

arm-none-eabi-gcc -MMD -MP -MF build/thumb.d                       -mcpu=arm7tdmi -mtune=arm7tdmi -g -gdwarf-2 -fno-rtti -Wall -Wno-format-truncation -Wno-write-strings -Ibuild -ffast-math -fno-strict-aliasing -fstack-check -fstack-protector-strong -mthumb-interwork -mthumb   -DSHOW_PROFILE -DNDEBUG -c code/thumb_old.cpp -O3 -o build/thumb.o
arm-none-eabi-gcc -MMD -MP -MF build/arm.d                         -mcpu=arm7tdmi -mtune=arm7tdmi -g -gdwarf-2 -fno-rtti -Wall                                           -Ibuild -ffast-math -fno-strict-aliasing -fstack-check -fstack-protector-strong -marm                       -DSHOW_PROFILE -DNDEBUG -c code/arm.cpp       -O3 -o build/arm.o
arm-none-eabi-gcc -MMD -MP -MF build/asm.d -x assembler-with-cpp                                                                                                                                                -fstack-check -fstack-protector-strong -mthumb-interwork -mthumb   -DSHOW_PROFILE -DNDEBUG -c code/asm.s         -O3 -o build/asm.o


arm-none-eabi-gcc -specs=gba.specs build/asm.o build/arm.o build/thumb.o -Wl,-Map,build/game.map -Wl,--print-memory-usage -o build/game.elf


arm-none-eabi-nm -Sn build/game.elf > build/game.map
arm-none-eabi-objcopy -O binary build/game.elf build/game.gba


arm-none-eabi-objdump -h build/game.elf
arm-none-eabi-size -A build/game.elf
arm-none-eabi-nm -Sn --size-sort build/game.elf > build/game-symbols.txt


REM Bonus:

set LastError=%ERRORLEVEL%
if NOT %LastError%==0 (
      echo 
      echo ########################### ERROR ###########################
      echo ########################### ERROR ###########################
      echo ########################### ERROR ###########################
      echo 
       Completed: %date% %time%
) else (
      echo 
      echo ########################### SUCCESS ###########################
      echo ########################### SUCCESS ###########################
      echo ########################### SUCCESS ###########################
      echo 
)

As I said, I don't remember everything, I don't remember what -MMD etc. means

Some infos:
(I am one of those people who write in C and a little bit of a plus; where you use a C++ compiler but mostly write C code, that's why I have .cpp files)

code/thumb.cpp -> This is the regular code; that will compile to thumb instructions; it'S where your main goes and most of the logic of the game

code/arm.cpp -> This is where arm code goes; given that I have a HOT_CODE macro that automatically puts stuff into arm code; I don't really have anything in here except for the IrqHandler

// Some macros for stuff

#define EWRAM_DATA __attribute__((section(".ewram")))
#define IWRAM_DATA __attribute__((section(".iwram")))
#define  EWRAM_BSS __attribute__((section(".sbss")))


#define EWRAM_CODE __attribute__((section(".ewram"), long_call))
#define IWRAM_CODE __attribute__((section(".iwram"), long_call))


#define ARM_CODE __attribute__((target("arm")))
#define THUMB_CODE  __attribute__((target("thumb")))


#define HOT_CODE IWRAM_CODE ARM_CODE



// This is basically my arm.cpp
// Given that there is stuff commented out and those functions that are commented out, don't even exist; idk what I wanted to do here.
// Tonc has a good IrqHandler of course with like nested irqs
// I think that part was important though; so basically in your main you say what types of interrupts you want to have and then you have to write the handler so you clear them whenever they happen

void IrqHandler() {
    // int x = REG_IF;
    // if (x != 1) {
    //     int s = 2;
    // }
    // REG_IF = 1;


    if (REG_IF & IRQ_VBLANK) {
        // if (VBlankHandler) {
        //     VBlankHandler();
        // }
        // VBlankHandler();
        REG_IF     = IRQ_VBLANK;
        REG_IFBIOS = IRQ_VBLANK;
    }


    if (REG_IF & IRQ_KEYPAD) {
        // KeyHandler();
        REG_IF     = IRQ_KEYPAD;
        REG_IFBIOS = IRQ_KEYPAD;
    }
}

My main starts with this

    REG_ISR_MAIN = IrqHandler;


    REG_DISPSTAT |= DSTAT_VBL_IRQ;
    REG_IE |= IRQ_VBLANK;


    // I don't use this atm
    // REG_KEYCTRL |= KCTRL_IRQ;
    // REG_IE |= IRQ_KEYPAD;


    REG_IME = 1;

My asm.s is where the assembly code goes. This file starts with some special interrupt codes, you can look them up somewhere,

@ at top of your file
    .text           @ aka .section .text
    .code 16        @ aka .thumb

.align 2        @ aka .balign 4     
    .global IntrWait
    .thumb_func
IntrWait:
    swi     0x04
    bx      lr


I have them for a few functions but this gets annoying with the reddit formating (they all look alike just with the number after swi being different
Some others are VBlankIntrWait, IntrDiv, IntrSqrt; you will easily find them online
VBlankIntrWait is the most import one though; you can just call it to wait a frame. They only work if you setup the interrupt stuff though

A bit important is also intrs.h. It contains this so that you can actually call them in your code

#pragma once


extern "C" void IntrWait(int a, int b);
extern "C" void VBlankIntrWait();
extern "C" int IntrDiv(int, int);
extern "C" unsigned int IntrSqrt(unsigned int);

void IrqHandler();

That's about it; it's a bit much but there is quite some debugging info in there.

-DSHOW_PROFILE and -DNDEBUG are obviously specific to my code

1

u/tinymoat 4d ago edited 4d ago

can you share your gba.specs file? I'm compiling with nano.specs that comes with the arm toolchain. Did you make gba.specs yourself?

1

u/MagicWolfEye 4d ago

I think I didn't I didn't even realise that existed.  You will have to wait a few hours though until I'm at my pc again 

1

u/tinymoat 4d ago

Thank you!

1

u/MagicWolfEye 4d ago

Hah, I knew I actually don't such a file.
I am using devkitARM and it just uses the one from there. It will essentially call the linker file also provided by devkitARM.

(Also: While it looks awful, I much prefer the old Tonc version: https://www.coranac.com/tonc/text/toc.htm)

1

u/msthe_student 4d ago

Tried running it in an emulator with a debugger?

1

u/tinymoat 4d ago

I just did and now I am more confused. With the unity build I set a breakpoint at main and saw my main function but with the linked build it goes to the correct address but the first instruction is now `lsl r0, r7, #1`, which isn't in my program anywhere. Then it runs `b 0x07FFFCE0`, which once again doesn't appear in my source code. After that it runs `lsl r0, r0, #0` forever.

I'm so far out of my depth I don't know how to even start debugging this

1

u/tinymoat 4d ago

I figured it out! When I .included the file it set the cpu mode to thumb from the code in the header. When I stopped including the code it started compiling the main file as .arm code. The weird instructions were the arm code interpreted as thumb code.

1

u/ProfitLow5177 4d ago

Did a bit of digging and it looks like the CPU is executing blank data as instructions (0x0000 can be executed as "LSL r0, r0, #0" in THUMB instruction).

Apparently this can happen if the program accesses uninitialised memory or corrupted pointers.

1

u/tinymoat 4d ago

Right. I'm confused why changing how I build the program leads to a jump to uninitialized memory

1

u/ProfitLow5177 4d ago

I wouldn't have the slightest clue.

1

u/HowziCanReddit 4d ago edited 4d ago

Your entrypoint is running in ARM mode, but your main routine is assembled as Thumb code. A plain bl main from ARM mode cannot correctly switch to a Thumb function (the CPU will try to execute the Thumb instructions as ARM, leading to a crash or silent failure). Even if the linker resolves the address of main, the mode mismatch prevents the code from running correctly. The gba_crt0.s from gba-bootstrap switches the CPU to Thumb mode and then calls main via a bx-style trampoline. You need to replicate that logic in your header.s

1

u/tinymoat 3d ago

Hi, thanks for the detailed response. I switched to thumb mode in my entrypoint subroutine. The problem was that I didn't include the .thumb directive in main.s so the main file was actually assembled as arm code. Once I included the directive everything worked!