Assembly Language for Beginners

(nextflipdebug2) #1

1.20. ARRAYS


; .data:off_140011000
aFebruary_1 db 'February',0 ; DATA XREF: .data:0000000140011008
align 4
aMarch_1 db 'March',0 ; DATA XREF: .data:0000000140011010


And this is 0x797261756E614A.


Soon after, some other function (presumably, one that processes strings) may try to read bytes at this
address, expecting a C-string there.


Most likely it is about to crash, because this value doesn’t look like a valid address.


Array overflow protection


If something can go wrong, it will

Murphy’s Law

It’s a bit naïve to expect that every programmer who use your function or library will never pass an
argument larger than 11.


There exists the philosophy that says “fail early and fail loudly” or “fail-fast”, which teaches to report
problems as early as possible and halt.


One such method in C/C++ is assertions.


We can modify our program to fail if an incorrect value is passed:


Listing 1.241: assert() added

const char* get_month1_checked (int month)
{
assert (month<12);
return month1[month];
};


The assertion macro checks for valid values at every function start and fails if the expression is false.


Listing 1.242: Optimizing MSVC 2013 x64

$SG3143 DB 'm', 00H, 'o', 00H, 'n', 00H, 't', 00H, 'h', 00H, '.', 00H
DB 'c', 00H, 00H, 00H
$SG3144 DB 'm', 00H, 'o', 00H, 'n', 00H, 't', 00H, 'h', 00H, '<', 00H
DB '1', 00H, '2', 00H, 00H, 00H


month$ = 48
get_month1_checked PROC
$LN5:
push rbx
sub rsp, 32
movsxd rbx, ecx
cmp ebx, 12
jl SHORT $LN3@get_month1
lea rdx, OFFSET FLAT:$SG3143
lea rcx, OFFSET FLAT:$SG3144
mov r8d, 29
call _wassert
$LN3@get_month1:
lea rcx, OFFSET FLAT:month1
mov rax, QWORD PTR [rcx+rbx*8]
add rsp, 32
pop rbx
ret 0
get_month1_checked ENDP


In fact, assert() is not a function, but macro. It checks for a condition, then passes also the line number
and file name to another function which reports this information to the user.


Here we see that both file name and condition are encoded in UTF-16. The line number is also passed
(it’s 29).

Free download pdf