Why call and ret functions work like this in assembly? - debugging

So, I was messing around with assembly, and stumbled upon weird thing. Before writing anything, I set registers to these values:
AX 0000, BX 0000, SP 00FD.
Lets say, that we write simple code, which increases registers AX and BX:
A100
INC AX
CALL 0200
A200
INC BX
RETN
After writing it, I tried to see how registers change when executing commands, one by one, using T command. First time, it increases AX, moves to 0200, increases BX and returns. Here is the weird bit: when it returns, it executes command:
ADD [BX+SI],AX and then calls 0200 again.
When it calls 0200 again, it repeats itself, but now, when it returns, it returns to CALL 0100 command (not to CALL 0200) and increases AX again and so on. Why is this happening?
I have image of full output, maybe this can help understand my question better?:
http://s18.postimg.org/wt6eracg9/Untitled.png

Based on your screenshots, your code seems to be this (filled with nop's, disassembled with udcli):
echo 40 e8 fc 00 01 00 e8 f7 00 e8 f4 ff x{1..244} 43 c3 | sed 's/x[0-9]*\>/90/g' | udcli -o 0x100 -x -16
0000000000000100 40 inc ax
0000000000000101 e8fc00 call word 0x200
0000000000000104 0100 add [bx+si], ax
0000000000000106 e8f700 call word 0x200
0000000000000109 e8f4ff call word 0x100
000000000000010c *** never reached ***
0000000000000200 43 inc bx
0000000000000201 c3 ret
The code flow is the following, line by line:
0000000000000100 40 inc ax
ax gets incremented.
0000000000000101 e8fc00 call word 0x200
Return address 0x104 gets pushed to the stack, ip (instruction pointer) is set to 0x200.
0000000000000200 43 inc bx
bx gets incremented.
0000000000000201 c3 ret
Near return, that is, ip is popped from stack. New ip will be 0x104.
0000000000000104 0100 add [bx+si], ax
The value of ax is added to the word value at [bx+si].
0000000000000106 e8f700 call word 0x200
Return address 0x109 gets pushed to the stack, ip (instruction pointer) is set to 0x200.
0000000000000200 43 inc bx
bx gets incremented.
0000000000000201 c3 ret
Near return, that is, ip is popped from stack. New ip will be 0x109.
0000000000000109 e8f4ff call word 0x100
Return address 0x10c gets pushed to the stack, ip (instruction pointer) is set to 0x100. So this is actually an infinite recursive function and will run out of stack.
So your problem is that you don't define the code after CALL 0200. There happens to be 01 00 (add [bx+si], ax) and after return it will be executed, and after it other undefined instructions.
My advice: download any decent assembler (NASM, YASM, FASM...) ASAP and don't ruin your life trying to write assembly code with DEBUG. Trying to write assembly programs with DEBUG is an attempt destined to fail.

On possible reason is that you don't have some exit, you didn't use DOS's 0x4c service, and the program get bound the code and started to execute random commands or the execution flow hit some ret instruction where no call is used, it then will behave unexpectedly.

Related

Why do these `const int main=0xc3` (or other number) programs return 252 on OS X?

I heard about the "shortest C program that results in an illegal instruction": const main=6; for x86-64 over on codegolf.SE and it got me curious what would happen if I put different numbers there.
Now I guess this has to do with what is or isn't a valid x86-64 instruction (durr) but specifically I'd like to know what the different results mean.
const main=0 through 2 give bus error.
const main=3 gives a segfault.
6 and 7 give illegal instruction.
I get various bus errors and segfaults and illegal instructions up until
const main=194 which didn't give me an interrupt at all (at least not that got through to my python script that was generating these little programs).
There are a few other numbers that also do not lead to exceptions/interrupts and thus to Unix signals. I checked the return code of a couple and the return code was 252. I don't know why or what that means or how it got there.
204 got me a "trace trap". This is 0xcc which I know is the int3 interrupt - that's fun! (241/0xf1 also gets me this)
Anyway, it keeps going and it's obviously mostly bus errors and segfaults and a few illegal instructions here and there and the occasional... does whatever it does and then returns with 252...
I googled around some opcodes but I don't really know what I am doing or where to look to be honest. I haven't even looked at all my outputs yet just been scrolling through. I understand that a segfault is invalid access to valid memory and a bus error is access to invalid memory and I plan to look at the patterns of the numbers and work out where these are happening and why. But the 252 thing has me a bit stumped.
#!/usr/bin/env python3
import os
import subprocess
import time
import signal
os.mkdir("testc")
try:
os.chdir("testc")
except:
print("Could not change directory, exiting.")
for i in range(0, 65536):
filename = "test" + str(i) + ".c"
f = open(filename, "w")
f.write("const main=" + str(i) + ";")
f.close()
outname = "test" + str(i)
subprocess.Popen(["gcc", filename, "-o", outname], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
time.sleep(1)
err = subprocess.Popen("./" + outname, shell=True)
result = None
while result is None:
result = err.poll()
r = result
if result == -11:
r = "segfault"
if result == -10:
r = "bus error"
if result == -4:
r = "illegal instruction"
if result == -5:
print = "trap"
print("const main=" + str(hex(i)) + " : " + r)
This produces a C program in testc/test20.c like
const int main=20;
Then compiles it with gcc and runs it. (And sleeps for 1 second before trying the next number.)
There were no expectations. I just wanted to see what happened.
int main = 194 is c2 00 00 00, which decodes as ret 0
Whatever called main must have left 252 in the low byte of RAX. (The calling convention says that RAX is the return-value register, but it's not an arg-passing register so on function entry it holds whatever tmp garbage your caller was using it for.)
See the bottom of the answer for a theory on why you get SIGBUS for 2 but SIGSEGV for 3: I think RAX is a valid pointer on entry to main (by chance of what the dynamic linker had there), 03 00 add eax, [rax] destroys it but 02 00 add al, [rax] doesn't, and then execution either faults on the 00 00 add [rax], al from the next 2 bytes of main, or runs the 00 00 instruction and then falls off the end of a page.
Update from #MichaelPetch: RAX is pointing to main (in the read-only TEXT segment), and stores to read-only pages also SIGBUS. So 00 00 add [rax], al will SIGBUS for that reason if RAX is still pointing there.
(Beware that this answer has some wrong guesses and wasn't fully rewritten every time I got new info from #SWilliams or #MichaelPetch. The bullet points about what kinds of #PF cause which signal are up to date, and I've tried to at least add a correction after things that weren't quite accurate. I think there's some value to the wrong theories, as an illustration of others kinds of things that might have happened, so I'm leaving it all in here.)
Your Python program fails on my Linux machine once it gets to c2 00 00 00 ret imm16, the first one that returns successfully. (On Linux, the .rodata section ends up after .text in the TEXT segment, so there's nothing for main to fall into.)
...
const main=0xc0 : segfault
const main=0xc1 : segfault
Traceback (most recent call last):
File "./opcode-test.py", line 34, in <module>
print("const main=" + str(hex(i)) + " : " + r)
TypeError: must be str, not int
Doesn't python have an equivalent of strsignal(3) to map signals to standard text strings like "Illegal instruction"? (Like strerror but for signal codes instead of errno values?)
Most x86 instructions are multiple bytes long. x86 is little-endian, so you're mostly looking at
?? 00 00 00 90 90 90 ... or for larger integers ?? ?? 00 00 90 90 90 90 ..., assuming your linker fills bytes between functions with 0x90 nop like GNU ld on Linux does.
These byte sequences might decode to one or more valid instructions before you hit the NOPs and fall through to whatever CRT function the linker puts after main. If you get there without faulting, and without offsetting the stack pointer, you've entered the function with a valid return address on the stack (main's caller, another CRT function) exactly like if main tail-called it.
Presumably that function returns 252 (or some wider value whose low byte is 252). Returning from main leads to clean process exit, making an exit system call with main's return value.
This fall-through tailcall is like if main ended with return next_function(argc, argv);.
Correction (without rewriting the whole answer, sorry)
Since main=194 is the first one that worked, I think you're not actually getting fall-through, probably only C2 ret imm16 and C3 ret are leading to a clean exit. And for c2, it has to be followed by 2 00 bytes, or else it'll break the stack for main's caller.
Or those instructions with a prefix that doesn't do anything, or a harmless one-byte instruction. e.g. 90 nop / c3 ret or 90 nop / c2 00 00 ret 0. Or 91 xchg eax, ecx, etc. could actually give you a different return value, swapping EAX with another register. (x86 dedicates opcodes 90 .. 97 to xchg-with-EAX, because on original 8086 AX was more "special", without instructions like movsx to sign-extend into other registers. And without 2 operand imul.
Other harmless one-byte instructions include 99 cdq and 98 cwde, but not push or pop (because changing RSP would make it not point at the return address). Some one-byte flag set/clear instructions are f9 stc, fd std, but not fb sti (that's privileged, unlike the carry flag and direction flag).
Harmless prefixes are 0x40..4f REX prefixes, 0xf2/f3REP, and0x66and0x67` operand-size and address size. Also any segment-override prefixes might also be harmless.
I just tested main=0xc366 and main=0xc367 and yes they both exit cleanly. GDB decodes 66 c3 as retw (operand-size prefix) and 67 c3 as addr32 ret (address size prefix), but both still pop a 64-bit return address, and don't truncate the stack pointer either. (I took out the -no-pie I'd been using, so RIP was outside the low 32 bits along with RSP).
Note that 00 is the opcode for add [r/m8], r8, so 00 00 decodes as add [rax], al.
To get past those 00 bytes and get to the "nop sled" the linker inserts as padding, you need the opcode (and modrm byte if the opcode uses one) to encode the start of a longer instruction, like 0xb8 mov eax, imm32 which is 5 bytes long, and consumes the next 4 bytes after the 0xb8. In fact there are short-form mov-immediate encodings for every register, so 0xb8 + 0..7 will all get you past the gap. Except for mov esp, imm32, which will lead to a crash once you get to the next function because it stepped on the stack pointer.
One of the early ones is 05, the short-form (no modrm) opcode for add eax, imm32. Most original-8086 ALU instructions have a special AX,imm16 / EAX,imm32 short form, instead of the op r/m32, imm32 or imm8 form that uses a ModRM byte to encode the destination operand. (And the bits of the /r field in ModRM as extra opcode bits.)
See Tips for golfing in x86/x64 machine code for more about AL / EAX / RAX short form encodings, and one byte instructions.
For manually decoding x86 machine code, see Intel's manuals, especially the vol.2 manual which details the instruction encoding formats, and has an opcode table at the end. (See links in the x86 tag wiki). For just an opcode map, see http://ref.x86asm.net/coder64.html.
Use a disassembler or debugger to see what's in your executables
But really, use a disassembler like objdump -drwC -Mintel. Or llvm-objdump. Find main in the output, and look at what you get. (Or use GDB, because labels in the middle of an instruction throw off the disassembler.)
Use objdump -rwC -Mintel -D -j .rodata -j .text testc/test194 to get output like this, disassembling the .text and .rodata sections as code:
testc/test194: file format elf64-x86-64
Disassembly of section .text:
0000000000400540 <__libc_csu_init>:
400540: 41 57 push r15
400542: 49 89 d7 mov r15,rdx
...
4005a4: c3 ret
4005a5: 90 nop
4005a6: 66 2e 0f 1f 84 00 00 00 00 00 nop WORD PTR cs:[rax+rax*1+0x0]
00000000004005b0 <__libc_csu_fini>:
4005b0: c3 ret
Disassembly of section .rodata:
00000000004005c0 <_IO_stdin_used>: ;;;; This is actually data!
4005c0: 01 00 add DWORD PTR [rax],eax
4005c2: 02 00 add al,BYTE PTR [rax]
00000000004005c4 <main>:
4005c4: c2 00 00 ret 0x0
... ; objdump elided the last 0, not me. It literally put ...
(I modified your python script to add the -no-pie gcc option, which is why my disassembly has absolute addresses, instead of just small addresses relative to the start of the file = 0. I wondered if that might put main somewhere it could fall through, but it didn't.)
Notice there's only a small gap between .text and .rodata. They're part of the same ELF segment (in the ELF program headers that the OS's program loader looks at), so they're part of the same mapping, no unmapped pages between them. If we're lucky, the intervening bytes are even filled with 0x90 nop instead of 00. Actually, something filled the gap between __libc_csu_init and __libc_csu_fini with long NOPs. Maybe that was from the assembler if they were in the same source file.
main is of course in .rodata because you declared it in C as a read-only global (static storage), like const int main = 6;. I you used const int main __attribute__((section(".text"))) = 123, you could get main in the normal .text section. On my system, it ends up right before __libc_csu_init.
But labels interrupt disassembly; the disassembler thinks it must have been wrong and restarts decoding from the label. So in GDB on testc/test5 (with set disassembly-flavor intel and layout reg, then using the start command to stop at the start of main), I'll get
|0x40053c <main> add eax,0x41000000 │
│0x400541 <__libc_csu_init+1> push rdi │
│0x400542 <__libc_csu_init+2> mov r15,rdx
But from objdump -drwC -Mintel (disassembing only the .text section is the default for -d, and I used the GNU C attribute to put main there so my program could work the way yours does), I get:
000000000040053c <main>:
40053c: 05 00 00 00 ....
0000000000400540 <__libc_csu_init>:
400540: 41 57 push r15
400542: 49 89 d7 mov r15,rdx
Notice that the .... on the same line as the 05 00 00 00 indicates that decoding didn't get to the end of an instruction.
And since main isn't aligned by 16 here, it's right up against the start of __libc_csu_init. So the add eax, imm32 consumes the REX.W prefix (41) from push r15, making it decode as push rdi if reached by falling through from main instead of by a call to the __libc_csu_init label.
The above output was from Linux. Your OS X system would be different
OS X puts most of the CRT startup code in libc, not statically linked into the executable with main.
Or maybe there isn't anything for your main to fall through into
If there was, main=5 would have worked, but you say the first non-crashing result was with main=194, which is an actual ret.
If nothing before c3 ret or c2 00 00 ret 0 returned, then probably there's nothing to fall into after main, or the gap isn't padded with repeated 90 nop to form a "nop sled" that will execute ok if decoding starts anywhere in the middle of it. (e.g. after an earlier instruction consumes the trailing 0 bytes at the end of the dword int main, and some of the padding bytes.)
I understand that a segfault is invalid access to valid memory and a bus error is access to invalid memory
No, that simplified description is backwards. Usually you get a segfault for trying to access an unmapped page, on all Unixes. But you get a bus error for some kinds of invalid access (even on valid addresses).
Solaris on SPARC gives you a bus error for misaligned word loads/stores to valid memory.
On x86-64 Linux, you only get SIGBUS for really weird stuff. See Debugging SIGBUS on x86 Linux. Non-canonical stack pointer leading to a #SS exception, reading past the end of a mmaped file that was truncated. Also if you enable x86 alignment checking (AC flag), but nobody does that because library funcs like memcpy use unaligned loads/stores, and compiler code-gen assumes that unaligned integer loads/stores are safe.
IDK what hardware exceptions *BSD maps to SIGBUS, but I'd assume that regular out-of-bounds access, like NULL-pointer dereference, would SIGSEGV. That's pretty standard.
#MichaelPetch says in comments that on OS X
#PF (page fault hardware exception) from code-fetch cases the kernel to deliver SIGBUS
#PF from a data load/store to an unmapped page results in SIGSEGV.
#PF from a store to a read-only page results in SIGBUS. (And this is what's happening after 02 00 add al, [rax], in the 00 00 add [rax], al that forms the 2nd byte of main. The rest of this answer doesn't take this into account.)
(Of course this is after checking if the page-fault was due a difference between the hardware page table and the logical process memory map, e.g. from lazy mapping, copy-on-write, or pages paged out to disk.)
So if your int main is landing at the very end of an unmapped page, 05 add eax,imm32 would read one extra byte past the end of the dword holding int main (.long 5 in GAS syntax asm). That would go into the next page and SIGBUS. (Your last comment indicates it does SIGBUS.)
A theory for what's going on with the first few values:
You report:
a bus error for main = 02 00 add al, [rax] / `00 00 add [rax], al
but a segfault for main = 03 00 add eax, [rax] / 00 00 add [rax], al.
We know the low byte of RAX is 252, so if RAX holds a valid pointer value, it's 4-byte aligned. So if loading a byte from [rax] works, so does loading a dword.
So probably the memory-source add is succeeding, and modifying AL, the low byte of RAX (byte operand size) probably still leaving RAX a valid pointer.** Then if the rest of the page containing main is filled with 00 00 add [rax], al instructions (or just the one inside main itself), those will succeed (without further modifying RAX) until execution falls off into an unmapped page, as long as RAX is still a valid pointer after running whatever main decoded to.
Actually, the memory-destination add itself faults and raises SIGBUS.
03 00 add eax, [rax] writes EAX, and thus truncates RAX to 32-bit. (writing a 32-bit register implicitly zero-extends into the full 64-bit register, unlike writing low 8 or 16 partial registers.) This definitely gives you an invalid pointer, because OS X maps static code/data outside the low 32 bits of virtual address space.
So the following 00 00 add [rax], al will definitely fault from trying to write an out-of-bounds address, causing a #PF that raises SIGSEGV.
There's probably just the one 00 00 from the last two bytes of main before the end of a page. Otherwise 05 add eax, imm32 would segfault from truncating RAX and then running 00 00 add [rax], al. For it to SIGBUS, it must code-fetch into an unmapped page without decoding any memory-access instructions after that.
There are certainly other plausible explanations for what you're seeing, but I think this explains all your observations so far; without more data we can't disprove it. Obviously the easiest thing would be to fire up GDB or whatever other debugger and just start / si and watch what happens.

LOOP is done only one time when single stepping in Turbo Debugger

The code must output 'ccb',but output only 'c', LOOP is done only one time, i have calibrated in TD, but why LOOP is done only one time?
I THINK THAT I MUST TO DECREMENT STRING_LENGTH, SO I WROTE
DEC STRING_LENGTH
BUT IT NOT WORK, SO I WROTE LIKE THAT
MOV SP,STRING_LENGTH
DEC SP
MOV STRING_LENGTH,SP
I KNOW WHAT ARE YOU THINKING RIGHT NOW, THAT IS SO INCORRECT, YOU ARE RIGHT)))
I CAN USE C++, BUT I WANT TO DO IT ONLY IN ASSEMBLY,
DOSSEG
.MODEL SMALL
.STACK 200H
.DATA
STRING DB 'cScbd$'
STRING_LENGTH EQU $-STRING
STRING1 DB STRING_LENGTH DUP (?) , '$'
.CODE
MOV AX,#DATA
MOV DS,AX
XOR SI,SI
XOR DI,DI
MOV CX,STRING_LENGTH
S:
MOV BL,STRING[DI]
AND STRING[DI],01111100B
CMP STRING[DI],01100000B
JNE L1
MOV AL,BL
MOV STRING1[SI],AL
ADD SI,2
L1:
ADD DI,2
LOOP S
MOV DL,STRING1
MOV AH,9
INT 21H
MOV AH,4CH
INT 21H
END
In Turbo Debugger (TD.EXE) the F8 "F8 step" will execute the loop completely, until the cx becomes zero (you can even create infinite loop by updating cx back to some value, preventing it from reaching the 1 -> 0 step).
To get "single-step" out of the loop instruction, use the F7 "F7 trace" - that will cause the cx to go from 6 to 5, and the code pointer will follow the jump back on the start of the loop.
About some other issues of your code:
MOV SP,STRING_LENGTH
DEC SP
MOV STRING_LENGTH,SP
sp is not general purpose register, don't use it for calculation like this. Whenever some instruction does use stack implicitly (push, pop, call, ret, ...), the values are being written and read in memory area addressed by the ss:sp register pair, so by manipulating the sp value you are modifying the current "stack".
Also in 16 bit x86 real mode all the interrupts (keyboard, timer, ...), when they occur, the current state of flag register and code address is stored into stack, before giving the control to the interrupt handler code, which usually will push additional values to the stack, so whatever is in memory on addresses below current ss:sp is not safe in 16 bit x86 real mode, and the memory content keeps "randomly" changing there by all the interrupts being executed meanwhile (the TD.EXE itself does use part of this stack memory after every single step).
For arithmetic use other registers, not sp. Once you will know enough about "stack", you will understand what kind of sp manipulation is common and why (like sub sp,40 at beginning of function which needs additional "local" memory space), and how to restore stack back into expected state.
One more thing about that:
MOV SP,STRING_LENGTH
DEC SP
MOV STRING_LENGTH,SP
The STRING_LENGTH is defined by EQU, which makes it compile time constant, and only compile time. It's not "variable" (memory allocation), contrary to the things like someLabel dw 1345, which cause the assembler to emit two bytes with values 0100_0001B, 0000_0101B (when read as 16 bit word in little-endian way, that's value 1345 encoded), and the first byte address has symbolic name someLabel, which can be used in further instructions, like dec word ptr [someLabel] to decrement that value in memory from 1345 to 1344 during runtime.
But EQU is different, it assigns the symbol STRING_LENGTH final value, like 14.
So your code can be read as:
mov sp,14 ; makes almost sense, (practically destroys stack setup)
dec sp ; still valid
mov 14,sp ; doesn't make any sense, constant can't be destination for MOV

Patch an executable file

In short
What would be the easiest way to make sure that the high word of ecx contains 0 by replacing following instruction in the exe file?
004044be 0fbf4dfc movsx ecx,word ptr [ebp-4]
Instead of containing FFFF9298 after executing adress 004044be I'd like ecx to contain 00009298.
What have I tried
I have tried replacing movsx with a simple movby replacing the opcode 0fbf in the executable with 8b0c but that didn't work out as planned (using the debugger to verify the change, I'm sure it was at the the right place)
Some background
I have a rather old program that for one reason or another AV's when I try to print to my HP printer. Everything works fine when I print to CutePDF so the current workaround is to generate a PDF file and print the PDF.
Getting my feet wet with WinDbg I tried to find the reason of why this was happening.
While this is not the root cause of my problem, it seems that ecx at some point get's a negative value which is used to allocate memory, ultimately resulting in an exception.
I could try to find why a negative value is returned but during my debugging session, I noticed that zeroing out the high word in ecx did the job (aka printed the file).
So instead of containing FFFF9298 after executing adress 004044be I'd like ecx to contain 00009298.
004044ac 0fbf05e8025100 movsx eax,word ptr [Encore32!SystemsPerPageDlogProc+0x10e4a1 (005102e8)]
004044b3 05416f0000 add eax,6F41h
004044b8 668945fc mov word ptr [ebp-4],ax
004044bc 6a40 push 40h
004044be 0fbf4dfc movsx ecx,word ptr [ebp-4] --> replace with ?
004044c2 51 push ecx
004044c3 8b55f8 mov edx,dword ptr [ebp-8]
004044c6 52 push edx
Use movzx, it does exactly what you need.
The opcode (for 16->32 version) is 0F B7 /r so just patching BF to B7 should do it.
movsx mean "move with sign extend". That means that the top bit of src is copied to all high bits of dest. You don't want that.
movzx fills top bits with 0.
movzx ecx,word ptr [ebp-4] is what you need. Using 32-bit code as in your example it can be encoded as 0F B7 4D FC.

