From: GAMMELJL AT SLU DOT EDU Date: Wed, 19 Aug 1998 09:08:57 -0500 (CDT) Subject: assembly language subroutines To: djgpp AT delorie DOT com Message-id: <01J0S6CR6YJM94G7O9@SLU.EDU> Organization: SAINT LOUIS UNIVERSITY St. Louis, MO MIME-version: 1.0 Content-type: text/plain Precedence: bulk The C++ compiler seems to have a slightly different programming style than george DOT foot AT merton DOT oxford DOT ac DOT uk. Here is how the gnu compiler programs a subroutine which has two arguments, both of which are arrays. The C++ version of sub is: sub(unsigned int *z1,unsigned int *z2) {i=666; //a line to mark beginning of code .C++ CODE return 0; //xorl %eax,%eax marks end of code } .globl _sub__FPUiT0 _sub__FPUiT0: pushl %ebp The first eight lines are straightforward movl %esp,%ebp but I do not relate them well to the subl $40,%esp lines after xorl %eax,%eax below. pushl %edi Will be used for origin of one of the arrays. pushl %esi Will be used for origin of the other array. pushl %ebx Will be used to number elements of the arrays. movl 8(%ebp),%edi Origin of z1 stored in edi. movl 12(%ebp),%esi Origin of z2 stored in esi. movl $666,_i Marks beginning of C++ code. .followed by lines of assembly language .easily recognizable as arising from CODE. . . The stack is addressed frequently using N(%ebp) .where N is a negative multiple of 4 (-40<=N<=-4) . .ebp is not changed during the program. .esp is not changed during the program. . xorl %eax,%eax Marks the end of the C++ code. leal -52(%ebp),%esp My question is: What is going on popl %ebx in these remaining lines? popl %esi I understand the 3 popl, but not popl %edi the "leal -52 etc." and the "leave" leave or why the order of the commands is ret what it is. Notice that there is no .align 2 popl %ebp. What does "leave" do? A simpler example has the following source code: sub2(int a,int b) {i1=666; //int i1 is a global variable return a+b;} For sub2 gnu compiler produces: .globl _zadd__FUiUi _zadd__FUiUi: pushl %ebp movl %esp,%ebp movl $666,_i1 Marks beginning of C++ code. movl 8(%ebp),%eax addl 12(%ebp),%eax Marks end of C++ code leave ret The gnu compiler does not restore esp (no reason to: it was never changed) or (unless leave does it) ebp. But if sub2 is used many times in the code so that ebp is pushed many times, isn't there a danger of stack overflow (or memory leak)? George Foot is always careful to popl %ebp at the end of the subroutine after restoring esp (if it has been changed with a subl $4,%esp as on page 4 of his notes,for instance) with movl %ebp,%esp. George Foot's programming style is straightforward. Why the difference in the two styles?