about summary refs log blame commit diff stats
path: root/rf.c
blob: d2d18aa41cb24e137acd14afa9f643a937fdcd47 (plain) (tree)
71abce4 ^


== code

# Problem: create a function which pushes n zeros on the stack.
# This is not a regular function, so it won't be idiomatic.
# Registers must be properly restored.
# Registers can be spilled, but that modifies the stack and needs to be
# cleaned up.

# This file is kinda like a research notebook, to interactively arrive at the
# solution. Nobody should have to do this without a computer. To run it:
#   $ ./translate_subx_debug init.linux tools/stack_array.subx  &&  bootstrap --debug --trace --dump run a.elf
# There are multiple versions. You'll need to uncomment exactly one.

# The final version has its own Entry, but the others share this one.
#? Entry:
#?     # . prologue
#?     89/<- %ebp 4/r32/esp
#?     #
#?     68/push 0xfcfdfeff/imm32
#?     b8/copy-to-eax 0x34353637/imm32
#? $dump-stack:
#?     (push-n-zero-bytes 0x20)
#? $dump-stack2:
#?     68/push 0x20202020/imm32
#? $dump-stack3:
#?     b8/copy-to-eax 1/imm32/exit
#?     cd/syscall 0x80/imm8

## 0

#? push-n-zero-bytes:  # n: int
#?     # . prologue
#?     55/push-ebp
#?     89/<- %ebp 4/r32/esp
#? $push-n-zero-bytes:end:
#?     # . epilogue
#?     89/<- %esp 5/r32/ebp
#?     5d/pop-to-ebp
#?     c3/return

# stack at dump-stack:
# 0 a: bdffffd0: 00000000     00000000     00000000      00000000
# 0 a: bdffffe0: 00000000     00000000     00000000      00000000
# 0 a: bdfffff0: 00000000     fcfdfeff     00000001      bf000000
#
# =>
#
# stack at dump-stack3:
# 0 a: stack:
# 0 a: bdffffd0: 00000000     00000000     00000000      00000000
# 0 a: bdffffe0: 00000000     00000000     bdfffff8/ebp  090000cc/ra
# 0 a: bdfffff0: 00000004/arg fcfdfeff     00000001      bf000000

## 1

#? push-n-zero-bytes:  # n: int
#?     # . prologue
#?     55/push-ebp
#?     89/<- %ebp 4/r32/esp
#?     # . save registers
#?     50/push-eax
#? $push-n-zero-bytes:end:
#?     # . restore registers
#?     58/pop-to-eax
#?     # . epilogue
#?     5d/pop-to-ebp
#?     c3/return

# stack at dump-stack3:
# 0 a: bdffffd0: 00000000 00000000 00000000 00000000
# 0 a: bdffffe0: 00000000 34353637 bdfffff8 090000d1
# 0 a: bdfffff0: 00000004 fcfdfeff 00000001 bf000000

## 2

#? push-n-zero-bytes:  # n: int
#?     # . prologue
#?     55/push-ebp
#?     89/<- %ebp 4/r32/esp
#?     # . save registers
#?     50/push-eax
#?     #
#?     8b/-> *(esp+8) 0/r32/eax
#?     2b/subtract *(ebp+8) 4/r32/esp
#?     89/<- *(esp+8) 0/r32/eax
#? $push-n-zero-bytes:end:
#?     # . restore registers
#?     58/pop-to-eax
#?     # . epilogue
#?     5d/pop-to-ebp
#?     c3/return

# stack at dump-stack3:
# 0 a: bdffff90: 00000000 00000000 00000000 00000000
# 0 a: bdffffa0: 00000000 00000000 00000000 00000000
# 0 a: bdffffb0: 00000000 00000000 00000000 00000000
# 0 a: bdffffc0: 00000000 00000000 00000000 090000d1
# 0 a: bdffffd0: 00000000 00000000 00000000 00000000
# 0 a: bdffffe0: 00000000 34353637 bdfffff8 090000d1
# 0 a: bdfffff0: 00000020 fcfdfeff 00000001 bf000000

## 3

#? push-n-zero-bytes:  # n: int
#?     # . prologue
#?     55/push-ebp
#?     89/<- %ebp 4/r32/esp
#?     # . save registers
#?     # -- esp = ebp
#?     50/push-eax
#?     # -- esp+8 = ebp+4
#?     8b/-> *(esp+8) 0/r32/eax
#?     2b/subtract *(ebp+8) 4/r32/esp
#?     89/<- *(esp+8) 0/r32/eax
#?     c7 0/subop/copy *(ebp+4) 0/imm32
#? $push-n-zero-bytes:end:
#?     # . restore registers
#?     58/pop-to-eax
#?     # . epilogue
#?     5d/pop-to-ebp
#?     c3/return

