Page 1 of 1

variadic function and wrong stack address

Posted: Tue Dec 25, 2012 5:47 pm
by ever
hey,
i'm trying to implement a printf function.
here is some code :

Code: Select all

void printf(const char *s, ...)
{
	unsigned int ptr = (unsigned int)(&s);
	_asm
	{
		push eax
		mov eax, ptr
		XCHG BX, BX    // breakpoint here
		pop eax
	}
	va_list vl;
	va_start(vl, s);

	while (*s)
	{
		if(*s == '\n')
		{
			text_cursor += (160 - (((unsigned int)text_cursor - 0xB8000) % 160));
			s++;
			continue;
		}
		if (*s == '%')
		{
			if (*(s + 1) == '%')
				s++;
                       	else
			{
				if(*(s + 1) == 'i')
					printValue(va_arg(vl, int));
				else if(*(s + 1) == 's')
					printf(va_arg(vl, char*));

				s += 2;
				continue;
			}
		}
		*text_cursor++ = *s++;
   		*text_cursor++ = 0x07;
	}
}
what I get in eax on the breakpoint is 0x6ffec. Actually, the variable is located at 0x7ffec. The stack segment start at 0x10000 and the data segment start at 0. So why don't I get the true address of the stack? obviously the va_arg macro get me a wrong value then...

Thanks

Re: variadic function and wrong stack address

Posted: Tue Dec 25, 2012 6:44 pm
by Owen
ever wrote:... 0x6ffec ... located at 0x7ffec ... stack segment start at 0x10000 ... data segment start at 0 ...
Do some math. Understand your compiler (MSVC?), and particularly its understanding of segmentation

Re: variadic function and wrong stack address

Posted: Tue Dec 25, 2012 10:35 pm
by ever
i'm using ICC.
hmmm.... 0x6ffec + 0x10000 = 0x7ffec, i'm right? :P
the problem is, this :

Code: Select all

void func(int b)
{
int a = *(int*)&b;
}
should assign to a the value of b, it doesn't.
Here is the asm code I get :

Code: Select all

push    ebp
mov     ebp, esp
lea     eax, [ebp+arg_0]
mov     eax, [eax]
mov     [ebp+var_18], eax
What I see is that the compiler assumes SS = DS, strange... this code works on windows, so my conclusion is SS should always be equal to DS (at least on windows). Can someone confirm it?

Re: variadic function and wrong stack address

Posted: Wed Dec 26, 2012 2:20 am
by bluemoon
ever wrote:is SS should always be equal to DS (at least on windows). Can someone confirm it?
Windows uses flat model, so yes.
But talking about Microsoft I wouldn't sure anything be "always" in the future, they like to break compatibility :mrgreen:

Re: variadic function and wrong stack address

Posted: Wed Dec 26, 2012 5:10 am
by rdos
bluemoon wrote:
ever wrote:is SS should always be equal to DS (at least on windows). Can someone confirm it?
Windows uses flat model, so yes.
But talking about Microsoft I wouldn't sure anything be "always" in the future, they like to break compatibility :mrgreen:
Only if you use flat memory model. For 16-bit segmented, SS != DS in DLLs.