Professional Documents
Culture Documents
SomenotesadoptedfromBryantandOHallaron
Processes
Def:Aprocessisaninstanceofarunningprogram.
Oneofthemostprofoundideasincomputerscience. Notthesameasprogramorprocessor
Processprovideseachprogramwithtwokeyabstractions:
Logical i lcontrol lfl flow
EachprogramseemstohaveexclusiveuseoftheCPU.
Privateaddressspace
Eachprogramseemstohaveexclusiveuseofmainmemory.
HowaretheseIllusionsmaintained?
Processexecutionsinterleaved(multitasking) Addressspacesmanagedbyvirtualmemorysystem
Concurrent Processes
Twoprocessesrunconcurrently (areconcurrent) if theirflowsoverlapintime. Otherwise,theyaresequential. Examples:
Concurrent:A&B,A&C Sequential:B&C
Process A Time Process B Process C
Context Switching
ProcessesaremanagedbyasharedchunkofOScode calledthekernel Controlflowpassesfromoneprocesstoanotherviaa contextswitch.
Process A code
Process B code
user code context switch
Time
context switch
SP
Thread2
Programcontext: Dataregisters Conditioncodes Stackpointer(SP) Programcounter(PC) stack
SP
Threadsandprocesses:differences
Threadssharecodeanddata data,processes(typically)do not Threadsaremuchlessexpensivethanprocesses
Processcontrol(creatingandreaping)ismoreexpensiveas threadcontrol Contextswitchesforprocessesmuchmoreexpensivethanfor threads
Allocation:Compilerandruntimesystem
Wheredifferentprogramobjectsshouldbestored Allallocationwithinsingle g virtualaddressspace p
Butwhyvirtualmemory? Whynotphysicalmemory?
FFF
Andtherearemanyprocesses.
stack heap
Whatgoes where?
Processj
Processj
Process1
Physicalmemory
mapping
Virtual i lmemory
Processn
Address Spaces
Virtualaddressspace
SetofN=2nvirtualaddresses:{0,1,2,3,,N1}
Physicaladdressspace
SetofM=2mphysicaladdresses:{0,1,2,3,,M1}
CPU
Physicaladdress (PA)
... .
M1:
Dataword
MMU
Mainmemory 0: 1: 2 2: 3: 4: 5: 6: 7: 8:
...
M1:
Dataword
Simplifiesmemorymanagementforprogrammers
Eachprocessgetsthesamefull,privatelinearaddressspace
Isolatesaddressspaces
Oneprocesscantinterferewithanothersmemory
becausetheyoperateindifferentaddressspaces
Userprocesscannotaccessprivilegedinformation
differentsectionsofaddressspaceshavedifferentpermissions
Physicalmemory (DRAM)
VP1 VP2 VP7 VP4
PP0 PP3
null
Virtualmemory (disk)
VP1 VP2 VP3 VP4 VP6 VP7
Virtualaddress
Virtualpagenumber(VPN) Virtualpageoffset(VPO)
Pagetable
Valid Physicalpagenumber(PPN)
Physicalpagenumber(PPN)
Physicalpageoffset(PPO)
Physicaladdress
Exceptions
SomenotesadoptedfromBryantandOHallaron
Control Flow
ComputersdoOnlyOneThing
Fromstartuptoshutdown,aCPUsimplyreadsand executes(interprets)asequenceofinstructions Thissequenceisthesystemsphysicalcontrolflow (or flowofcontrol).
Physical control flow Ti Time <startup> inst1 inst2 inst3 instn <shutdown>
Systemneedsmechanismsforexceptionalcontrolflow
CombinationofhardwareandOSsoftware
HigherLevelMechanisms
Processcontextswitch Signals Nonlocaljumps(setjmp/longjmp) I l Implemented dby b either: ih
OSsoftware(contextswitchandsignals). Clanguageruntimelibrary:nonlocaljumps.
Processor
Interrupt controller t ll
Keyboard controller t ll
Local/IO Bus
Memory
Video adapter p
Network adapter p
Display
Network
Exceptions
AnexceptionisatransferofcontroltotheOSinresponse tosomeevent(i.e.,changeinprocessorstate)
UserProcess exception exceptionprocessing b exception by ti h handler dl returntoI_current returntoI_next abort OS
event
I_current I_next
Interrupt Vectors
Exception numbers b code for exception handler 0 interrupt vector
0 1 2 n-1
...
...
code for exception handler n-1
Eachtypeofeventhas auniqueexception numberk Indexintojumptable ( k interrupt (a.k.a., i vector) Jump J t table bl entry t k pointstoafunction (exceptionhandler). handler) Handlerkiscalledeach timeexceptionk occurs.
Examples:
I/Ointerrupts
hittingctlcatthekeyboard arrivalofapacketfromanetwork arrivalofadatasectorfromadisk
Hardresetinterrupt
hittingtheresetbutton
Softresetinterrupt
hittingctlaltdeleteonaPC
bus interface
I/O bridge
main memory
I/O bus USB controller mouse keyboard graphics adapter monitor disk disk controller
CPU initiates a disk read by writing a command, logical block number, and destination memory y address to a port (address) associated with disk controller.
bus interface
main memory
I/O bus
disk controller
disk
Disk controller reads the sector and performs a direct memory access (DMA) transfer into main memory. y
bus interface
main memory
I/O bus
disk controller
disk
When the DMA transfer completes, the disk controller notifies the CPU with an interrupt ( (i.e., asserts a special interrupt pin on the CPU)
bus interface
main memory
I/O bus
disk controller
disk
Synchronous Exceptions
Causedbyeventsthatoccurasaresultofexecutingan instruction:
Traps
Intentional Examples: p system y calls, ,breakpoint p traps, p ,special p instructions Returnscontroltonextinstruction
Faults
Unintentional lbut b possibly bl recoverable bl Examples:pagefaults(recoverable),protectionfaults(unrecoverable). Eitherreexecutesfaulting(current)instructionoraborts.
Aborts
unintentionalandunrecoverable Examples: Examples parityerror error,machinecheck check. Abortscurrentprogram
Trap Example
OpeningaFile
Usercallsopen(filename,options)
0804d070 <__libc_open>: . . . 804d082: cd 80 804d084: 5b . . . int pop $0x80 %ebx
Functionopenexecutessystemcallinstructionint
OS
Fault Example #1
MemoryReference
Userwritestomemorylocation Thatportion(page)ofusersmemoryiscurrentlyondisk Page g handlermustloadpage p g intop physical y memory y int a[1000]; Returnstofaultinginstruction main () { Successful Success u o onseco second d t try y
a[500] = 13; }
User Process
OS
event
movl
Fault Example #2
MemoryReference
Userwritestomemorylocation int a[1000]; main () Addressisnotvalid { a[5000] = } Page g handlerdetectsinvalidaddress SendsSIGSEGsignaltouserprocess Userprocess Use p ocesse exits tswith t segmentation seg e tat o fault au t
User Process OS
13;
event
movl
Checkpp.183: http://download.intel.com/design/processor/manuals/253665.pdf
Linkers
SomenotesadoptedfromBryantandOHallaron
Example C Program
main.c int buf[2] = {1, 2}; int main() { swap(); return 0; } swap.c extern int buf[]; static int *bufp0 = &buf[0]; static int *bufp1; void swap() { i t temp; int t bufp1 = &buf[1]; temp = *bufp0; *bufp0 = *bufp1; *bufp1 = temp; }
Static Linking
Programsaretranslatedandlinkedusingacompiler driver:
unix>gccO2gopmain.cswap.c unix>./p
main.c Translators (cpp,cc1,as) main o main.o Linker(ld) p Fullylinkedexecutableobjectfile (containscodeanddataforallfunctions definedinmain.candswap.c swap.c Translators (cpp,cc1,as) swap o swap.o Separatelycompiled relocatableobjectfiles Sourcefiles
Space:Libraries
Commonfunctionscanbeaggregatedintoasinglefile file... Yetexecutablefilesandrunningmemoryimagescontain onlycodeforthefunctionstheyactuallyuse.
Linkerassociateseachsymbolreferencewithexactly onesymboldefinition.
Executableobjectfile
Containscodeanddatainaformthatcanbecopieddirectlyinto yandthenexecuted. memory
Sharedobjectfile(.sofile)
Specialtypeofrelocatable objectfilethatcanbeloadedinto memoryandlinkeddynamically,ateitherloadtimeorruntime. CalledDynamicLinkLibraries(DLLs)byWindows
Awkward,giventhelinkerframeworksofar:
Option p 1:Putallfunctionsintoasingle g sourcefile
Programmerslinkbigobjectfileintotheirprograms Spaceandtimeinefficient
Option2:Puteachfunctioninaseparatesourcefile
Programmersexplicitlylinkappropriatebinariesintotheir programs Moreefficient,butburdensomeontheprogrammer
Archiver (ar)
libc.a
Cstandardlibrary
libm.a (theCmathlibrary)
1MBarchive hi of f226object bj fil files. floatingpointmath(sin,cos,tan,log,exp,sqrt,)
% ar -t /usr/lib/libc.a | sort fork.o fprintf.o fpu_control.o fputc.o freopen.o fscanf.o fseek o fseek.o fstab.o % ar -t /usr/lib/libm.a | sort e_acos.o e_acosf.o e_acosh.o e_acoshf.o e_acoshl.o e_acosl.o e_asin.o e asinf o e_asinf.o e_asinl.o
p2
Problem:
Commandlineordermatters! Moral:putlibrariesattheendofthecommandline.
unix> gcc -L. libtest.o -lmine unix> gcc -L. L -lmine lmine libtest.o libtest o libtest.o: In function `main': libtest.o(.text+0x4): undefined reference to `libfun'
Shared Libraries
Staticlibrarieshavethefollowingdisadvantages:
Duplicationinthestoredexecutables(everyfunction needstdlibc) Duplicationintherunningexecutables Minorbugfixesofsystemlibrariesrequireeach applicationtoexplicitlyrelink
ModernSolution:SharedLibraries
Object j filesthatcontaincodeanddatathatareloaded andlinkedintoanapplicationdynamically,ateither loadtimeorruntime Alsocalled:dynamiclinklibraries,DLLs,.sofiles
Dynamiclinkingcanalsooccurafterprogramhasbegun (runtimelinking). ( g)
InUnix,thisisdonebycallstothedlopen()interface.
Highperformancewebservers. Runtimelibraryinterpositioning
p2
Loader (execve)
Dynamiclinker(ld-linux.so)
Userstack (createdatruntime)
Memorymappedregionfor sharedlibraries
0x40000000
Unused
linktime
Whentherelocatable objectfilesarelinkedtoforman executableobjectfile
load/runtime
Whenanexecutableobjectfileisloadedintomemory, dynamicallylinked,andthenexecuted.
Behindthescenesencryption
Automaticallyencryptotherwiseunencryptednetwork connections.
MonitoringandProfiling f
Countnumberofcallstofunctions Characterizecallsitesandargumentstofunctions Malloc tracing
Detectingmemoryleaks Generatingmalloc traces