Showing posts with label Function. Show all posts
Showing posts with label Function. Show all posts

Tuesday, 21 July 2015

Concept of function in python !

In Python, functions provide organized blocks of reusable code. Typically, this allows a programmer to write a block of code to perform a single, related action. Functions are reusable pieces of programs. They allow you to give a name to a block of statements and you can run that block using that name anywhere in your program and any number of times. This is known as calling the function.

Function Definition: The def and return Statements:
Functions are defined using the def keyword.
We create a function with a def statement and The return statement specifies the result value of the function :
def odd( spin ):
    """Return true if this spin is odd."""
    if spin % 2 == 1:
         return True
    return False


Function Parameters
A function can take parameters which are just values you supply to the function so that the function can do something utilising
those values. These parameters are just like variables except that the values of these variables are defined when we call the
function and are not assigned values within the function itself.
Parameters are specified within the pair of parentheses in the function definition, separated by commas.

Keyword Arguments :
If you have some functions with many parameters and you want to specify only some of them, then you can give values for such
parameters by naming them - this is called keyword arguments

Using Keyword Arguments
#!/usr/bin/python

def func(a, b=5, c=10):
    print 'a is', a, 'and b is', b, 'and c is', c
func(3, 7)
func(25, c=24)
func(c=50, a=100)

Output :
>>> python func.py
a is 3 and b is 7 and c is 10
a is 25 and b is 5 and c is 24
a is 100 and b is 5 and c is 50


                                            



In the first usage, func(3, 7), the parameter a gets the value 3, the parameter b gets the value 5 and
c gets the default value of 10.
In the second usage func(25, c=24), the variable a gets the value of 25 due to the position of the
argument. Then, the parameter c gets the value of 24 due to naming i.e. keyword arguments. The variable
b gets the default value of 5.
In the third usage func(c=50, a=100), we use keyword arguments completely to specify the values.

Type conversion :
Python provides a collection of built-in functions that convert values from one type to another. The int function takes any value and converts it to an integer, if possible :
>>> int("32")
32
>>> int("Hello")
ValueError: invalid literal for int(): Hello


If you like this post or have any question, please feel free to comment!

Function call implementation in Assembly language !

Prerequisites:1.What is variable - variables for hackers : http://programmingethicalhackerway.blogspot.in/2015/07/what-is-variable-variables-for-hackers.html
2.Concept of function in C - Programmer section: http://programmingethicalhackerway.blogspot.in/2015/07/concept-of-function-in-c-programmer.html
3. Introduction to stack : http://programmingethicalhackerway.blogspot.in/2015/07/introduction-to-stack.html

A functions can be defined as :
It is the set of information that can be grouped into smaller sub-program called a function.
OR
It is set of instructions that performs a particular task and we need several times in our program so it can be grouped into a smaller subprogram called a function.

How Functions Work?
Functions are composed of several different pieces:
Function name:-A function’s name is a symbol that represents the address where the function’s code starts. In assembly language, the symbol is defined by typing the the function’s name as a label before the function’s code. This is just like labels you have used for jumping.

function parameters:When a function is invoked, you pass a value to the parameter. This value is referred to actual parameter or argument.For example, in mathematics, there is a sine function. If you were to ask a computer to find the sine of 2, sine would be the function’s name, and 2 would be the parameter.

local variables:Variables that are declared inside a function or block are called local variables. They can be used only by statements that are inside that function or block of code.It’s kind of like a scratch pad of paper. Functions get a new piece of paper every time they are activated, and they have to throw it away when they are finished processing.

static variables:According to Wikipedia, a static variable is a variable that has been allocated statically—whose lifetime or "extent" extends across the entire run of the program.Static variables are generally not used unless absolutely necessary, as they can cause problems later on.

Global variables :  If Variables are defined at the  beginning of the code i.e outside of any functions are called Global variables.
This variable can be read from and written to by any function, and the changes to it will  persist between functions.

return address:The return address is a parameter which tells the function where to resume executing after the function is completed. This is needed because functions can be called to do processing from many different parts of your program, and the function needs to be able to get back to wherever it was called from. In most programming languages, this parameter is passed automatically when the function is called. In assembly language, the call instruction handles passing the return address for you, and ret handles using
that address to return back to where you called the function from.

return value:The return value is the main method of transferring data back to the main program. Most programming languages only allow a single return value for a function.