# stack at dump-stack3:
# 0 a: bdffff90: 00000000 00000000 00000000 00000000
# 0 a: bdffffa0: 00000000 00000000 00000000 00000000
# 0 a: bdffffb0: 00000000 00000000 00000000 00000000
# 0 a: bdffffc0: 00000000 00000000 00000000 090000d1
# 0 a: bdffffd0: 20202020 00000000 00000000 00000000
# 0 a: bdffffe0: 00000000 34353637 bdfffff8 00000000
# 0 a: bdfffff0: 00000020 fcfdfeff 00000001 bf000000

## 4

#? push-n-zero-bytes:  # n: int
#?     # . prologue
#?     55/push-ebp
#?     89/<- %ebp 4/r32/esp
#?     # . save registers
#?     # -- esp = ebp
#?     50/push-eax
#?     # copy return address over
#?     # -- esp+8 = ebp+4
#?     8b/-> *(esp+8) 0/r32/eax
#?     2b/subtract *(ebp+8) 4/r32/esp
#?     89/<- *(esp+8) 0/r32/eax
#?     58/pop-to-eax
#?     c7 0/subop/copy *(ebp+8) 0/imm32
#?     c7 0/subop/copy *(ebp+4) 0/imm32
#?     c7 0/subop/copy *(ebp+0) 0/imm32
#?     c7 0/subop/copy *(ebp-4) 0/imm32
#?     # . epilogue
#?     5d/pop-to-ebp
#?     c3/return

# stack at dump-stack3:
# 0 a: bdffff90: 00000000 00000000 00000000 00000000
# 0 a: bdffffa0: 00000000 00000000 00000000 00000000
# 0 a: bdffffb0: 00000000 00000000 00000000 00000000
# 0 a: bdffffc0: 00000000 00000000 00000000 090000d1
# 0 a: bdffffd0: 20202020 00000000 00000000 00000000
# 0 a: bdffffe0: 00000000 00000000 00000000 00000000
# 0 a: bdfffff0: 00000000 fcfdfeff 00000001 bf000000

# Stack looks good now (the 20202020 marks where the array length 0x20 will
# go, and the next 0x20 bytes show the space for the array has been zeroed
# out).
# Final issue: ebp has been clobbered on return.

## 5

# I'd like to translate ebp to esp so we can stop pushing ebp. But we need to
# hold 'n' somewhere, which would require a register, which we then need to
# push.

#? push-n-zero-bytes:  # n: int
#?     55/push-ebp
#?     89/<- %ebp 4/r32/esp
#?     # -- esp = ebp
#?     50/push-eax
#? $push-n-zero-bytes:bulk-cleaning:
#? $push-n-zero-bytes:copy-ra:
#?     # -- esp+8 = ebp+4
#?     8b/-> *(esp+8) 0/r32/eax
#?     2b/subtract *(esp+0xc) 4/r32/esp
#?     # -- esp+8+n = ebp+4
#?     89/<- *(esp+8) 0/r32/eax
#?     58/pop-to-eax
#?     # -- esp+n = ebp
#? $push-n-zero-bytes:spot-cleaning:
#?     c7 0/subop/copy *(ebp+8) 0/imm32
#?     c7 0/subop/copy *(ebp+4) 0/imm32
#?     c7 0/subop/copy *(ebp+0) 0/imm32
#?     c7 0/subop/copy *(ebp-4) 0/imm32
#?     5d/pop-to-ebp
#?     c3/return

# stack at dump-stack3:
# 0 a: bdffff90: 00000000 00000000 00000000 00000000
# 0 a: bdffffa0: 00000000 00000000 00000000 00000000
# 0 a: bdffffb0: 00000000 00000000 00000000 00000000
# 0 a: bdffffc0: 00000000 00000000 00000000 090000d1
# 0 a: bdffffd0: 20202020 00000000 00000000 00000000
# 0 a: bdffffe0: 00000000 00000000 00000000 00000000
# 0 a: bdfffff0: 00000000 fcfdfeff 00000001 bf000000

# Bah. May be simpler to just create a new segment of global space for this
# function.

## 6

#? push-n-zero-bytes:  # n: int
#?     89/<- *Push-n-zero-bytes-ebp 5/r32/ebp  # spill ebp without affecting stack
#?     89/<- %ebp 4/r32/esp
#?     # -- esp = ebp
#?     50/push-eax
#? $push-n-zero-bytes:bulk-cleaning:
#? $push-n-zero-bytes:copy-ra:
#?     # -- esp+8 = ebp+4
#?     # -- esp+4 = ebp
#?     8b/-> *(esp+4) 0/r32/eax
#?     2b/subtract *(ebp+4) 4/r32/esp
#?     # -- esp+4+n = ebp
#?     89/<- *(esp+4) 0/r32/eax
#?     58/pop-to-eax
#?     # -- esp+n = ebp
#? $push-n-zero-bytes:spot-cleaning:
#?     c7 0/subop/copy *(ebp+4) 0/imm32
#?     c7 0/subop/copy *(ebp+0) 0/imm32
#?     c7 0/subop/copy *(ebp-4) 0/imm32
#?     c7 0/subop/copy *(ebp-8) 0/imm32
#?     8b/-> *Push-n-zero-bytes-ebp 5/r32/ebp  # restore spill
#?     c3/return
#? 
#? == data
#? Push-n-zero-bytes-ebp:  # (addr int)
#?   0/imm32
#? == code