x86 assember - illegal opcode 0xff /7 under Windows

I'm currently developing an x86 disassembler, and I started disassembling a win32 PE file. Most of the disassembled code looks good, however there are some occurences of the illegal 0xff /7 opcode (/7 means reg=111, 0xff is the opcode group inc/dec/call/callf/jmp/jmpf/push/illegal with operand r/m 16/32). The first guess was, that /7 is the pop instruction, but it is encoded with 0x8f /0. I've checked this against the official Intel Architecture Software Developer’s Manual Volume 2: Instruction Set Reference - so I'm not just missleaded.
Example disassembly: (S0000O0040683a is a lable being jumped to by another instruction)
S0000O0040683a: inc edi ; 0000:0040683a ff c7
test dword ptr [eax+0xff],edi ; 0000:0040683c 85 78 ff
0xff/7 edi ; 0000:0040683f ff ff
BTW: gdb disassembles this equally (except the bug 0xff not yielding -1 in my disassembly):
(gdb) disassemble 0x0040683a 0x00406840
Dump of assembler code from 0x40683a to 0x406840:
0x0040683a: inc %edi
0x0040683c: test %edi,0xffffffff(%eax)
0x0040683f: (bad)
End of assembler dump.
So the question is: Is there any default handler in the illegal opcode exception handler of Windows, which implements any functionality in this illegal opcode, and if yes: What happends there?
Regards, Bodo
After many many additional hours getting my disassembler to produce the output in the exact same syntax than gdb does, I could diff over the two versions. This revealed a rather awkward bug in my disassember: I forgot to take into account, that the 0x0f 0x8x jump instruction have a TWO byte opcode (plus the rel16/32 operand). So each 0x0f 0x8x jump target was off by one leading to code which is not reachable in reality. After fixing this bug, no 0xff/7 opcodes are disassembled any longer.
Thanks go to everyone answering to my question (and commenting that answers as well) and thus at least trying to help me.
Visual Studio disassembles this to the following:
00417000 FF C7 inc edi
00417002 85 78 FF test dword ptr [eax-1],edi
00417005 ?? db ffh
00417006 FF 00 inc dword ptr [eax]
Obviously, a general protection fault happens at 00417002 because eax does not point to anything meaningful, but even if I nop it out (90 90 90) it throws an illegal opcode exception at 00417005 (it does not get handled by the kernel). I'm pretty sure that this is some sort of data and not executable code.
To answer your question, Windows will close the application with the exception code 0xC000001D STATUS_ILLEGAL_INSTRUCTION. The dialog will match the dialog used for any other application crashes, whether it offers a debugger or to send an error report.
Regarding the provided code, it would appear to have either been assembled incorrectly (encoding a greater than 8-bit displacement) or is actually data (as suggested by others already).
It looks like 0xFFFFFFFF has been inserted instead of 0xFF for the test instruction, probably in error?
85 = test r/m32, and 78 is the byte for parameters [eax+disp8], edi, with the disp8 to follow which should just be 0xFF (-1) but as a 32-bit signed integer this is 0xFFFFFFFF.
So I am assuming that you have 85 78 FF FF FF FF where it should be 85 B8 FF FF FF FF for a 32-bit displacement or 85 78 FF for the 8-bit displacement? If this is the case the next byte in the code should be 0xFF...
Of course, as suggested already, this could just be data, and don't forget that data can be stored in PE files and there is no strong guarantee of any particular structure. You can actually insert code or user defined data into some of the MZ or PE header fields if you are agressively optimising to decrease the .exe size.
EDIT: as per the comments below I'd also recommend using an executable where you already know exactly what the expected disassembled code should be.