Stack-based exploits are made possible by the call and ret instructions. When a function is called, the return address of the next instruction is pushed to the stack, beginning the stack frame. After the function is finished, the ret instruction pops the return address from the stack and jumps EIP back there. By overwriting the stored return address on the stack before the ret instruction, we can take control of a program’s execution.

A function call in assembly language simply requires pushing the arguments to the function onto the stack in reverse order, and issuing a call instruction. After calling, the arguments are then popped back off of the stack. After calling, the arguments are then popped back off of the stack.
For example,consider the C code:
sum("The sum is %d", 10);

This code can be translated into assembly language as such:
.section .data
    string:
        .ascii "The sum is %d\0"

.section .text
    pushl $10
    pushl $string
    call printf
    popl %eax
   

C Calling Conventions: The way that the variables are stored and the parameters and return values are transferred by the computer varies from language to language as well. This variance is known as a language’s calling convention, because it describes how functions expect to get and receive data when they are called.

You cannot write assembly-language functions without understanding how the computer’s  stack works. Each computer program that runs uses a region of memory called the stack to enable functions to  work properly.

                                                       
            


In previous Section we saw a simple example of a subroutine( sum(); ) defined in x86 assembly language.In practice, such simple function definitions are rarely useful. When more complex subroutines are combined in a single program, a number of complicating issues arise.For example, how are parameters passed to a subroutine? Can subroutines overwrite the values in a register, or does the caller expect the register contents to be preserved? Where should local variables in a subroutine be stored? How should results be returned from functions?
To allow separate programmers to share code and develop libraries for use by many programs, and to simplify the use of subroutines in general, programmers typically adopt a common calling convention.


The C calling convention is based heavily on the use of the hardware-supported stack. It is based on the push, pop, call, and ret instructions. Subroutine parameters are passed on the stack. Registers are saved on the stack, and local variables used by subroutines are placed in memory on the stack. The vast majority of high-level procedural languages implemented on most processors have used similar calling conventions.
The calling convention is broken into two sets of rules. The first set of rules is employed by the caller of the subroutine, and the second set of rules is observed by the writer of the subroutine (the “callee”).

The Caller’s Rules :
1. Before calling a subroutine, the caller should save the contents of certain registers that are designated
caller-saved. The caller-saved registers are EBX, ECX, EDX. If you want the contents of these registers to be preserved across the subroutine call, push them onto the stack.
2. To pass parameters to the subroutine, push them onto the stack before the call. The parameters
should be pushed in inverted order (i.e. last parameter first)—since the stack grows down, the first parameter will be stored at the lowest address (this inversion of parameters was historically used to allow functions to be passed a variable number of parameters).
3. To call the subroutine, use the call instruction. This instruction places the return address on
top of the parameters on the stack, and branches to the subroutine code.
4. After the subroutine returns, (i.e. immediately following the call instruction) the caller must remove the parameters from stack. This restores the stack to its state before the call was performed.
5. The caller can expect to find the return value of the subroutine in the register EAX.
6. The caller restores the contents of caller-saved registers (EBX, ECX, EDX) by popping them
off of the stack. The caller can assume that no other registers were modified by the subroutine

The Callee’s Rules:
1.At the beginning of the subroutine, the function should push the value of EBP onto the stack, and then copy the value of ESP into EBP using the following instructions:
push ebp
mov esp, ebp
The reason for this initial action is the maintenance of the base pointer, EBP. The base pointer is used by convention as a point of reference for finding parameters and local variables on the stack. Essentially, when any subroutine is executing, the base pointer is a “snapshot” of the stack pointer value from when the subroutine started executing. Parameters and local variables  will always be located at known, constant offsets away from the base pointer value. We push the old base pointer value at the beginning of the subroutine so that we can later restore the appropriate base pointer value for the caller when the subroutine returns. Remember, the caller isn’t expecting the subroutine to change the value of the base pointer. We then move the stack pointer into EBP to obtain our point of reference for accessing parameters and local variables.
2.Next, allocate local variables by making space on the stack.For example, if 3 local integers (4 bytes each) were required, the stack pointer would need to be decremented by 12 to make space for these local variables. I.e:
    sub 12, esp