# stack at dump-stack3:
# 0 a: bdffff90: 00000000 00000000 00000000 00000000
# 0 a: bdffffa0: 00000000 00000000 00000000 00000000
# 0 a: bdffffb0: 00000000 00000000 00000000 00000000
# 0 a: bdffffc0: 00000000 00000000 00000000 090000d1
# 0 a: bdffffd0: 20202020 00000000 00000000 00000000
# 0 a: bdffffe0: 00000000 00000000 00000000 00000000
# 0 a: bdfffff0: 00000000 fcfdfeff 00000001 bf000000

# Ok, we're there. Now start using zero-out rather than spot-cleaning.

## 7: we need to zero out the return address, but we can't do it inside the function.
## So we'll change the signature slightly.
## Before: clear N bytes and then push N as the array length.
## After: clear N bytes, set *esp to N.
## The helper adds and clears N bytes *before* esp. esp can't be cleared since
## it contains the return address.

#? Entry:
#?     # . prologue
#?     89/<- %ebp 4/r32/esp
#?     #
#?     68/push 0xfcfdfeff/imm32
#?     b8/copy-to-eax 0x34353637/imm32
#? $dump-stack0:
#?     (push-n-zero-bytes 0x20)
#? $dump-stack9:
#?     c7 0/subop/copy *esp 0x20/imm32
#? $dump-stacka:
#?     b8/copy-to-eax 1/imm32/exit
#?     cd/syscall 0x80/imm8
#? 
#? push-n-zero-bytes:  # n: int
#? $push-n-zero-bytes:prologue:
#?     89/<- *Push-n-zero-bytes-ebp 5/r32/ebp  # spill ebp without affecting stack
#?     89/<- %ebp 4/r32/esp
#? $push-n-zero-bytes:copy-ra:
#? $dump-stack1:
#?     # -- esp = ebp
#?     50/push-eax
#? $dump-stack2:
#?     # -- esp+8 = ebp+4
#?     # -- esp+4 = ebp
#?     8b/-> *(esp+4) 0/r32/eax
#? $dump-stack3:
#?     2b/subtract *(ebp+4) 4/r32/esp
#? $dump-stack4:
#?     # -- esp+4+n = ebp
#?     89/<- *(esp+4) 0/r32/eax
#? $dump-stack5:
#?     58/pop-to-eax
#?     # -- esp+n = ebp
#? $push-n-zero-bytes:bulk-cleaning:
#? $dump-stack6:
#?     89/<- *Push-n-zero-bytes-esp 4/r32/esp
#?     81 0/subop/add *Push-n-zero-bytes-esp 4/imm32
#? $dump-stack7:
#?     (zero-out *Push-n-zero-bytes-esp *(ebp+4))  # n
#? $push-n-zero-bytes:epilogue:
#? $dump-stack8:
#?     8b/-> *Push-n-zero-bytes-ebp 5/r32/ebp  # restore spill
#?     c3/return
#? 
#? zero-out:  # start: (addr byte), len: int
#?     # pseudocode:
#?     #   curr/esi = start
#?     #   i/ecx = 0
#?     #   while true
#?     #     if (i >= len) break
#?     #     *curr = 0
#?     #     ++curr
#?     #     ++i
#?     #
#?     # . prologue
#?     55/push-ebp
#?     89/copy                         3/mod/direct    5/rm32/ebp    .           .             .           4/r32/esp   .               .                 # copy esp to ebp
#?     # . save registers
#?     50/push-eax
#?     51/push-ecx
#?     52/push-edx
#?     56/push-esi
#?     # curr/esi = start
#?     8b/copy                         1/mod/*+disp8   5/rm32/ebp    .           .             .           6/r32/esi   8/disp8         .                 # copy *(ebp+8) to esi
#?     # var i/ecx: int = 0
#?     31/xor                          3/mod/direct    1/rm32/ecx    .           .             .           1/r32/ecx   .               .                 # clear ecx
#?     # edx = len
#?     8b/copy                         1/mod/*+disp8   5/rm32/ebp    .           .             .           2/r32/edx   0xc/disp8       .                 # copy *(ebp+12) to edx
#? $zero-out:loop:
#?     # if (i >= len) break
#?     39/compare                      3/mod/direct    1/rm32/ecx    .           .             .           2/r32/edx   .               .                 # compare ecx with edx
#?     7d/jump-if->=  $zero-out:end/disp8
#?     # *curr = 0
#?     c6          0/subop/copy        0/mod/direct    6/rm32/esi    .           .             .           .           .               0/imm8            # copy byte to *esi
#?     # ++curr
#?     46/increment-esi
#?     # ++i
#?     41/increment-ecx
#?     eb/jump  $zero-out:loop/disp8
#? $zero-out:end:
#?     # . restore registers
#?     5e/pop-to-esi
#?     5a/pop-to-edx
#?     59/pop-to-ecx
#?     58/pop-to-eax
#?     # . epilogue
#?     89/copy                         3/mod/direct    4/rm32/esp    .           .             .           5/r32/ebp   .               .                 # copy ebp to esp
#?     5d/pop-to-ebp
#?     c3/return
#? 
#? == data
#? Push-n-zero-bytes-ebp:  # (addr int)
#?   0/imm32
#? Push-n-zero-bytes-esp:  # (addr int)
#?   0/imm32
#? == code

