Simple way to Get filesize in x86 Assembly Language

后端 未结 2 584
天涯浪人
天涯浪人 2021-01-16 23:34

Assuming that I have opened a file in assembly and have the file handle for that file in register eax. How would I go about getting the size of the file so I can allocate en

相关标签:
2条回答
  • 2021-01-16 23:55

    Here is how is implemented in FreshLib. It is a wrapper in order to provide portability. You can simplify it of course (see below).

      struct STAT
        .st_dev     dw  ?     ; ID of device containing file
        .pad1       dw  ?
        .st_ino     dd  ?     ; inode number
        .st_mode    dw  ?     ; protection
        .st_nlink   dw  ?     ; number of hard links
        .st_uid     dw  ?     ; user ID of owner
        .st_gid     dw  ?     ; group ID of owner
        .st_rdev    dw  ?     ; device ID (if special file)
        .pad2       dw  ?
        .st_size    dd  ?     ; total size, in bytes
        .st_blksize dd  ?     ; block size
        .st_blocks  dd  ?
    
        .st_atime   dd  ?     ; time of last access
        .unused1    dd  ?
    
        .st_mtime   dd  ?     ; time of last modification
        .unused2    dd  ?
    
        .st_ctime   dd  ?     ; time of last status change
        .unused3    dd  ?
        .unused4    dd  ?
        .unused5    dd  ?
      ends
    
      sys_newfstat =  $6c
    
      proc FileSize, .handle
      .stat STAT
      begin
              push    edx ecx ebx
    
              mov     eax, sys_newfstat
              mov     ebx, [.handle]
              lea     ecx, [.stat]
              int     $80
    
              cmp     eax, -1
              jle     .error
    
              mov     eax, [.stat.st_size]
              clc
              pop     ebx ecx edx
              return
    
      .error:
              neg     eax       ; error code
              stc
              pop     ebx ecx edx
              return
      endp
    

    The minimal version can look this way (much less readable and not thread safe):

      ; argument: file handle in ebx
      ; returns:  the size in EDX; error code in EAX
      FileSize:
              mov     eax, $6c
              mov     ecx, file_stat
              int     $80
              mov     edx, [file_stat+$14]
              retn
    
      file_stat rd $10
    
    0 讨论(0)
  • 2021-01-16 23:57

    My solution -- Just use .lcomm to create locations for all the named variables

    movl    inputfile, %ebx         #Move file handler into ebx for system call
    movl    $0x6c, %eax          #Stat Sys Call into eax
    leal    statlocation, %ecx      #Move reserved location for stat structure into
    int     $0x80                    #Execute System Call
    movl    20(%ecx), %eax          #20 to location of size variable, size is now in eax
    
    0 讨论(0)
提交回复
热议问题