AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / coding / Perguntas / 79279435
Accepted
burneraccount
burneraccount
Asked: 2024-12-14 03:49:00 +0800 CST2024-12-14 03:49:00 +0800 CST 2024-12-14 03:49:00 +0800 CST

Segfault mesmo com valor correto na variável?

  • 772

Tenho o seguinte main.c:

#include <stdio.h>
#include <stdlib.h>

extern unsigned short addsub(int op1, int op2, char what, int *res, int *bit_count);

void print_flags(unsigned short flags) {
    printf("Flags:\n");
    printf("%s", "O D I T S Z   A   P   C\n");

    int bits_to_display = 12; // Significant bits only (0 included)

    for (int i = bits_to_display - 1; i >= 0; --i) {
        printf("%d ", (flags >> i) & 1);
    }
    printf("\n\n");
}

void print_result(int op1, int op2, int result, unsigned short flags, char operation, int bit_count) {
    // Signed interpretation
    printf("Ergebnis und Operanden Signed:\n");
    printf("%d %c %d = %d ", (signed char)op1, operation, (signed char)op2, (signed char)result);
    if ((flags & 0x0800) != 0) { // Overflow flag (OF)
        printf("(Ergebnis ist falsch!)\n");
    } else {
        printf("(Ergebnis ist richtig!)\n");
    }

    // Unsigned interpretation
    printf("\nErgebnis und Operanden Unsigned:\n");
    printf("%u %c %u = %u ", (unsigned char)op1, operation, (unsigned char)op2, (unsigned char)result);
    if ((flags & 0x0001) != 0) { // Carry flag (CF)
        printf("(Ergebnis ist falsch!)\n");
    } else {
        printf("(Ergebnis ist richtig!)\n");
    }

    // Print POPCNT result
    printf("\nDie Anzahl der gesetzten Bits im Ergebnis beträgt: %d\n", bit_count);
}

int main(int argc, char *argv[]) {
    if (argc != 4) {
        fprintf(stderr, "Usage: %s <operand1> <+|-> <operand2>\n", argv[0]);
        return 1;
    }

    int op1 = atoi(argv[1]);
    int op2 = atoi(argv[3]);
    char op = argv[2][0];

    if (op != '+' && op != '-') {
        fprintf(stderr, "Error: Invalid operator. Use '+' or '-'.\n");
        return 1;
    }

    int res = 0;
    int bit_count = 0;
    unsigned short flags = addsub(op1, op2, op, &res, &bit_count);

    if (bit_count == -1) {
        printf("Diese CPU unterstützt den Befehl CPUID nicht!\n");
        return 1;
    } else if (bit_count == -2) {
        printf("Diese CPU unterstützt den Befehl POPCNT nicht!\n");
        return 1;
    }

    print_flags(flags);
    print_result(op1, op2, res, flags, op, bit_count);
    return 0;
}

que é combinado com o seguinte módulo de montagem:

section .text
global addsub

; CPUID function genutzt um cpu informationen auszulesen

; EAX = 1 provides feature information in ECX
; Bit 23 of ECX = 1 indicates POPCNT support

addsub:
    push ebp
    mov ebp, esp

    ; Load function arguments
    mov eax, [ebp+8]       ; Load op1
    mov ebx, [ebp+12]      ; Load op2
    mov ecx, [ebp+16]      ; Load operation ('+' or '-')
    mov edx, [ebp+20]      ; Load address of res
    mov esi, [ebp+24]      ; Load address of bit_count

    ; Save registers
    push eax
    push ebx
    push ecx
    push edx
    push esi

    ; CPUID for POPCNT support check
    pushfd
    pop eax
    mov ecx, eax
    xor eax, 0x00200000    ; Toggle ID bit in EFLAGS
    push eax               ; Save modified flags
    popfd                  ; Load modified flags
    pushfd                 ; Push modified flags to stack
    pop eax                ; Pop flags back into EAX
    xor eax, ecx           ; Check if ID bit was toggled
    jz no_cpuid            ; CPUID not supported

    ; CPUID supported, check POPCNT support (bit 23)
    mov eax, 1             ; Set EAX to 1 (feature information)
    cpuid
    test ecx, 1 << 23
    jz no_popcnt           ; POPCNT not supported

    ; Restore registers
    pop esi
    pop edx
    pop ecx
    pop ebx
    pop eax

    cmp cl, '+'
    je add
    cmp cl, '-'
    je sub

    ; Invalid operation
    xor eax, eax
    leave
    ret

add:
    add al, bl
    mov [edx], eax         ; Store result
    pushfd
    pop eax
    jmp count_bits

sub:
    sub al, bl
    mov [edx], eax         ; Store result
    pushfd
    pop eax
    jmp count_bits

count_bits:
    push ebx
    push esi
    mov ebx, [edx]
    and ebx, 0xFF        ; Hardcoded 8-bit limit
    popcnt ecx, ebx        ; Count the number of set bits in result
    mov [esi], ecx         ; Store bit count in variable
    pop ebx
    pop esi
    jmp fin

no_cpuid:
    mov dword [esi], -1             ; CPUID not supported flag for C program
    jmp fin

no_popcnt:
    mov dword [esi], -2             ; POPCNT not supported flag for C program
    jmp fin

fin:
    leave                  ; Restore stack frame (includes pop ebp)
    ret 

O propósito do programa é ler os flags da CPU e retorná-los. Quando tento ler a variável flags depois que o addsub()método termina, o programa trava, e não consigo descobrir o motivo. No gdb, o valor correto é armazenado na variável flags. Quando removo a instrução print, o programa funciona conforme o esperado.