Why does malloc overwrite RSP and RSP+8?

You can read about the 64-bit calling convention here. x64 functions are supposed to clean up after themselves however, when I call malloc from .asm, it overwrites the value at RSP and RSP+8. This seems very wrong. Any suggestions?
public TestMalloc
extern malloc : near
.CODE
align 8
TestMalloc proc
mov rcx, 100h
000000018000BDB8 48 C7 C1 00 01 00 00 mov rcx,100h
call malloc
000000018000BDBF E8 CC AC 06 00 call malloc (180076A90h)
ret
000000018000BDC4 C3 ret
000000018000BDC5 66 66 90 xchg ax,ax
TestMalloc endp
END
For the x64 calling convention, even if the parameters are passed in the registers the caller is required to save space for them on the stack:
Note that space is always allocated
for the register parameters, even if
the parameters themselves are never
homed to the stack; a callee is
guaranteed that space has been
allocated for all its parameters. Home
addresses are required for the
register arguments so a contiguous
area is available in case the called
function needs to take the address of
the argument list (va_list) or an
individual argument.
http://msdn.microsoft.com/en-us/library/ew5tede7.aspx
I'm not sure, truthfully, but have you tried stepping through the assembly in a debugger? If you follow the internal logic you might unearth some clues as to what is going on. I recommend WinDbg.

Resources