# stack at dump-stack0:
# 0 a: bdffffb0:  00000000   00000000   00000000   00000000 
# 0 a: bdffffc0:  00000000   00000000   00000000   00000000 
# 0 a: bdffffd0:  00000000   00000000   00000000   00000000 
# 0 a: bdffffe0:  00000000   00000000   00000000   00000000 
# 0 a: bdfffff0:  00000000  [fcfdfeff]  00000001   bf000000 

# desired state after push-n-zero-bytes:
# 0 a: bdffff90:  00000000   00000000   00000000   00000000 
# 0 a: bdffffa0:  00000000   00000000   00000000   00000000 
# 0 a: bdffffb0:  00000000   00000000   00000000   bdffffec 
# 0 a: bdffffc0:  0900012a   bdffffd0   00000020   090000d1 
# 0 a: bdffffd0: [rrrrrrrr]  00000000   00000000   00000000 
# 0 a: bdffffe0:  00000000   00000000   00000000   00000000 
# 0 a: bdfffff0:  00000000   fcfdfeff   00000001   bf000000 

# Stack pointer contains ra is caller's responsibility to over-write with array length.

# actual state:
# 0 a: bdffff90:  00000000   00000000   00000000   00000000
# 0 a: bdffffa0:  00000000   00000000   00000000   00000000
# 0 a: bdffffb0:  00000000   00000000   00000000   bdffffec
# 0 a: bdffffc0:  0900012a   bdffffd0   00000020   090000d1
# 0 a: bdffffd0:  00000000  [00000000]  00000000   00000000
# 0 a: bdffffe0:  00000000   00000000   00000000   00000000
# 0 a: bdfffff0:  00000020   fcfdfeff   00000001   bf000000

# Couple of issues. But where does the return address disappear to?

## 8:

#? Entry:
#?     # . prologue
#?     89/<- %ebp 4/r32/esp
#?     #
#?     68/push 0xfcfdfeff/imm32
#?     b8/copy-to-eax 0x34353637/imm32
#? $dump-stack0:
#?     (push-n-zero-bytes 0x20)
#? $dump-stack9:
#?     68/push 0x20/imm32
#? #?     c7 0/subop/copy *esp 0x20/imm32
#? $dump-stacka:
#?     b8/copy-to-eax 1/imm32/exit
#?     cd/syscall 0x80/imm8
#? 
#? push-n-zero-bytes:  # n: int
#? $push-n-zero-bytes:prologue:
#?     89/<- *Push-n-zero-bytes-ebp 5/r32/ebp  # spill ebp without affecting stack
#?     89/<- %ebp 4/r32/esp
#? $push-n-zero-bytes:copy-ra:
#? $dump-stack1:
#?     # -- esp = ebp
#?     50/push-eax
#? $dump-stack2:
#?     # -- esp+8 = ebp+4
#?     # -- esp+4 = ebp
#?     8b/-> *(esp+4) 0/r32/eax
#? $dump-stack3:
#?     2b/subtract *(ebp+4) 4/r32/esp
#? $dump-stack4:
#?     # -- esp+4+n = ebp
#?     89/<- *(esp+4) 0/r32/eax
#? $dump-stack5:
#?     58/pop-to-eax
#?     # -- esp+n = ebp
#? $push-n-zero-bytes:bulk-cleaning:
#? $dump-stack6:
#?     89/<- *Push-n-zero-bytes-esp 4/r32/esp
#?     81 0/subop/add *Push-n-zero-bytes-esp 4/imm32
#? $dump-stack7:
#?     (zero-out *Push-n-zero-bytes-esp *(ebp+4))  # n
#? $push-n-zero-bytes:epilogue:
#? $dump-stack8:
#?     8b/-> *Push-n-zero-bytes-ebp 5/r32/ebp  # restore spill
#?     c3/return
#? 
#? zero-out:  # start: (addr byte), len: int
#?     # pseudocode:
#?     #   curr/esi = start
#?     #   i/ecx = 0
#?     #   while true
#?     #     if (i >= len) break
#?     #     *curr = 0
#?     #     ++curr
#?     #     ++i
#?     #
#?     # . prologue
#?     55/push-ebp
#?     89/copy                         3/mod/direct    5/rm32/ebp    .           .             .           4/r32/esp   .               .                 # copy esp to ebp
#?     # . save registers
#?     50/push-eax
#?     51/push-ecx
#?     52/push-edx
#?     56/push-esi
#?     # curr/esi = start
#?     8b/copy                         1/mod/*+disp8   5/rm32/ebp    .           .             .           6/r32/esi   8/disp8         .                 # copy *(ebp+8) to esi
#?     # var i/ecx: int = 0
#?     31/xor                          3/mod/direct    1/rm32/ecx    .           .             .           1/r32/ecx   .               .                 # clear ecx
#?     # edx = len
#?     8b/copy                         1/mod/*+disp8   5/rm32/ebp    .           .             .           2/r32/edx   0xc/disp8       .                 # copy *(ebp+12) to edx
#? $zero-out:loop:
#?     # if (i >= len) break
#?     39/compare                      3/mod/direct    1/rm32/ecx    .           .             .           2/r32/edx   .               .                 # compare ecx with edx
#?     7d/jump-if->=  $zero-out:end/disp8
#?     # *curr = 0
#?     c6          0/subop/copy        0/mod/direct    6/rm32/esi    .           .             .           .           .               0/imm8            # copy byte to *esi
#?     # ++curr
#?     46/increment-esi
#?     # ++i
#?     41/increment-ecx
#?     eb/jump  $zero-out:loop/disp8
#? $zero-out:end:
#?     # . restore registers
#?     5e/pop-to-esi
#?     5a/pop-to-edx
#?     59/pop-to-ecx
#?     58/pop-to-eax
#?     # . epilogue
#?     89/copy                         3/mod/direct    4/rm32/esp    .           .             .           5/r32/ebp   .               .                 # copy ebp to esp
#?     5d/pop-to-ebp
#?     c3/return
#? 
#? == data
#? Push-n-zero-bytes-ebp:  # (addr int)
#?   0/imm32
#? Push-n-zero-bytes-esp:  # (addr int)
#?   0/imm32
#? == code

# stack at dump-stack0:
# 0 a: bdffffb0:  00000000   00000000   00000000   00000000 
# 0 a: bdffffc0:  00000000   00000000   00000000   00000000 
# 0 a: bdffffd0:  00000000   00000000   00000000   00000000 
# 0 a: bdffffe0:  00000000   00000000   00000000   00000000 
# 0 a: bdfffff0:  00000000  [fcfdfeff]  00000001   bf000000 

# desired state after push-n-zero-bytes:
# 0 a: bdffff90:  00000000   00000000   00000000   00000000 
# 0 a: bdffffa0:  00000000   00000000   00000000   00000000 
# 0 a: bdffffb0:  00000000   00000000   00000000   bdffffec 
# 0 a: bdffffc0:  0900012a   bdffffd0   00000020   090000d1 
# 0 a: bdffffd0: [rrrrrrrr]  00000000   00000000   00000000 
# 0 a: bdffffe0:  00000000   00000000   00000000   00000000 
# 0 a: bdfffff0:  00000000   fcfdfeff   00000001   bf000000 

# actual state:
# 0 a: bdffff90:  00000000   00000000   00000000   00000000
# 0 a: bdffffa0:  00000000   00000000   00000000   00000000
# 0 a: bdffffb0:  00000000   00000000   00000000   bdffffec
# 0 a: bdffffc0:  09000124   bdffffd0   00000020   090000d1
# 0 a: bdffffd0: [00000000]  00000000   00000000   00000000
# 0 a: bdffffe0:  00000000   00000000   00000000   00000000
# 0 a: bdfffff0:  00000020   fcfdfeff   00000001   bf000000

# Ok, just one diff, at bdfffff0

## 9:

Entry:
    # . prologue
    89/<- %ebp 4/r32/esp
    #
    68/push 0xfcfdfeff/imm32
    b8/copy-to-eax 0x34353637/imm32
$dump-stack0:
    (push-n-zero-bytes 0x20)
$dump-stack9:
    68/push 0x20/imm32
$dump-stacka:
    b8/copy-to-eax 1/imm32/exit
    cd/syscall 0x80/imm8

push-n-zero-bytes:  # n: int
$push-n-zero-bytes:prologue:
    89/<- *Push-n-zero-bytes-ebp 5/r32/ebp  # spill ebp without affecting stack
    89/<- %ebp 4/r32/esp
$push-n-zero-bytes:copy-ra:
$dump-stack1:
    # -- esp = ebp
    50/push-eax
$dump-stack2:
    # -- esp+8 = ebp+4
    # -- esp+4 = ebp
    8b/-> *(esp+4) 0/r32/eax
$dump-stack3:
    2b/subtract *(ebp+4) 4/r32/esp
$dump-stack4:
    # -- esp+4+n = ebp
    89/<- *(esp+4) 0/r32/eax
$dump-stack5:
    58/pop-to-eax
    # -- esp+n = ebp
$push-n-zero-bytes:bulk-cleaning:
$dump-stack6:
    89/<- *Push-n-zero-bytes-esp 4/r32/esp
    81 0/subop/add *Push-n-zero-bytes-esp 4/imm32
$dump-stack7:
    81 0/subop/add *(ebp+4) 4/imm32
    (zero-out *Push-n-zero-bytes-esp *(ebp+4))  # n