Talvez alguém possa ajudar porque estou ficando louco!

c
  • 1 1 respostas
  • 96 Views

1 respostas

  • Voted
  1. Best Answer
    Jester
    2024-12-14T04:25:15+08:002024-12-14T04:25:15+08:00

    Suspeito que o problema seja porque você não preserva os registros conforme a convenção de chamada. Reorganizei um pouco seu código, o que deve corrigir o problema:

    global addsub
    
    ; CPUID function genutzt um cpu informationen auszulesen
    
    ; EAX = 1 provides feature information in ECX
    ; Bit 23 of ECX = 1 indicates POPCNT support
    
    addsub:
        push ebp
        mov ebp, esp
        ; Save registers
        push ebx
        push esi
        mov esi, [ebp+24]      ; Load address of bit_count
    
        ; CPUID for POPCNT support check
        pushfd
        pop eax
        mov ecx, eax
        xor eax, 0x00200000    ; Toggle ID bit in EFLAGS
        push eax               ; Save modified flags
        popfd                  ; Load modified flags
        pushfd                 ; Push modified flags to stack
        pop eax                ; Pop flags back into EAX
        xor eax, ecx           ; Check if ID bit was toggled
        jz no_cpuid            ; CPUID not supported
    
        ; CPUID supported, check POPCNT support (bit 23)
        mov eax, 1             ; Set EAX to 1 (feature information)
        cpuid
        test ecx, 1 << 23
        jz no_popcnt           ; POPCNT not supported
    
        ; Load rest of function arguments
        mov eax, [ebp+8]       ; Load op1
        mov ebx, [ebp+12]      ; Load op2
        mov ecx, [ebp+16]      ; Load operation ('+' or '-')
        mov edx, [ebp+20]      ; Load address of res
    
        cmp cl, '+'
        je add
        cmp cl, '-'
        je sub
    
        ; Invalid operation
        xor eax, eax
        jmp fin
    
    add:
        add al, bl
        mov [edx], eax         ; Store result
        pushfd
        pop eax
        jmp count_bits
    
    sub:
        sub al, bl
        mov [edx], eax         ; Store result
        pushfd
        pop eax
        jmp count_bits
    
    count_bits:
        mov ebx, [edx]
        and ebx, 0xFF        ; Hardcoded 8-bit limit
        popcnt ecx, ebx        ; Count the number of set bits in result
        mov [esi], ecx         ; Store bit count in variable
        jmp fin
    
    no_cpuid:
        mov dword [esi], -1             ; CPUID not supported flag for C program
        jmp fin
    
    no_popcnt:
        mov dword [esi], -2             ; POPCNT not supported flag for C program
    
    fin:
        pop esi
        pop ebx
        leave                  ; Restore stack frame (includes pop ebp)
        ret
    
    • 3

relate perguntas

  • Multiplicação mais rápida que *

  • Usando uma macro para comprimento de string no especificador de formato scanf () em C

  • Como você pode definir o tipo de dados de #define para long double?

  • Ponteiros const incompatíveis

  • Mudança de cor não gradual no OpenGL

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Vue 3: Erro na criação "Identificador esperado, mas encontrado 'import'" [duplicado]

    • 1 respostas
  • Marko Smith

    Por que esse código Java simples e pequeno roda 30x mais rápido em todas as JVMs Graal, mas não em nenhuma JVM Oracle?

    • 1 respostas
  • Marko Smith

    Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores?

    • 1 respostas
  • Marko Smith

    Como faço para corrigir um erro MODULE_NOT_FOUND para um módulo que não importei manualmente?

    • 6 respostas
  • Marko Smith

    `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso?

    • 3 respostas
  • Marko Smith

    Quando devo usar um std::inplace_vector em vez de um std::vector?

    • 3 respostas
  • Marko Smith

    Um programa vazio que não faz nada em C++ precisa de um heap de 204 KB, mas não em C

    • 1 respostas
  • Marko Smith

    PowerBI atualmente quebrado com BigQuery: problema de driver Simba com atualização do Windows

    • 2 respostas
  • Marko Smith

    AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos

    • 1 respostas
  • Marko Smith

    Estou tentando fazer o jogo pacman usando apenas o módulo Turtle Random e Math

    • 1 respostas
  • Martin Hope
    Aleksandr Dubinsky Por que a correspondência de padrões com o switch no InetAddress falha com 'não cobre todos os valores de entrada possíveis'? 2024-12-23 06:56:21 +0800 CST
  • Martin Hope
    Phillip Borge Por que esse código Java simples e pequeno roda 30x mais rápido em todas as JVMs Graal, mas não em nenhuma JVM Oracle? 2024-12-12 20:46:46 +0800 CST
  • Martin Hope
    Oodini Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores? 2024-12-12 06:27:11 +0800 CST
  • Martin Hope
    sleeptightAnsiC `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso? 2024-11-09 07:18:53 +0800 CST
  • Martin Hope
    The Mad Gamer Quando devo usar um std::inplace_vector em vez de um std::vector? 2024-10-29 23:01:00 +0800 CST
  • Martin Hope
    Chad Feller O ponto e vírgula agora é opcional em condicionais bash com [[ .. ]] na versão 5.2? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench Por que um traço duplo (--) faz com que esta cláusula MariaDB seja avaliada como verdadeira? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng Por que `dict(id=1, **{'id': 2})` às vezes gera `KeyError: 'id'` em vez de um TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos 2024-03-20 03:12:31 +0800 CST
  • Martin Hope
    MarkB Por que o GCC gera código que executa condicionalmente uma implementação SIMD? 2024-02-17 06:17:14 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve