.include "syscalls.S" .include "constants.S" .include "string.S" .global _start /* Exits the program with the provided exit code @args: r0 => exit code */ exit: mov r7, #SYS_EXIT svc 0 /* print to stdout @args: r1 => pointer to buffer to print r2 => how many bytes to print @clobbers: r0 */ print: mov r0, #STDOUT mov r7, #SYS_WRITE svc 0 bx lr open_fail: push {r0} ldr r1, =OPEN_FAIL mov r2, #31 bl print pop {r0} bl exit dir_read_fail: push {r0} ldr r1, =DIR_READ_FAIL mov r2, #29 bl print pop {r0} bl exit fd_not_dir: ldr r1, =FD_NOT_DIR mov r2, #24 bl print mov r0, #1 bl exit fd_not_found: ldr r1, =FD_NOT_FOUND mov r2, #58 bl print mov r0, #1 bl exit _start: ldr r0, [sp] cmp r0, #1 ldrgt r0, [sp, #8] ldrle r0, =FALLBACK_DIR mov r1, #0 @ flags mov r2, #0 @ mode_t mov r7, #SYS_OPEN svc 0 cmp r0, #ENOENT beq fd_not_found cmp r0, #0 blt open_fail @ r0 needs the fd, which it should already be since the call to open() set r0 to the fd. ldr r1, =buffer @ pointer to linux_dirent structure @ TODO: we can allocate the required memory on the stack instead of in the bss section I think. mov r2, #16384 @ how many bytes to read mov r7, #SYS_GETDENTS svc 0 cmp r0, #ENOTDIR beq fd_not_dir cmp r0, #0 blt dir_read_fail mov r4, #0 @ initialize r4 to 0 ldr r5, =buffer 1: push {r0} add r1, r5, #10 @ offset 10 bytes into the dirent struct to reach d_name. bl strlen mov r2, r0 bl print ldr r1, =NEWLINE mov r2, #1 bl print pop {r0} @ load the value (as 16-bits zero-extended as opposed to loading 32-bits and then extending that ourselves with UXTH) @ in the memory address of r5 offset by 8 bytes to get us the d_reclen ldrh r6, [r5, #8] add r5, r5, r6 @ skip to the next dirent add r4, r4, r6 @ accumulate how many bytes we read cmp r4, r0 blt 1b mov r0, #0 bl exit .data FALLBACK_DIR: .asciz "." OPEN_FAIL: .ascii "Failed to open file descriptor" DIR_READ_FAIL: .ascii "Failed to read the directory\n" FD_NOT_DIR: .ascii "File is not a directory\n" FD_NOT_FOUND: .ascii "Failed to open file descriptor: No such file or directory\n" NEWLINE: .ascii "\n" .bss buffer: .skip 16384