3. Next, the values of any registers that are designated callee-saved that will be used by the func-
tion must be saved. To save registers, push them onto the stack. The callee-saved registers are
EDI and ESI (ESP and EBP will also be preserved by the call convention, but need not be
pushed on the stack during this step).
4. When the function is done, the return value for the function should be placed in EAX if it is
not already there.
5. The function must restore the old values of any callee-saved registers (EDI and ESI) that were
modified. The register contents are restored by popping them from the stack. Note, the registers
should be popped in the inverse order that they were pushed.
6. Next, we deallocate local variables. The obvious way to do this might be to add the appropriate
value to the stack pointer (since the space was allocated by subtracting the needed amount from the stack
pointer).In practice,
mov ebp, esp
This trick works because the base pointer always contains the value that the stack pointer contained
immediately prior to the allocation of the local variables.
7. Immediately before returning, we must restore the caller’s base pointer value by popping EBP off the stack. Remember, the first thing we did on entry to the subroutine was to push the base pointer to save its old value.
8. Finally, we return to the caller by executing a ret instruction. This instruction will find and remove the appropriate return address from the stack.

The first half of the rules apply to the beginning of the function, and are therefor commonly said to define the prologue to the function. The latter half of the rules apply to the end of the function, and are thus commonly said to define the epilogue of the function.

Call Convention Example : The Call Convention Example is here in detail: Concept of function in C - Hacker section: http://programmingethicalhackerway.blogspot.in/2015/07/concept-of-function-in-c-hacker-section.html
A good way to visualize the operation of the calling convention is to draw the contents of the nearby region of the stack during subroutine execution.

If you like this post or have any question, please feel free to comment!

Introduction to stack !

For assembly language programmer and exploit writer it is important to understand the concept of stack.
What is the stack ?
A Compiled program’s memory is divided into five segments: text, data, bss, heap, and stack. We will concentrate on the stack region, but first a small overview of the other regions is in order.The text segment is also sometimes called the code segment. This is where the assembled machine language instructions of the program are located.The data and bss segments are used to store global and static program variables. The data segment is filled with the initialized global and static variables, while the bss segment is filled with their uninitialized counterparts.The heap segment is a segment of memory a programmer can directly control. Blocks of memory in this segment can be allocated and used for whatever the programmer might need.

                                         



A stack is a storage device that stores information in such a manner that the item stored last is the first item received i.e. stack is a LIFO (Last Input First Output). The stack is a mechanism that computers use both to pass arguments to functions and to reference local function variables. Its purpose is to give programmers an easy way to access local data in a specific function and to pass information from the function’s caller. The stack acts like a buffer, holding all the information that the function needs.The stack is created at the beginning of a function and released at the end of it. Stacks are typically static, meaning that once they are set up in the beginning of a function, they really do not change; the data held in the stack may change, but the stack itself typically does not.

                                                     
                                   
                                                      


Why Do We Use Stack?
The stack’s primary purpose is to make the use of functions more efficient. From a low-level perspective, a function alters the flow of control of a program, so that an instruction or group of instructions can be executed independently from the rest of the program. More important, when a function has completed executing its instructions, it returns control to the original function caller. This concept of functions is most efficiently implemented with the use of the stack.
The stack is also used to hold function arguments and dynamically allocate space for local variables and to return values from the function.

Stack Operations : Several operations are defined on stacks.  Two of the most important are PUSH and POP.Data is placed onto the stack using the PUSH instruction; it is removed from the stack using the POP instruction. These instructions are highly optimized and efficient at moving data onto and off of the stack.

The ESP stack pointer points to the top of stack. Stack-specific instructions, PUSH and POP, use ESP to know where the stack is in memory.

Stacks on Intel x86 processors are considered to be inverted. This means that stacks grow downward. When an item is pushed “onto” the stack, ESP is decreased and the new element is written in the resulting location. When an item is popped from the stack, an element is read from the location to which ESP points and ESP is increased, moving toward the upper boundary and shrinking the stack.Thus, when we say an element is placed on top of the stack, it actually is written to the memory below all previous stack entries.

In other words, Every time we push something onto the stack with push, %esp gets subtracted by 4 so that it points to the new top of the stack (remember, each word is four bytes long, and the stack grows downward). If we want to remove something from the stack, we simply use the pop instruction, which adds 4 to %esp and puts the previous top value in whatever register you specified.

Let's understand the stack operation. Suppose at initial state, there are some variables A, B, C stored onto the stack. So the initial state of Stack look like this :

                                                 



Now we want to add a variable D onto the stack.To insert variable, We use the following command:
push D
After pushing D, stack look like this:

                                                    

                       


We we will remove the variable D from the stack. To remove variable,We use the following command:
pop D
After poping D, stack look like this :

                                                

                               

Another relevant register to the stack is EBP. The EBP register is usually used  to calculate an address relative to another address, sometimes called a frame pointer. Although it can be used as a general-purpose register, EBP has historically been used for working with the stack. For example, the following instruction
makes use of EBP as an index:
mov eax,[ebp+10h]
This instruction will move a dword from 16 bytes (10 in hex) down the stack into EAX.

Most compilers insert what is known as a prologue at the beginning of a function. In the prologue, the stack is set up for use by the function.This process often involves saving the EBP and setting EBP to point to the current stack pointer. This is done so that the EBP then contains a pointer to the top of our stack.The EBP register is then used to reference stack-based variables using offsets from the EBP.

To understand how the stack works in the real world, we need some understanding of the Intel CALL
and RET instructions.The CALL instruction makes functions possible. The purpose of this instruction is to divert processor control to a different part of code while remembering where you need to return.To achieve this goal, a CALL instruction operates like this:
1. Push address of the next instruction after the call onto the stack. (This is where the processor will return to after executing the function.)
2. Jump to the address specified by the call.

The RET instruction does the opposite. Its purpose is to return from a called function to whatever was right after the CALL instruction.The RET instruction operates like this:
1. Pop the stored return address off the stack.
2. Jump to the address popped off the stack.
This combination allows code to be jumped to and returned from very easily, without restricting the nesting of function calls too much.

For more detail :
http://programmingethicalhackerway.blogspot.in/2015/07/concept-of-function-in-c-hacker-section.html

If you like this post or have any question, please feel free to comment!

Monday, 20 July 2015

Concept of function in C - Hacker section!

In previous tutorial, Concept of function in C - Programmer section we have discussed the concept of function in C. For programmer that was enough but for hacker,this is not end! A programmer is one who only concerned with source code.A hacker is someone who is curious about how something(like computer) works.A hacker realizes that the compiled program is what actually gets executed out in the real world.This is the reason hackers have yet to learn.How function works in high level language C, we have discussed so far. Now we will see what is happening behind the scenes. I mean how function calls are represented in memory.

prerequisite : Concept of function in C - Programmer section!
                     Basic Assembly Programming Survival Skills for Hackers!
                     Essential GDB debugger skills for hacker to analyze the code !

There are two major syntax-es for x86 assembly: Intel and AT&T. AT&T syntax is used by Linux and The Intel syntax is used by many windows assemblers and debuggers. The two formats yield exactly the same machine language; however, there are a few differences in style and format:
Intel syntex:
mov dest, source ; copies data from the source to the destination
mov ebp,esp ; copies data from source "esp" register to the destination "ebp" register
AT&T syntex :
mov source, dest; copies data from the source to the destination
mov esp,ebp ; copies data from source "esp" register to the destination "ebp" register

AT&T format uses a % before registers while Intel does not. AT&T format uses a $ before literal values while Intel does not.
All the code in this post was compiled on an x86(Debian) Kali-Linux 1.1 using gcc 4.7 compiler.

In assembly the functions are mostly called by an instruction ‘CALL address’ the address is the place where the function code lies.Every function has an identical prologue(The starting of function code) and epilogue ( The ending of a function).

Prologue: The structure of Prologue is look like:
push  ebp
mov   esp,ebp

Epilogue: The structure of Prologue is look like:
leave 
ret

Now let's write a program which simply add two numbers:
#include<stdio.h>
#include<stdlib.h>

int sum(int a);
int main()
{ 
    int x, y;   
    x = 10;
    y = sum(x);   
    printf("The sum is: %d", y);
}

int sum(int a)
{
    int b=3,c; 
    c= b+a;
    return c;
}

Now Compile and load the program in the gdb :
root@Kali:~# gcc -g sum.c
root@Kali:~# gdb - ./a.out

We now disassemble the binary using gdb. Two registers are mentioned here: EBP points to the current frame (frame pointer), and ESP points to the top of the stack and updated every time. More detail here: basic-assembly-programming-survival-skills-for-hackers.
First, Let's disassemble the main function:
(gdb) disas main
Dump of assembler code for function main:
   0x0804841c <+0>:    push   %ebp
   0x0804841d <+1>:    mov    %esp,%ebp
   0x0804841f <+3>:    and    $0xfffffff0,%esp
   0x08048422 <+6>:    sub    $0x20,%esp
   0x08048425 <+9>:    movl   $0xa,0x1c(%esp)
   0x0804842d <+17>:    mov    0x1c(%esp),%eax
   0x08048431 <+21>:    mov    %eax,(%esp)
   0x08048434 <+24>:    call   0x8048453 <sum>
   0x08048439 <+29>:    mov    %eax,0x18(%esp)
   0x0804843d <+33>:    mov    0x18(%esp),%eax
   0x08048441 <+37>:    mov    %eax,0x4(%esp)
   0x08048445 <+41>:    movl   $0x8048500,(%esp)
   0x0804844c <+48>:    call   0x8048300 <printf@plt>
   0x08048451 <+53>:    leave 
   0x08048452 <+54>:    ret   
End of assembler dump.

Now, disassemble the sum function:
(gdb) disas sum
Dump of assembler code for function sum:
   0x08048453 <+0>:    push   %ebp
   0x08048454 <+1>:    mov    %esp,%ebp
   0x08048456 <+3>:    sub    $0x10,%esp
   0x08048459 <+6>:    movl   $0x3,-0x4(%ebp)
   0x08048460 <+13>:    mov    0x8(%ebp),%eax
   0x08048463 <+16>:    mov    -0x4(%ebp),%edx
   0x08048466 <+19>:    add    %edx,%eax
   0x08048468 <+21>:    mov    %eax,-0x8(%ebp)
   0x0804846b <+24>:    mov    -0x8(%ebp),%eax
   0x0804846e <+27>:    leave 
   0x0804846f <+28>:    ret   
End of assembler dump.

                                        


So, let’s look at what’s going on. The stack section is used to keep track of function calls (recursively) and grows from the higher addressed memory to the lower-addressed memory on most systems.Local variables exist in the stack section.

                                             


Now let’s look at main function assembler code.The first two lines are the function prologue :

0x0804841c <+0>:    push   %ebp
0x0804841d <+1>:    mov    %esp,%ebp

The Next two lines are also the part of function prologue :
 0x0804841c <+0>:    push   %ebp
 0x0804841d <+1>:    mov    %esp,%ebp
 0x0804841f <+3>:    and    $0xfffffff0,%esp
 0x08048422 <+6>:    sub    $0x20,%esp
But First two lines of function prologue are common in all types of system including windows and Linux. The first four lines are common only on Linux based system.

The first instruction :
push   %ebp
pushes old value of EBP, the base pointer, onto the stack and esp is updated. For the sake of simplicity, let's assume the starting address of stack is 0x1000

                                      


The second instruction :
mov    %esp,%ebp
copies current vale of esp into the ebp. This means ebp is now point to top of the stack.

                                            


The third instruction :
and    $0xfffffff0,%esp
aligns the stack to a 32-byte boundary and forces the last 4 bits of esp to 0:

                                                           


And Finally, the program allocates 32 bytes of stack (local) storage.

The fourth instruction :
 0x08048422 <+6>:    sub    $0x20,%esp
allocates 32(0x20 = 32 in decimal) bytes of space on the stack. Remember that the stack grows towards lower memory addresses so allocations will use ‘sub’ which actually means that  add 32 bytes of space on the stack.At this point, the program can be sure there are 32 bytes of 32-byte aligned memory being pointed to by esp.
                                                         

The fifth instruction:
0x08048425 <+9>:    movl   $0xa,0x1c(%esp)
moves the our variable 10 (10 is 0xa in hexa) into the location pointed by esp+28 bytes.The meaning of 0x1c(%esp) in simple words is 1c+esp i.e 28+esp(0x1c in hexa = 28 in decimal). So actual meaning of esp+28 bytes is to subtract 28 bytes from where esp is currently points.
                                               


The next instruction:
0x0804842d <+17>:    mov    0x1c(%esp),%eax
copy the data(i.e. 10 which is our variable value) from the location pointed by esp+28 bytes to the eax register.

                                   


The next instruction:
0x08048431 <+21>:    mov    %eax,(%esp)
moves the eax(which contain value 10) into the location pointed by esp currently.

                                         


The next instruction:
0x08048434 <+24>:     call   0x8048453 <sum>
simply calls the sum function.As soon as we call any function, the return address is saved onto the stack.

                                               


