;================================================================================= ; sys_open (O_CREAT) & sys_brk demonstration. ; ; Creates new file (if file already exists it application will fail), writes a ; string to the newly created file, expands .bss segment, reads the string back to ; the newly created space, and terminates. ; ; The LSCR Project. ;================================================================================= format ELF include '../macros.inc' include '../../include/symbols.inc' include '../../include/structs.inc' extrn error_chk section '.text' executable public _start _start: mov eax, SYS_OPEN ; create the file in synchronous read-write mode. (creation will fail mov ebx, filename_s ; if file already exist) mov ecx, O_RDWR or O_CREAT or O_EXCL or O_SYNC mov edx, S_IRWXU int 0x80 mov [file_d], eax cmp eax, -EEXIST je already_exist ccall error_chk, <"SYS_OPEN has failed: ">, exit mov eax, SYS_WRITE ; write a string to the new file mov ebx, [file_d] mov ecx, test_s mov edx, test_s_sz int 0x80 ccall error_chk, <"SYS_WRITE has failed: ">, close mov eax, SYS_FSTAT ; obtain file size (stat.st_size) mov ebx, [file_d] mov ecx, fstat int 0x80 ccall error_chk, <"SYS_FSTAT has failed: ">, close ; here we expand the .bss segment. new space will be used for reading data ; from the file. mov eax, SYS_BRK ; obtain current bottom of the .bss segment xor ebx, ebx int 0x80 ccall error_chk, <"SYS_BRK has failed: ">, close mov [bss_original], eax mov ebx, [fstat.st_size] ; expand the .bss segment add ebx, eax mov eax, SYS_BRK int 0x80 ccall error_chk, <"SYS_BRK has failed: ">, close mov eax, SYS_LSEEK ; relocate file pointer to the beginning of the file mov ebx, [file_d] xor ecx, ecx mov edx, SEEK_SET int 0x80 ccall error_chk, <"SYS_LSEEK has failed: ">, close mov eax, SYS_READ ; read data from the file mov ebx, [file_d] mov ecx, [bss_original] mov edx, [fstat.st_size] int 0x80 ccall error_chk, <"SYS_READ has failed: ">, close mov edx, eax ; print the string to STDOUT mov eax, SYS_WRITE mov ebx, STDOUT mov ecx, [bss_original] int 0x80 mov eax, SYS_BRK ; collapse the .bss segment size to its original size mov ebx, [bss_original] int 0x80 ccall error_chk, <"SYS_BRK has failed: ">, close close: mov eax, SYS_CLOSE mov ebx, [file_d] int 0x80 jmp exit already_exist: mov eax, SYS_WRITE mov ebx, STDOUT mov ecx, exist_s mov edx, exist_s_sz int 0x80 exit: mov eax, SYS_EXIT xor ebx, ebx int 0x80 section '.data' writeable fstat stat file_d rd 1 bss_original rd 1 filename_s db "newfile.txt",0 exist_s db "The file already exists and can not be created",0xa exist_s_sz = $-exist_s test_s db "This is a test!",0xa test_s_sz = $-test_s