$push-n-zero-bytes:epilogue:
$dump-stack8:
    8b/-> *Push-n-zero-bytes-ebp 5/r32/ebp  # restore spill
    c3/return

zero-out:  # start: (addr byte), len: int
    # pseudocode:
    #   curr/esi = start
    #   i/ecx = 0
    #   while true
    #     if (i >= len) break
    #     *curr = 0
    #     ++curr
    #     ++i
    #
    # . prologue
    55/push-ebp
    89/copy                         3/mod/direct    5/rm32/ebp    .           .             .           4/r32/esp   .               .                 # copy esp to ebp
    # . save registers
    50/push-eax
    51/push-ecx
    52/push-edx
    56/push-esi
    # curr/esi = start
    8b/copy                         1/mod/*+disp8   5/rm32/ebp    .           .             .           6/r32/esi   8/disp8         .                 # copy *(ebp+8) to esi
    # var i/ecx: int = 0
    31/xor                          3/mod/direct    1/rm32/ecx    .           .             .           1/r32/ecx   .               .                 # clear ecx
    # edx = len
    8b/copy                         1/mod/*+disp8   5/rm32/ebp    .           .             .           2/r32/edx   0xc/disp8       .                 # copy *(ebp+12) to edx
$zero-out:loop:
    # if (i >= len) break
    39/compare                      3/mod/direct    1/rm32/ecx    .           .             .           2/r32/edx   .               .                 # compare ecx with edx
    7d/jump-if->=  $zero-out:end/disp8
    # *curr = 0
    c6          0/subop/copy        0/mod/direct    6/rm32/esi    .           .             .           .           .               0/imm8            # copy byte to *esi
    # ++curr
    46/increment-esi
    # ++i
    41/increment-ecx
    eb/jump  $zero-out:loop/disp8
$zero-out:end:
    # . restore registers
    5e/pop-to-esi
    5a/pop-to-edx
    59/pop-to-ecx
    58/pop-to-eax
    # . epilogue
    89/copy                         3/mod/direct    4/rm32/esp    .           .             .           5/r32/ebp   .               .                 # copy ebp to esp
    5d/pop-to-ebp
    c3/return

== data
Push-n-zero-bytes-ebp:  # (addr int)
  0/imm32
Push-n-zero-bytes-esp:  # (addr int)
  0/imm32
== code

# stack at dump-stack0:
# 0 a: bdffffb0:  00000000   00000000   00000000   00000000 
# 0 a: bdffffc0:  00000000   00000000   00000000   00000000 
# 0 a: bdffffd0:  00000000   00000000   00000000   00000000 
# 0 a: bdffffe0:  00000000   00000000   00000000   00000000 
# 0 a: bdfffff0:  00000000  [fcfdfeff]  00000001   bf000000 

# desired state after push-n-zero-bytes:
# 0 a: bdffff90:  00000000   00000000   00000000   00000000 
# 0 a: bdffffa0:  00000000   00000000   00000000   00000000 
# 0 a: bdffffb0:  00000000   00000000   00000000   bdffffec 
# 0 a: bdffffc0:  0900012a   bdffffd0   00000020   090000d1 
# 0 a: bdffffd0: [xxxxxxxx]  00000000   00000000   00000000 
# 0 a: bdffffe0:  00000000   00000000   00000000   00000000 
# 0 a: bdfffff0:  00000000   fcfdfeff   00000001   bf000000 

# actual state:
# 0 a: bdffff90:  00000000   00000000   00000000   00000000
# 0 a: bdffffa0:  00000000   00000000   00000000   00000000
# 0 a: bdffffb0:  00000000   00000000   00000000   bdffffec
# 0 a: bdffffc0:  0900012f   bdffffd0   00000024   090000d1
# 0 a: bdffffd0: [00000000]  00000000   00000000   00000000
# 0 a: bdffffe0:  00000000   00000000   00000000   00000000
# 0 a: bdfffff0:  00000000   fcfdfeff   00000001   bf000000
ass='oid'>4d87267 ^
11074e0 ^


4120bca ^


















8af4130 ^
8af4130 ^
a0a2564 ^
dc4c58d ^
8af4130 ^


a0a2564 ^

4d87267 ^







8af4130 ^

b4f90ec ^
8af4130 ^



4120bca ^


4d87267 ^



11074e0 ^

8af4130 ^

4d87267 ^
0de5b3a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372


                       
                         
 

                   
                    



                   
                      



                      
                   
                   
 

                        



                               
                 
                  

                   

                      

  

                   
                                



                                                        


                                                                             

 
                                    


                                                                      
 
                 

 




                                           


                                                                            
 


                                         

                 
 


                                                                            
 


                                         

                 
 


                                                                           
 


                                         

                 
 
                 

 
                                                                         

                                                            

                 
                                       


                              
                                                


                                                        
                                        

                                  

                                                            




                                                                      



                                                         
                                                                                  
                                               
                                                   
                                         



                                                                                          
                                                         


                                                                                                        

                                          

                                                                  
                                                 



                                                                    
 











                                                                                                                


                                         
                                                       
                                                      
                                                            
                                                
                                                            
                                         
                                 

                         
                                      


                                                                   












                                                                               
 
 
                                 
                                    





                               
 
               
                        






                                          
 








                                                             
                             



                                                      



                                      


                                           
 
                         
                                               

                              
                         
                                            

                              

                                               

                              
                         

                                                                           
 



                                                                
 

                                                       
 
                              


                 


                                                                                                   
 























































                                                                                                        


                                   


















                                                                                                               
                            
                          
                                                  
                                                                                 


                                               

                                                       







                                                                                      

                 
                                                                              



                                                                         


                                             



                                                             

                            

         
                           
 
#define _BSD_SOURCE
#define _DEFAULT_SOURCE

#define _XOPEN_SOURCE 700

#include <dirent.h>
#include <errno.h>
#include <fnmatch.h>
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

#include "config.h"
#include "ignore.h"

extern char *__progname;

struct ignores *global_ignores;
struct ignores *config_ignores;
struct ignores *local_ignores;

struct switches {
	int count;
	int invert;
	int limit;
	int substring;
	int wholename;
};

int read_links = 0;

static void usage(char *error) {
	if (error != NULL) {
		fprintf(stderr, "Error: %s\n\n", error);
	}

	fprintf(stderr,
		"usage: %s [-d directory] [-c config] [-lsvw] pattern ...\n",
		__progname);
}

static int is_child(char *dirname) {
	if (strcmp("..", dirname) == 0 || strcmp(".", dirname) == 0) {
		return 0;
	}

	return 1;
}

static int excluded(const char *name) {
	if (!fnmatch("/proc/*", name, 0)) {
		return 1;
	}

	if (global_ignores != NULL) {
		for (int i = 0; i < global_ignores->size; i++) {
			int res = fnmatch(global_ignores->list[i], name, 0);

			if (res == 0) {
				return 1;
			}
		}
	}

	if (config_ignores != NULL) {
		for (int i = 0; i < config_ignores->size; i++) {
			int res = fnmatch(config_ignores->list[i], name, 0);

			if (res == 0) {
				return 1;
			}
		}
	}

	if (local_ignores != NULL) {
		for (int i = 0; i < local_ignores->size; i++) {
			int res = fnmatch(local_ignores->list[i], name, 0);

			if (res == 0) {
				return 1;
			}
		}
	}

	return 0;
}

/* return 1 if breaking early (e.g. reaching limit) otherwise return 0 */
static int recurse_find(char **patterns, int *pattern_count,
	const char *dirname, struct switches *switches) {
	DIR *dir;

	char path[MAXPATHLEN] = {'\0'};
	strcat(path, dirname);
	dir = opendir(path);

	if (dir != NULL && !excluded(dirname)) {
		struct dirent *entry;

		while ((entry = readdir(dir)) != NULL) {
			int matched = 0;
			int p = 0;

			char full_path[MAXPATHLEN] = {'\0'};
			strcat(full_path, path);

			if (full_path[strlen(full_path) - 1] != '/') {
				strcat(full_path, "/");
			}

			strcat(full_path, entry->d_name);

			struct stat entry_stat;

			if ((read_links ? stat : lstat)(full_path, &entry_stat)) {
				perror("stat");
				exit(EXIT_FAILURE);
				continue;
			}

			if (entry_stat.st_mode & S_IFDIR) {
				if (is_child(entry->d_name) && !excluded(entry->d_name)) {
					if (recurse_find(
							patterns, pattern_count, full_path, switches)) {
						closedir(dir);
						return 1;
					};
				}
			} else if (entry_stat.st_mode & S_IFREG) {
				if (excluded(entry->d_name)) {
					continue;
				}

				for (; p < *pattern_count; p++) {
					char *pattern = patterns[p];

					if (switches->substring) {
						if (strstr(
								switches->wholename ? full_path : entry->d_name,
								pattern) != NULL) {
							matched = 1;
						}
					} else {
						if (fnmatch(pattern,
								switches->wholename ? full_path : entry->d_name,
								0) == 0) {
							matched = 1;
						}
					}
				}

				if (switches->invert) {
					if (matched) {
						matched = 0;
					} else {
						matched = 1;
					}
				}
			}

			if (matched) {
				if (is_child(entry->d_name) != 0) {
					printf("%s\n", full_path);
				}

				if (switches->limit > 0 &&
					++switches->count == switches->limit) {
					closedir(dir);
					return 1;
				}
			}
		} /* while */

		closedir(dir);
	} /* if */

	return 0;
}

int main(int argc, char **argv) {
	struct switches switches = {
		.count = 0,
		.invert = 0,
		.limit = 0,
		.substring = 0,
		.wholename = 0,
	};

	int ch;
	char *remainder;
	size_t len = 0;
	const char *root = ".";
	FILE *fp;
	char cwd[MAXPATHLEN];
	int unmatched_error = 0;
	char wildcard = 0;
	char *override_config_file = NULL;

	if (getcwd(cwd, MAXPATHLEN) == NULL) {
		perror("getcwd");
		exit(EXIT_FAILURE);
	}

	char *xdg_config_home = getenv("XDG_CONFIG_HOME");
	char *home = getenv("HOME");

	while ((ch = getopt(argc, argv, "c:d:l:svw")) > -1) {
		switch (ch) {
		case 'c':
			override_config_file = optarg;
			break;

		case 'd':
			root = optarg;
			break;

		case 'h':
			usage(NULL);
			exit(EXIT_SUCCESS);

		case 's':
			switches.substring = 1;
			break;

		case 'v':
			switches.invert = 1;
			break;

		case 'w':
			switches.wholename = 1;
			break;

		case 'l':
			do {
				int limit = strtol(optarg, &remainder, 10);

				if (limit < 0) {
					usage("Invalid limit.");
					exit(EXIT_FAILURE);
				}

				switches.limit = limit;
			} while (0);

			break;
		}
	}

	char config_file[xdg_config_home
						 ? (strlen(xdg_config_home) + strlen("ignore") + 3)
						 : (strlen(cwd) + strlen(".rfignore") + 1)];

	if (xdg_config_home) {
		sprintf(config_file, "%s/rf/%s", xdg_config_home, "config");
	} else {
		sprintf(config_file, "%s/.config/rf/%s", home, "config");
	}

	fp = fopen(override_config_file ? override_config_file : config_file, "r");

	if (fp != NULL) {
		while ((config_get(&len, fp)) != -1) {
			if (strlen(config_key) && strlen(config_value)) {
				if (strcmp(config_key, "symlinks") == 0) {
					if (strcmp(config_value, "true") == 0) {
						read_links = 1;
					} else if (strcmp(config_value, "false") == 0) {
						read_links = 0;
					} else {
						fprintf(stderr,
							"'%s' is not a valid value for property: %s.\n",
							config_value, config_key);
						exit(EXIT_FAILURE);
					}
				} else if (strcmp(config_key, "wholename") == 0) {
					if (strcmp(config_value, "true") == 0) {
						switches.wholename = 1;
					} else if (strcmp(config_value, "false") == 0) {
						/* default */
					} else {
						fprintf(stderr,
							"'%s' is not a valid value for property: %s.\n",
							config_value, config_key);
						exit(EXIT_FAILURE);
					}
				} else if (strcmp(config_key, "limit") == 0) {
					int limit = strtol(config_value, &remainder, 10);

					if (limit < 0) {
						fprintf(stderr, "Warning: Invalid limit, ignoring.");
					} else {
						switches.limit = limit;
					}
				} else if (strcmp(config_key, "unmatched error") == 0) {
					unmatched_error = 1;
				} else if (strcmp(config_key, "wildcard") == 0) {
					wildcard = config_value[0];
				}
			} else if (strlen(config_key)) {
				fprintf(stderr,
					"Warning: Ignoring empty config property '%s'.\n",
					config_key);
			}
		}

		fclose(fp);
	} else if (override_config_file) {
		perror("fopen");
		exit(EXIT_FAILURE);
	}

	char global_ignore_path[(strlen(home) + strlen(".rfignore") + 1)];
	char config_ignore_path[xdg_config_home
								? (strlen(xdg_config_home) + strlen("ignore") +
									  3)
								: (strlen(cwd) + strlen(".rfignore") + 1)];
	char local_ignore_path[strlen(cwd) + strlen(".rfignore") + 1];
	sprintf(global_ignore_path, "%s/%s", home, ".rfignore");
	sprintf(local_ignore_path, "%s/%s", cwd, ".rfignore");

	if (xdg_config_home) {
		sprintf(config_ignore_path, "%s/rf/%s", xdg_config_home, "ignore");
	} else {
		sprintf(config_ignore_path, "%s/.config/rf/%s", home, "ignore");
	}

	global_ignores = init_ignores(global_ignore_path);
	config_ignores = init_ignores(config_ignore_path);
	local_ignores = init_ignores(local_ignore_path);

	if (optind < argc) {
		int i = 0;
		int pattern_count = argc - optind;
		char **patterns = (char **)calloc(sizeof(char *), pattern_count);

		memset(patterns, '\0', optind);

		while (optind < argc) {
			patterns[i++] = argv[optind++];

			if (wildcard) {
				for (size_t j = 0; j < strlen(patterns[i - 1]); j++) {
					if (patterns[i - 1][j] == wildcard) {
						patterns[i - 1][j] = '*';
					}
				}
			}
		}

		if (recurse_find(patterns, &pattern_count, root, &switches)) {
			/* finished early because we reached the limit */
		};

		free(patterns);
		free_ignores(global_ignores);
		free_ignores(config_ignores);
		free_ignores(local_ignores);

		if (unmatched_error && switches.count == 0) {
			exit(EXIT_FAILURE);
		}
	} else {
		usage(NULL);
	}

	exit(EXIT_SUCCESS);
}