Every hackers, exploit writer have crush on this return address.As i have already discussed, Before the processor jumps on to the function code (sum function here), the address of next instruction to the call instruction is saved on the stack as return address, which will be loaded in EIP at when the called function(i.e. sum) finishes its job.In buffer overflow attacks this situation is exploited to control the execution of the processor by overwriting the saved return address. We will discus this attack technique in detail later tutorials.

Let's go back to the code, now we will look assembler code for function sum.
The first two instructions are same as in main function.
0x08048453 <+0>:    push   %ebp
0x08048454 <+1>:    mov    %esp,%ebp

                                       

The next instruction :
0x08048456 <+3>:    sub    $0x10,%esp
allocates 16 (0x10 in hexa =16 in decimal) bytes of space on the stack.

                                                


The next instruction:
0x08048459 <+6>:    movl   $0x3,-0x4(%ebp)
mov 3(our local variable value of sum function) into the location pointed by ebp-4 (-0x4(%ebp) = ebp-4) bytes. Don't get confused with esp and ebp here. we move -4 byte from ebp not esp.So , ebp-4 means 4 bytes towards down.

                                                   


The next instruction:
0x08048460 <+13>:    mov    0x8(%ebp),%eax
moves the data from the location pointed by ebp+8(ebp+8 contains eax register with value 10) into eax register.So ,ebp+8 means 8 bytes towards up.

The next instruction:
0x08048463 <+16>:    mov    -0x4(%ebp),%edx
moves the data from the location pointed by ebp-4(ebp-4 contains value 3) into edx register.



The next instruction:
 0x08048466 <+19>:    add    %edx,%eax
simply add the edx(i.e. 3) and eax(i.e. 10) and stores the results in eax register.

The next instruction:
0x08048468 <+21>:    mov    %eax,-0x8(%ebp)
moves the value from eax(i.e. 13) to the top of stack i.e. location in memory where ebp-8 points to.

                                               


The next instruction:
0x0804846b <+24>:    mov    -0x8(%ebp),%eax
moves the data from the location pointed by ebp-8(ebp-8 contain 13) into eax register.

                                         


The next instructions:
0x0804846e <+27>:    leave 
0x0804846f <+28>:    ret   
leave command moves the Base Pointer in to the Stack Pointer, then “pops” the old Base Pointer from the stack. The next command, ‘ret’ pops the return address from the stack and loads it into EIP. That causes execution to return to
where we left main function above.

                                   


Now sum function transfers the execution control back to the main. So let's go back to where we left in main.
In the main function , After the instruction:
0x08048434 <+24>:    call   0x8048453 <sum>

The next instruction is :
 0x08048439 <+29>:    mov    %eax,0x18(%esp)
moves the value of eax(i.e. 13) onto the location pointed by esp+24( 18 bytes upward side) .

                                        


The next instruction is :
0x0804843d <+33>:    mov    0x18(%esp),%eax
stores that value in the EAX register from  location pointed by esp+24.

The next instruction is :
0x08048441 <+37>:    mov    %eax,0x4(%esp)
moves the values(i.e. 13) from eax register to location pointed by esp+4.

                                     


The next instruction is :
0x08048445 <+41>:    movl   $0x8048500,(%esp)
moves the data at 0x8048500 to the esp. let's check what is there at 0x8048500:
(gdb) x/1s 0x8048500
0x8048500:     "The sum is: %d"
(gdb)
As expected, this is string "The sum is:"

                                             

The next instruction is :
0x0804844c <+48>:    call   0x8048300 <printf@plt>
simply call printf  function And the rest two lines are self explanatory and thus we get our result 13.In high level language C, it is very easy to add two numbers but in assembly, it is equally difficult. Again, A programmer is one who only concerned with source code. But A hacker realizes that the compiled program is what actually gets executed out in the real world.This is the first step towards  the understanding and exploiting buffer_overflow vulnerabilities.

I have tried to KISS(Keep It Simple Stupid). if you like this post or have any question, please feel free to comment !

Concept of function in C - Programmer section!

A functions can be defined as :
It is the set of information that can be grouped into smaller sub-program called a function.
OR
It is set of instructions that performs a particular task and we need several times in our program so it can be grouped into a smaller subprogram called a function.

Function is very important concept from hacker's perspective as well as programmers. Before the processor jumps on to the function call, the address of next instruction to the call instruction is saved on the stack as return address, which will be loaded in EIP register at when  the called function finishes its job. Remember the ret instruction will make the processor to land on an address saved in place of saved return address. In buffer overflow attacks this situation is exploited to control the execution  of the processor by overwriting the saved return address.

