简体   繁体   English

如何从程序集x86中的文件读取

[英]How to read from a file in assembly x86

I have a code in c language that needs to be translated to assembly x86. 我有一个C语言代码,需要将其翻译为程序集x86。 Here is the c code: 这是C代码:

int rb (FILE *f){
    int s;
    char c;
    s = fr(&c, 1, 1, f);
    if (s <= 0) return -1;
    return (int)c;
}

So far I got to this assembly code that gives me Segmentation fault: 到目前为止,我已经了解了导致分段错误的汇编代码:

rb:
    pushl %ebp
    movl %esp,%ebp
    pushl 8(%ebp)
    pushl $1
    pushl $1
    leal 12(%ebp), %eax
    pushl %eax
    call fr
    jz ng
    jns ex
ng:
    pushl $1
    negl %eax
ex:
    popl %ebp
    ret

Can anyone help me to solve this? 谁能帮我解决这个问题? :) :)

Both Gcc and Clang can generate the assember for you. Gcc和Clang都可以为您生成assember。 It might not always be easy to read but this is how to do it: 它可能并不总是很容易阅读,但这是这样做的:

Make the snippet you want to inspect compilable with no errors. 使您要检查的代码段可正确编译。 Note, I've changed your example to take a pointer to an integer as an argument because in your example you were declaring a char on the stack and then returning it ie Undefined Bahaviour. 注意,我已更改您的示例以将指向整数的指针作为参数,因为在您的示例中,您是在堆栈上声明一个char,然后返回它,即Undefined Bahaviour。

Create a file called foo.c with this in it: 创建一个名为foo.c的文件,其中包含以下内容:

#include <stdio.h>
extern size_t fr(void *restrict ptr, size_t size, size_t nitems, FILE *restrict stream);
int rb (FILE *f, int *c){
  int s;
  s = fr(c, 1, 1, f); 
  if (s <= 0) return -1; 
  return *c; 
}

Compile it using the S flag to gcc ie 使用S标志将其编译为gcc

gcc-5 -S -O0 -Wall -pedantic -std=c11 foo.c

The open the following file foo.s 打开以下文件foo.s

.text
  .globl _rb 
_rb:
LFB1:
  pushq %rbp
LCFI0:
  movq  %rsp, %rbp
LCFI1:
  subq  $32, %rsp
  movq  %rdi, -24(%rbp)
  movq  %rsi, -32(%rbp)
  movq  -24(%rbp), %rdx
  movq  -32(%rbp), %rax
  movq  %rdx, %rcx
  movl  $1, %edx
  movl  $1, %esi
  movq  %rax, %rdi
  call  _fr 
  movl  %eax, -4(%rbp)
  cmpl  $0, -4(%rbp)
  jg  L2  
  movl  $-1, %eax
  jmp L3
L2:
  movq  -32(%rbp), %rax
  movl  (%rax), %eax
L3:
  leave
LCFI2:
  ret 
LFE1:
  .section __TEXT,__eh_frame,coalesced,no_toc+strip_static_syms+live_support
....
.... snipped
....

Now you have the assembler on x86 for the code you wanted. 现在,您可以在x86上使用所需的代码进行汇编。 Note, you can play around with various options to change the output in particular the optimization levels will drastically change the output. 请注意,您可以使用各种选项来更改输出,特别是优化级别将极大地更改输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM