What is process?

Running instance of program. All processes are decedents of swapper process(PID=0). Both(threads, processes) are independent sequence of operations

fork() = Create child process

Memory Layout of a Process

Java Process

C++ Process

After compilation obj file is created ELF(Executable and linking format) format. This ELF file has (.text=CS, .data & .rodata = DS and others) This file is loaded in memory which creates Memory layout of the process.
Memory layout of a process
Segment Details
Code/Text Segment (Read Only) Size = 8k
(RO) Have Executable Instructions. Neither grows nor shrinks.
When a process is run twice OS maintains 1 set of pages kept in main memory. Both processes points to same memory (ie does not have personal CS)
Data Segment {Global, Static}
Stores global, Static variables
Part desc
Initialized DS
Initialized by Coder. Again its divided into 2 parts
RO(READ ONLY)
Global constants are stored here. Eg: const char *a = "test"
RW(READ WRITE)
Stores Initialized globals, extern variables, local static

char s[] = "test";  //Initialized Globals
int a = 1;        
static int b = 1;

extern int a;     //Extern variable

static int a;     //Local static
                                                
Unintialized DS / BSS(Block Started by Symbol)
Stores uninitialized global and static. Data is Initialized to 0(by kernel) before code start executing.

int a;
static int b;
                    
Pointer-to-Heap
Data Segment also stored pointer to heap.

malloc()->brk()
realloc()->sbrk()
                                    
Stack Segment
Stores: Local variables, Registers, Stack Frame pointer, return address, stack-based parameters, stack frame as LL

Stack Frame: {Input_parameters} {Return_address} {Local_variables}

address: The address to which control should return after the function call completes.

add(int a, int b){          //0x33
    int c;               //Local
}
main(int argc, char *argv[]){   //0x22
    int a ,b;
    add(a,b);
}   
From OS:Call to main()      //0x11

--------stack allocated in this direction---->
[ argv[] argc | 0x11 | b a ]  [ | b a | 0x22+offset | c | ]     //Input parameters are pushed in reverse order
/\<--- sf of main()  ----->  <------ sf of add()     ---->/\
|                                                         |
|                                                         rsp Stack pointer(Points to the top of the stack)
|
rbp Base pointer(Points to the base of the current stack frame. Remains fixed)
                        
Popping of Stack frame
Function add() finishes, Instruction pointer(is set to prev address)=0x22+offset
Then add() stack is cleared, Similarly main() stack is cleared
rsp, rbp are set to old values

Stack Overflow

When process uses all its stack. At end of process's stack there is a GUARD PAGE, when process goes into it.

fun() {
    fun();
}
                        

Stack Samshing

Stack overflow caused deliberately as part of an attack.

MAX Stack Size / Maximum stack allocated to process at start


8 MB(Default)  #cat /proc/pid/limits     //Linux
1 MB(Default)                            //Windows

$ ulimit -u unlimited                    //Changing stack size
                        
Why 8MB of stack? Atleast large and difficult to overflow
Why Stack size != Virtual Memory size (As Heap size = Virtual Memory size)?
  Every thread has its own Stack.if thread-1 consumes all and nothing left for thread-2.

Segmentation Fault

Program tries to access memory that it's not allowed to access (memory violation)
eg: null pointer (a pointer that doesn't point to any valid memory location), Accessing memory beyond bounds a[5]. access a[5]
Heap
Heap is not part of process Memory layout, but process stores pointer to its heap area
Heap is allocated on Virtual Memory/hard Disk & is used for dynamic Memory allocation.
Max Heap Size = Virtual memory size.

Heap Overflow / Memory leak

When process keeps on allocating more and more memory without freeing it causes Heap overflow.
Aftermaths: System shutdown, Crash, System becoming dead-slow.

while(1){ 
    char *p = (char *) malloc(12); 
}                            
                        

Process States

When a process executes, it passes through different states.
a. Start: Initial state when a process is first started/created.
b. Ready: The process is waiting to be assigned to a processor.
c. Running(Flag R): Once the process has been assigned to a processor by the OS scheduler state changes to running.
d. Waiting/Sleeping(Flag S): Process moves into the waiting state if it needs to wait for a resource, eg: waiting for user input or file.
e. Terminated or Exit: Once the process finishes its execution, or it is terminated by the OS. Here it waits to be removed from main memory.

Process Table & Process Control Block

Process Table

Process Table is Array of structures (called Process Control Blocks), one entry per process.

Process or Thread Control Block (struct task_struct)

What is PCB/TCB? struct task_struct containing all information about the process's state example:
- Execution Context: Registers, Program Counter (Store address from where to start again), Stack Pointer (SP).
- State: Running, Sleeping, Zombie, etc.
- Wait Queues: When a thread blocks on a mutex, socket, or condition variable, the kernel places a node (wait_queue_entry_t)
- Process's accounting and scheduling information
PCB Objective? To restart process from state where it left off, as it had never stopped. Process state which is interrupted using Interrupt is also saved on process table for later resumption. (due to context switch or interrupt)
struct task_struct When we create a process using fork() or a thread using pthread_create(), the kernel allocates a task_struct. Linux uses task_struct for both processes and threads

Process Table PCB/TCB (Process/Thread Control Block)

struct task_struct {
    long                 priority, pid, pgrp;   // Process PID, group
    unsigned short       uid,suid,gid,sgid..;     //UID,GID
    struct task_struct   *next_task, *prev_task;  //DOUBLY LL
    struct task_struct   *p_opptr, *p_pptr, *p_cptr,  //Pointers to parent, youngest child, silbilings etc

    //File system information
    struct fs_struct     *fs  {int users;seqlock_t seq;int umask;struct path root, pwd;}

    struct sem_queue     *semsleeping;            //IPC Information
    struct mm_struct     *mm;                     //memory management info
    struct signal_struct *sig;                    //signal handlers

    // Process State {RUNNING, INTERRUPTABLE, STOPPED, ZOMBIE, DEAD}
    unsigned int state; 

    // Registers: Stack pointer, Program Counter
    struct thread_struct {unsigned long sp, pc, flags..}
};
                        

Ways of Process Creation, Terminaton

Process Creation Ways

1. System initialization: At boot numerous processes are created.
2. Execution of a process-creation system call by a running process. fork(), CreateProcess()=Windows
3. A user request to create a new process.
4. Initiation of a batch job.

Process Termination ways

way Description Example
1. Normal exit (voluntary) Most processes terminate because they have done their work Scheduler terminates them
2. Error exit (voluntary) process discovers a fatal error `gcc foo.c` is intended for reading file but does not exists. It may exit
3. Fatal error (involuntary) Code bug divide by 0, but this may be handled by process itself using Interrupt(signals).
4. Killed by another process (involuntary) 1 process tells OS to kill other process `kill` system call. `TerminateProcess` on windows