First let's start  understand the concept of function from programmers perspective.

Here are some examples of functions:
int sum(int a, int b)
 {
    int answer = 0;   
    answer = a + b;  
    return answer
 }
The first line is called Function header. In this line, sum is our function and return value type is int.
In the second line, the body of function starts with { and ends with  }  in the sixth line .
In the third line, answer is variable, that holds the result which will be returned by the function.
The forth line calculates the sum.
And finally the fifth line will return the answer.

The function declaration  to be used in program is as follows:
return_type function_name (parameter_declarations)
{
    declarations
    statements
}

where return_type and parameter_declarations are optional.

Return Type: A function may return a value. The return_type is the data type of the value the function returns. If the return_type have returned no value, use the keyword void.

parameter_declarations :When a function is invoked, you pass a value to the parameter. This value is referred to actual parameter or argument.

Function Prototype : It is a declaration of the function that tells the program about the type of the value returned by function and type of each argument.

General form of Function Prototype :
 return_type function_name(type variable1, type variable2, ...., type variableN);

A prototype can be recognized by the ; right after the arguments. It tells the compiler that there is a function called argument defined somewhere else in our code.In larger compilations, the function prototypes are put in header files. Header files have an .h extension.

Difference between function prototype and function definition:
The difference between function prototype and function definition is that function prototype has no body and terminating by semicolon.
Function prototype :
int sum(int n1, int n2);

Function definition:
int sum(int a, int b)
{
    int s;
    sum = a+b;
    return sum;
}

main() Function:
int main();
Main is a function like any other.The main() function is the starting point for all  of the codes in your program. When the window runs program in C, it passes control of the PC over to that program. Operating system needs to know where inside your program the control needs to be passed. In the case of a C language program, it's the main() function that the operating system is looking for.So It is the function called by the Operating System when your code is executed.

                                             




Basically The function main() can be defined with any of the following forms:
int main (void)
int main ( )
int main(int argc, char *argv[])
int main (int argc, char ** argv)

But All C programs contain a main() structure that follows this format:
return_value_type main(optional argument)
{
    body_of_main;
}
where both the return value type and arguments are optional. If you use command-line arguments for main(), use the format:
return_value_type main(int argc, char * argv[])
where the argc integer holds the number of arguments and the argv array holds the input arguments (strings).

Called and Calling function :
int main()
{
    int x =3, y=4,z;
    z = sum(x,y);
    printf("The sum is : %d", z);
}
int sum(int a, int b)
{
    int c;
    c = a+b;
    return c;
}
Here main is called function and sum is calling function .


Returning from a Function:
The return statement is the mechanism for returning a value from the function. Generally, a return statement is used to terminate a function weather or not it returns a value.

The return statement :
The return statement is useful in two ways. First, an immediate exit from the function is caused as soon as a return statement is encountered. second use of return statement is that it is used to return a value to the calling function.

return expression ;
OR
return value;
The expression will converted to the return type of function if necessary.Parentheses are often used around the expression, but they are optional.
The calling function is free to ignore the returned value. Furthermore, if there is no expression after expression, no value is returned to the caller function.In any case, if a function fails to return a value, its 'value' is certain to be garbage. All function except those of type void, return a value.If in a function, a return statement is missing, then the return value of the function technically undefined. Only the function declared as void do not return a value and hence can not be used in expression.

Function Arguments:
Two most important ways of passing arguments to a functions are : call by value and call by reference.
Call  by value:The call by value method copies the values of actual parameters into formal parameters, that is, the function creates its own copy of arguments values and then use them.
Call by reference : When a function is called by reference, the formal parameter become reference to the actual parameter in the calling function. This means that in call by reference, the called function does not create its own copy of original values, rather, it refers to the original vales.

Important Note: In C,There is no call by reference in C. You use pointers to emulate that, but pointers are passed by value.
For more detail on call by reference and call by value, Google.

I think for programmer, This is enough. But for hackers, this does not end. Hackers are still proceed. In the next tutorial i will consider how function calls are represented in memory and show the stack organization when functions are called.This is important concept to a hacker. By understanding how function calls are represented in memory, You will be able to understand buffer-overflow concept and how to exploit it.

If you like this post or have any question, please feel free to comment !

Blogger Widget