# 1. Variaveis

```mermaid
graph TD
    A[Assembly] --> B[Seções]
    A --> C[Variáveis]
    A --> D[Tipagem]
    B --> E[.data]
    B --> F[.bss]
    B --> G[.text]
    C --> H[Registradores]
    C --> I[Memória]
    D --> J[Interpretação]
```

## 1. Estrutura Básica de um Programa Assembly

### 1.1 Seções Principais

| Seção     | Descrição               | Exemplo (NASM)      | Exemplo (MIPS)        |
| --------- | ----------------------- | ------------------- | --------------------- |
| **.data** | Dados inicializados     | `numero dd 42`      | `numero: .word 42`    |
| **.bss**  | Dados não inicializados | `buffer resb 1024`  | `buffer: .space 1024` |
| **.text** | Código executável       | `mov eax, [numero]` | `lw $t0, numero`      |

### 1.2 Exemplo Completo (x86-64)

```nasm
; programa.asm - Exemplo completo com .data, .bss e .text
section .data
    msg db 'Olá, mundo!', 0xa  ; String com newline
    len equ $ - msg             ; Calcula tamanho
    constante dd 42             ; Inteiro constante

section .bss
    input resb 16               ; Buffer para entrada (16 bytes)
    counter resd 1              ; Contador (32 bits)

section .text
    global _start

_start:
    ; Escrever mensagem
    mov rax, 1                  ; sys_write
    mov rdi, 1                  ; stdout
    mov rsi, msg
    mov rdx, len
    syscall

    ; Finalizar
    mov rax, 60                 ; sys_exit
    xor rdi, rdi                ; código 0
    syscall
```

## 2. Seções de Dados em Detalhe

### 2.1 `.data` (Dados Inicializados)

**Características:**

* Valores definidos no código-fonte
* Aumenta o tamanho do executável
* Permissões: Leitura/Escrita (`rw-`)
* Carregado na memória junto com o programa

{% tabs %}
{% tab title="NASM" %}

```nasm
section .data
    ; Inteiros
    int8    db  42                ; 8 bits (byte)
    int16   dw  1000              ; 16 bits (word)
    int32   dd  65536             ; 32 bits (doubleword)
    int64   dq  123456789         ; 64 bits (quadword)

    ; Ponto flutuante
    float32 dd  3.14159           ; 32-bit float
    float64 dq  3.14159265358979  ; 64-bit double

    ; Strings
    string1 db  'Hello', 0        ; Null-terminated
    string2 db  'World', 0xa, 0   ; Com newline e null
    string3 db  'ABC', 0, 0, 0    ; Padding manual

    ; Arrays
    array1  db  1, 2, 3, 4, 5     ; Array de bytes
    array2  dw  10, 20, 30        ; Array de words
    array3  times 10 dd 0         ; 10 zeros (32-bit)

    ; Constantes calculadas
    msg     db  'Texto', 0xa
    len     equ $ - msg           ; Tamanho calculado
```

{% endtab %}

{% tab title="MIPS" %}

```nasm
.data
    # Inteiros
    int8:   .byte   42            # 8 bits
    int16:  .half   1000          # 16 bits
    int32:  .word   65536         # 32 bits
    int64:  .double 123456789     # 64 bits

    # Ponto flutuante
    float32: .float 3.14159       # 32-bit float
    float64: .double 3.14159265358979  # 64-bit double

    # Strings
    string1: .asciiz "Hello"      # Null-terminated
    string2: .ascii "World\n"     # Sem null terminator
    string3: .space 16            # Buffer vazio

    # Arrays
    array1: .byte 1, 2, 3, 4, 5   # Array de bytes
    array2: .half 10, 20, 30      # Array de halfwords
    array3: .word 0:10            # 10 zeros (32-bit)
```

{% endtab %}
{% endtabs %}

### 2.2 `.bss` (Dados Não Inicializados)

**Vantagens:**

* Não ocupa espaço no executável
* Alocação eficiente para grandes buffers
* Automaticamente zerada pelo SO
* Ideal para áreas de trabalho e buffers

{% tabs %}
{% tab title="NASM" %}

```nasm
section .bss
    ; Reserva bytes
    buffer1 resb 1024             ; 1KB buffer
    buffer2 resb 256              ; 256 bytes
    
    ; Reserva palavras
    var32   resd 1                ; 1 doubleword (32 bits)
    var64   resq 1                ; 1 quadword (64 bits)
    
    ; Reserva arrays
    array   resd 100              ; 100 doublewords (400 bytes)
    stack   resb 4096             ; 4KB stack
    
    ; Com alinhamento
    align 16
    aligned resb 64               ; Alinhado a 16 bytes
```

{% endtab %}

{% tab title="MIPS" %}

```nasm
.bss
    # Reserva bytes
    buffer1: .space 1024          # 1KB buffer
    buffer2: .space 256           # 256 bytes
    
    # Reserva palavras
    var32:   .space 4             # 32 bits
    var64:   .space 8             # 64 bits
    
    # Reserva arrays
    array:   .space 400           # 100 palavras (4 bytes cada)
    stack:   .space 4096          # 4KB stack
    
    # Com alinhamento
    .align 4                      # Alinhamento a 16 bytes
    aligned: .space 64
```

{% endtab %}
{% endtabs %}

### 2.3 Comparação `.data` vs `.bss`

| Critério           | `.data`                        | `.bss`                               |
| ------------------ | ------------------------------ | ------------------------------------ |
| **Tamanho no EXE** | Aumenta com dados              | Impacto mínimo (apenas metadados)    |
| **Inicialização**  | Valores explícitos             | Zeros (garantido pelo SO)            |
| **Uso típico**     | Constantes, mensagens, tabelas | Buffers, variáveis dinâmicas, pilhas |
| **Modificável**    | Sim (em tempo de execução)     | Sim (em tempo de execução)           |
| **Permissões**     | `rw-`                          | `rw-`                                |

## 3. Variáveis e Tipagem

### 3.1 Conceito de Variáveis

Em Assembly, **não existem variáveis** como em linguagens de alto nível. O que chamamos de "variáveis" são:

* **Rótulos** para endereços de memória
* **Registradores** do processador
* **Posições na pilha**

A tipagem é determinada pelo uso, não pela declaração:

```nasm
section .data
    valor db 65        ; Pode ser interpretado como:
                       ; - Inteiro (65)
                       ; - Caractere ('A')
                       ; - Byte qualquer
    ; O programador decide como tratar o dado
```

### 3.2 Tipos de Dados

| Tipo                | Tamanho  | Diretivas NASM | Diretivas MIPS | Uso típico                |
| ------------------- | -------- | -------------- | -------------- | ------------------------- |
| **Byte**            | 8 bits   | `db`           | `.byte`        | Chars, flags, bytes       |
| **Word**            | 16 bits  | `dw`           | `.half`        | Inteiros pequenos         |
| **Doubleword**      | 32 bits  | `dd`           | `.word`        | Inteiros, floats          |
| **Quadword**        | 64 bits  | `dq`           | `.double`      | Inteiros grandes, doubles |
| **String**          | Variável | `db 'text',0`  | `.asciiz`      | Mensagens                 |
| **Float (32-bit)**  | 4 bytes  | `dd`           | `.float`       | Números reais             |
| **Double (64-bit)** | 8 bytes  | `dq`           | `.double`      | Alta precisão             |

### 3.3 Constantes e Macros

{% tabs %}
{% tab title="NASM" %}

```nasm
; NASM: Constantes com EQU
STDOUT equ 1
SYS_WRITE equ 1
SYS_EXIT equ 60

section .text
    mov rax, SYS_WRITE
    mov rdi, STDOUT

; NASM: Macros com %define
%define NEWLINE 0xa
%define PRINT_STRING(reg) mov rax, 1 ; mov rdi, 1 ; syscall
```

{% endtab %}

{% tab title="MIPS" %}

```nasm
; MIPS: Constantes com .equ
.eqv STDOUT 1
.eqv SYS_WRITE 1
```

{% endtab %}
{% endtabs %}

### 3.4 Escopo e Armazenamento

| Localização         | Sintaxe (NASM)     | Sintaxe (MIPS)   | Exemplo              |
| ------------------- | ------------------ | ---------------- | -------------------- |
| **Registradores**   | `mov eax, 42`      | `li $t0, 42`     | Uso imediato         |
| **Memória (.data)** | `mov [var], eax`   | `sw $t0, var`    | Global, inicializado |
| **Memória (.bss)**  | `mov [buffer], al` | `sb $t0, buffer` | Global, zero         |
| **Pilha**           | `push rax`         | `addiu $sp, -4`  | Variáveis locais     |

## 4. Operações com Variáveis

### 4.1 Aritméticas Básicas

{% tabs %}
{% tab title="x86-64" %}

```nasm
; x = y + z * 2
section .data
    x dd 0
    y dd 10
    z dd 20

section .text
    mov eax, [z]        ; Carrega z
    shl eax, 1          ; Multiplica por 2 (z * 2)
    add eax, [y]        ; Soma y (y + z*2)
    mov [x], eax        ; Armazena resultado em x
```

{% endtab %}

{% tab title="MIPS" %}

```nasm
.data
    x: .word 0
    y: .word 10
    z: .word 20

.text
    lw $t0, z           ; Carrega z
    sll $t0, $t0, 1     ; Multiplica por 2
    lw $t1, y           ; Carrega y
    addu $t2, $t1, $t0  ; y + z*2
    sw $t2, x           ; Armazena resultado
```

{% endtab %}
{% endtabs %}

### 4.2 Manipulação de Strings

{% tabs %}
{% tab title="x86-64" %}

```nasm
section .data
    str db 'Assembly', 0    ; Null-terminated string
    buffer times 16 db 0    ; Buffer para cópia

section .text
    ; Acessa caractere específico
    mov rsi, str            ; Endereço da string
    mov al, [rsi+3]         ; Acessa 4º caractere ('m')
    
    ; Copia string
    mov rsi, str            ; Fonte
    mov rdi, buffer         ; Destino
copy_loop:
    mov al, [rsi]           ; Carrega byte
    mov [rdi], al           ; Armazena byte
    inc rsi                 ; Avança fonte
    inc rdi                 ; Avança destino
    test al, al             ; Verifica null terminator
    jnz copy_loop           ; Continua se não zero
```

{% endtab %}

{% tab title="MIPS" %}

```nasm
.data
    str: .asciiz "Assembly"
    buffer: .space 16

.text
    la $t0, str             ; Endereço fonte
    la $t1, buffer          ; Endereço destino
    
copy_loop:
    lb $t2, 0($t0)          ; Carrega byte
    sb $t2, 0($t1)          ; Armazena byte
    beqz $t2, copy_done     ; Null terminator?
    addiu $t0, $t0, 1       ; Avança fonte
    addiu $t1, $t1, 1       ; Avança destino
    j copy_loop
    
copy_done:
    nop
```

{% endtab %}
{% endtabs %}

### 4.3 Arrays e Estruturas

{% tabs %}
{% tab title="x86-64" %}

```nasm
; Array de inteiros
section .data
    arr dd 10, 20, 30, 40    ; 4 inteiros (16 bytes)

section .text
    ; Acesso ao 3º elemento (30)
    mov eax, [arr + 8]       ; Offset = índice * 4 (2 * 4 = 8)
    
    ; Percorrer array
    mov rcx, 4               ; Contador
    mov rsi, arr             ; Endereço base
loop_array:
    mov eax, [rsi]           ; Carrega elemento
    add rsi, 4               ; Próximo elemento
    loop loop_array          ; Decrementa rcx e salta se não zero

; Estrutura (struct) simulada
section .data
    ; Struct Pessoa: nome[32], idade(4), altura(4)
    pessoa:
        nome times 32 db 0   ; 32 bytes para nome
        idade dd 25          ; 4 bytes para idade
        altura dd 165        ; 4 bytes para altura (em cm)
    
section .text
    ; Acessar idade (offset 32)
    mov eax, [pessoa + 32]   ; Carrega idade
    ; Acessar altura (offset 36)
    mov ebx, [pessoa + 36]   ; Carrega altura
```

