//---------------------------------------------------------------- // mywhoami.s // // This program illustrates the use of string-manipulation // instructions: (1) to search for an environment variable // and (2) to copy its value into a local buffer area from // which it can then be displayed. The algorithm which is // used here relies on the fact that Linux systems provide // for three arguments to the function 'main()': // // int main( int argc, char *argv[], char *envp[] ); // // Here the third argument 'envp' is a pointer to an array // of character pointers (known as the 'environment list') // in which each of the strings has the form 'name=value'. // Among these we search here for the one in which 'USER=' // appears: its value gives the current effective user id. // // programmer: ALLAN CRUSE // written on: 27 OCT 2003 //---------------------------------------------------------------- .section .data target: .ascii "USER=" # variable to search for tgtlen: .int . - target # length for target name user: .zero 80 # for storing a username size: .int 0 # for length of username fmt: .asciz "%s\n" # for 'printf()' format .section .text main: # setup local frame-pointer (to access 'envp' argument) pushl %ebp # preserve caller's frame movl %esp, %ebp # setup local stack frame # get 'envp' and search the list for the 'USER=' string movl 16(%ebp), %ebx # EBX points to the array xorl %edx, %edx # use EDX for array-index cld # do 'forward' processing nxvar: # check for end-of-array (i.e., a null string) movl (%ebx, %edx, 4), %edi # point EDI to next string cmpb $0, (%edi) # check: is a NULL string? je finis # yes, search unsuccessful # compare the string's variable-name to our target name movl $target, %esi # point ESI to our target movl tgtlen, %ecx # setup length for target rep cmpsb # check: do strings agree? je found # yes, search succeessful! # if they don't match, increment array-index and try again inc %edx # else advance array-index jmp nxvar # and examine new variable found: # determine the length of the environment variable's value movl %edi, %esi # save start-address in ESI xorb %al, %al # setup EAX with null value movl $0xC0000000, %ecx # address for top of memory subl %edi, %ecx # less address to scan from repne scasb # scan string for null byte movl %edi, size # ok, store the end address subl %esi, size # minus the begin address # now copy the variable's value to our local buffer movl $user, %edi # point EDI to local buffer movl size, %ecx # number of bytes to copy rep movsb # perform the string-copy # print the current effective user id pushl $user # printf argument #2 pushl $fmt # printf argument #1 call printf # call to runtime library addl $8, %esp # discard the arguments # restore caller stack-frame and exit finis: mov %ebp, %esp # insure stack is balanced popl %ebp # restore caller's frame ret # and return from 'main()' .globl main # make entry-point public