{% endtab %}

{% tab title="MIPS" %}

```nasm
.data
    # Array de inteiros
    arr: .word 10, 20, 30, 40
    
    # Struct simulada: nome[32], idade(4), altura(4)
    pessoa:
        nome: .space 32
        idade: .word 25
        altura: .word 165

.text
    # Acesso ao 3º elemento (30)
    la $t0, arr
    lw $t1, 8($t0)           # Offset = 2 * 4 = 8
    
    # Percorrer array
    li $t2, 4                # Contador
    la $t0, arr              # Endereço base
loop_array:
    lw $t1, 0($t0)           # Carrega elemento
    addiu $t0, $t0, 4        # Próximo elemento
    addiu $t2, $t2, -1       # Decrementa contador
    bnez $t2, loop_array
    
    # Acessar idade (offset 32)
    la $t0, pessoa
    lw $t1, 32($t0)          # Carrega idade
```

{% endtab %}
{% endtabs %}

## 5. Alinhamento de Memória

O alinhamento é crucial para performance e correção.

{% tabs %}
{% tab title="x86-64" %}

```nasm
section .data
    ; Alinhamento automático (geralmente suficiente)
    byte1 db 1
    word1 dw 2                ; Pode ser alinhado a 2 bytes
    dword1 dd 3               ; Alinhado a 4 bytes
    
    ; Alinhamento explícito
    align 16                  ; Alinha próximo dado a 16 bytes
    qword1 dq 4               ; Agora alinhado a 16 bytes

section .bss
    align 16
    buffer resb 64            ; Buffer alinhado a 16 bytes (para SSE)
```

{% endtab %}

{% tab title="MIPS" %}

```nasm
.data
    .align 2                  ; Alinhamento a 4 bytes (2^2)
    word1: .word 1
    .align 3                  ; Alinhamento a 8 bytes (2^3)
    double1: .double 3.14
```

{% endtab %}
{% endtabs %}

## 6. Boas Práticas

### 6.1 Organização de Código

{% stepper %}
{% step %}

### Agrupe dados relacionados

```nasm
; Configurações do sistema
section .data
    timeout dd 30
    retries db 3
    debug_flag db 1

; Mensagens
section .data
    msg_ok db '[OK] Sucesso!', 0xa, 0
    msg_err db '[ERRO] Falha!', 0xa, 0
```

{% endstep %}

{% step %}

### Use constantes simbólicas

```nasm
; NASM
STDOUT equ 1
SYS_WRITE equ 1
SYS_EXIT equ 60

; MIPS
.eqv STDOUT 1
.eqv SYS_WRITE 1
.eqv SYS_EXIT 10
```

{% endstep %}

{% step %}

### Documente estruturas

```nasm
; Estrutura de Processo
; offset 0: PID (4 bytes)
; offset 4: Status (4 bytes)
; offset 8: Nome (32 bytes)
struc Processo
    .pid resd 1
    .status resd 1
    .nome resb 32
endstruc

; Uso
mov eax, [meu_processo + Processo.pid]
```

{% endstep %}
{% endstepper %}

### 6.2 Controle de Memória

* **Alinhamento correto:** Use `align` para dados que serão acessados via SIMD
* **Inicialização:** Variáveis em `.bss` são zeradas automaticamente
* **Limites:** Sempre verifique limites de buffer
* **Pilha:** Reserve espaço suficiente para variáveis locais

### 6.3 Performance

```nasm
; Ineficiente (acesso repetido à memória)
mov eax, [contador]
inc eax
mov [contador], eax

; Eficiente (mantém em registrador)
mov eax, [contador]
add eax, 5
mov [contador], eax

; Uso de registradores para loops
mov ecx, 1000        ; Contador em registrador
loop_start:
    ; código
    dec ecx
    jnz loop_start
```

## 7. Ferramentas para Análise

| Comando               | Finalidade         | Exemplo                        |
| --------------------- | ------------------ | ------------------------------ |
| `objdump -h`          | Listar seções      | `objdump -h programa`          |
| `objdump -s -j .data` | Ver dados          | `objdump -s -j .data programa` |
| `readelf -S`          | Seções ELF         | `readelf -S programa`          |
| `nm`                  | Símbolos           | `nm programa`                  |
| `size`                | Tamanho das seções | `size programa`                |
| `gdb info variables`  | Variáveis globais  | `(gdb) info variables`         |

## 8. Exemplo Integrado Completo

```nasm
; programa_completo.asm - Exemplo integrando .data, .bss e .text
section .data
    ; Constantes
    SYS_WRITE equ 1
    SYS_READ equ 0
    SYS_EXIT equ 60
    STDOUT equ 1
    STDIN equ 0
    
    ; Mensagens
    prompt db 'Digite seu nome: ', 0
    prompt_len equ $ - prompt
    
    format db 'Olá, %s!', 0xa, 0
    format_len equ $ - format

section .bss
    nome resb 32                ; Buffer para nome
    buffer resb 128             ; Buffer auxiliar

section .text
    global _start

_start:
    ; Exibe prompt
    mov rax, SYS_WRITE
    mov rdi, STDOUT
    mov rsi, prompt
    mov rdx, prompt_len
    syscall

    ; Lê nome do usuário
    mov rax, SYS_READ
    mov rdi, STDIN
    mov rsi, nome
    mov rdx, 32
    syscall

    ; Remove newline do final
    mov rcx, rax                ; Bytes lidos
    mov rsi, nome
remove_newline:
    cmp byte [rsi + rcx - 1], 0xa
    jne .done
    mov byte [rsi + rcx - 1], 0
.done:

    ; Prepara saída (simplificada)
    mov rsi, nome
    mov rdi, buffer
    call format_string

    ; Exibe resultado
    mov rax, SYS_WRITE
    mov rdi, STDOUT
    mov rsi, buffer
    mov rdx, 128
    syscall

    ; Finaliza
    mov rax, SYS_EXIT
    xor rdi, rdi
    syscall

; Função simplificada para formatar "Olá, {nome}!"
format_string:
    mov rsi, format
    mov rdi, buffer
format_loop:
    lodsb
    cmp al, '%'                 ; Verifica placeholder
    je .subst
    cmp al, 0
    je .done
    stosb
    jmp format_loop
.subst:
    lodsb                       ; Carrega próximo char (%s)
    cmp al, 's'
    jne .skip
    push rsi
    mov rsi, nome
copy_name:
    lodsb
    cmp al, 0
    je .name_done
    stosb
    jmp copy_name
.name_done:
    pop rsi
    jmp format_loop
.skip:
    stosb
    jmp format_loop
.done:
    stosb
    ret
```

## 📚 Recursos Recomendados

1. **NASM Manual**: [nasm.us/doc](https://nasm.us/doc/)
2. **Intel SDM**: [Intel 64 Manuals](https://software.intel.com/en-us/articles/intel-sdm)
3. **MIPS Reference**: [MIPS Architecture](https://www.mips.com/products/architectures/)
4. **GDB Cheat Sheet**: [gdb-tutorial.net](https://www.gdb-tutorial.net/)
5. **Online Assembler**: [godbolt.org](https://godbolt.org/)

```mermaid
pie
    title Distribuição de Uso
    "Sistemas Embarcados" : 35
    "Drivers" : 25
    "Engenharia Reversa" : 20
    "Otimização Crítica" : 20
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://0xmorte.gitbook.io/bibliadopentestbr/conceitos/programacao-e-linguagens/assembly/1.-variaveis.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
