32
Carnegie Mellon 1 Excep&onal Control Flow 15-213: Introduc7on to Computer Systems Recita7on 9: Monday, October 26 th , 2015 Celeste Neary Adapted from slides by Ian Hartwig

Excep&onal Control Flow

  • Upload
    others

  • View
    7

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Excep&onal Control Flow

CarnegieMellon

1

Excep&onalControlFlow

15-213:Introduc7ontoComputerSystemsRecita7on9:Monday,October26th,2015CelesteNearyAdaptedfromslidesbyIanHartwig

Page 2: Excep&onal Control Flow

CarnegieMellon

2

Agenda¢  MidtermWrap-Up¢  Excep7onalControlFlow¢  Processes¢  Signals¢  Shelllab

Page 3: Excep&onal Control Flow

CarnegieMellon

3

MidtermWrap-Up¢  MidtermsscoresareonAutolab¢  ViewexamsduringOHin5207¢  Regraderequests–inwri7ng(hardcopyonly)

Page 4: Excep&onal Control Flow

CarnegieMellon

4

Excep&onalControlFlow¢  Uptonow:twomechanismsforchangingcontrolflow:

§  Jumpsandbranches§  CallandreturnBothreacttochangesinprogramstate

¢  Insufficientforausefulsystem:Difficulttoreacttochangesinsystemstate§  dataarrivesfromadiskoranetworkadapter§  instruc7ondividesbyzero§  userhitsCtrl-Catthekeyboard§  System7merexpires

¢  Systemneedsmechanismsfor“excep7onalcontrolflow”

Page 5: Excep&onal Control Flow

CarnegieMellon

5

AsynchronousExcep&ons(Interrupts)¢  Causedbyeventsexternaltotheprocessor

§  Indicatedbyse`ngtheprocessor’sinterruptpin§  Handlerreturnsto“next”instruc7on

¢  Examples:§  I/Ointerrupts

§  hi`ngCtrl-Catthekeyboard§  arrivalofapacketfromanetwork§  arrivalofdatafromadisk

§  Hardresetinterrupt§  hi`ngtheresetbucon

§  Sodresetinterrupt§  hi`ngCtrl-Alt-DeleteonaPC

Page 6: Excep&onal Control Flow

CarnegieMellon

6

SynchronousExcep&ons¢  Causedbyeventsthatoccurasaresultofexecu7ngan

instruc7on:§  Traps

§  Inten7onal§  Examples:systemcalls,breakpointtraps,specialinstruc7ons§  Returnscontrolto“next”instruc7on

§  Faults§  Uninten7onalbutpossiblyrecoverable§  Examples:pagefaults(recoverable),protec7onfaults(unrecoverable),floa7ngpointexcep7ons

§  Eitherre-executesfaul7ng(“current”)instruc7onoraborts§  Aborts

§  uninten7onalandunrecoverable§  Examples:parityerror,machinecheck§  Abortscurrentprogram

Page 7: Excep&onal Control Flow

CarnegieMellon

7

Processes¢  Whatisaprogram?

§  Abunchofdataandinstruc7onsstoredinanexecutablebinaryfile§  Wricenaccordingtoaspecifica7onthattellsuserswhatitis

supposedtodo§  Statelesssincebinaryfileissta7c

Page 8: Excep&onal Control Flow

CarnegieMellon

8

Processes¢  Defini7on:Aprocessisaninstanceofarunningprogram.¢  Processprovideseachprogramwithtwokeyabstrac7ons:

§  Logicalcontrolflow§  EachprogramseemstohaveexclusiveuseoftheCPU

§  Privatevirtualaddressspace§  Eachprogramseemstohaveexclusiveuseofmainmemory§  Givestherunningprogramastate

¢  HowaretheseIllusionsmaintained?§  Processexecu7onsinterleaved(mul7tasking)orrunonseparate

cores§  Addressspacesmanagedbyvirtualmemorysystem

§  Justknowthatthisexistsfornow;we’lltalkaboutitsoon

Page 9: Excep&onal Control Flow

CarnegieMellon

9

Processes¢  FourbasicStates

§  Running§  Execu7nginstruc7onsontheCPU§  NumberboundedbynumberofCPUcores

§  Runnable§ Wai7ngtoberunning

§  Blocked§ Wai7ngforanevent,maybeinputfromSTDIN§  Notrunnable

§  Zombie§  Terminated,notyetreaped

Page 10: Excep&onal Control Flow

CarnegieMellon

10

Processes¢  Fourbasicprocesscontrolfunc7onfamilies:

§  fork()§  exec()

§  Andothervariantssuchasexecve()§  exit()§  wait()

§  Andvariantslikewaitpid()

¢  StandardonallUNIX-basedsystems¢  Don’tbeconfused:

Fork(),Exit(),Wait()areallwrappersprovidedbyCS:APP

Page 11: Excep&onal Control Flow

CarnegieMellon

11

Processes¢  intfork(void)

§  createsanewprocess(childprocess)thatisiden7caltothecallingprocess(parentprocess)

§  OScreatesanexactduplicateofparent’sstate:§  Virtualaddressspace(memory),includingheapandstack§  Registers,exceptforthereturnvalue(%eax/%rax)§  Filedescriptorsbutfilesareshared

§  ResultàEqualbutseparatestate

§  Forkisinteres7ng(andodenconfusing)becauseitiscalledoncebutreturnstwice

Page 12: Excep&onal Control Flow

CarnegieMellon

12

Processes¢  intfork(void)

§  returns0tothechildprocess§  returnschild’spid(processid)totheparentprocess§  Usuallyusedlike:pid_tpid=fork();if(pid==0){//pidis0sowecandetectchildprintf("hellofromchild\n");}else{//pid=child’sassignedpidprintf("hellofromparent\n");}

Page 13: Excep&onal Control Flow

CarnegieMellon

13

Processes¢  intexec()

§  Replacesthecurrentprocess’sstateandcontext§  ButkeepsPID,openfiles,andsignalcontext

§  Providesawaytoloadandrunanotherprogram§  Replacesthecurrentrunningmemoryimagewiththatofnewprogram

§  Setupstackwithargumentsandenvironmentvariables§  Startexecu7onattheentrypoint

§  Neverreturnsonsuccessfulexecu7on§  Thenewlyloadedprogram’sperspec7ve:asiftheprevious

programhasnotbeenrunbefore§  Moreusefulvariantisintexecve()§  Moreinforma7on?man3exec

Page 14: Excep&onal Control Flow

CarnegieMellon

14

Processes¢  voidexit(intstatus)

§  Normallyreturnwithstatus0(othernumbersindicateanerror)§  Terminatesthecurrentprocess§  OSfreesresourcessuchasheapmemoryandopenfiledescriptors

andsoon…§  Reducetoazombiestate

§  Mustwaittobereapedbytheparentprocess(ortheinitprocessiftheparentdied)

§  Signalissenttotheparentprocessno7fyingofdeath§  Reapercaninspecttheexitstatus

Page 15: Excep&onal Control Flow

CarnegieMellon

15

Processes¢  intwait(int*child_status)

§  suspendscurrentprocessun7loneofitschildrenterminates§  returnvalueisthepidofthechildprocessthatterminated

§  Whenwaitreturnsapid>0,childprocesshasbeenreaped§  Allchildresourcesfreed

§  ifchild_status!=NULL,thentheobjectitpointstowillbesettoastatusindica7ngwhythechildprocessterminated

§  Moreusefulvariantisintwaitpid()§  Fordetails:man2wait

Page 16: Excep&onal Control Flow

CarnegieMellon

16

ProcessExamples¢  Whatarethepossible

output(assumingforksucceeds)?§  Child!

Parent!§  Parent!

Child!

¢  Howtogetthechildtoalwaysprintfirst?

pid_tchild_pid=fork();if(child_pid==0){/*onlychildcomeshere*/printf(“Child!\n”);exit(0);}else{printf(“Parent!\n”);}

Page 17: Excep&onal Control Flow

CarnegieMellon

17

intstatus;pid_tchild_pid=fork();if(child_pid==0){/*onlychildcomeshere*/printf(“Child!\n”);exit(0);}else{waitpid(child_pid,&status,0);printf(“Parent!\n”);}

ProcessExamples¢  Waits7lthechildhas

terminated.Parentcaninspectexitstatusofchildusing‘status’§  WEXITSTATUS(status)

¢  Outputalways:Child!Parent!

Page 18: Excep&onal Control Flow

CarnegieMellon

18

ProcessExamples

¢  Anexampleofsomethinguseful.

¢  Whyisthefirstarg“/bin/ls”?¢  Willchildreachhere?

intstatus;pid_tchild_pid=fork();char*argv[]={“/bin/ls”,“-l”,NULL};char*env[]={…,NULL};if(child_pid==0){/*onlychildcomeshere*/execve(“/bin/ls”,argv,env);/*willchildreachhere?*/}else{waitpid(child_pid,&status,0);…parentcontinueexecution…}

Page 19: Excep&onal Control Flow

CarnegieMellon

19

ProcessExamples¢  UnixProcessHierarchy:

Login shell

Child Child Child

Grandchild Grandchild

[0]

Daemon e.g. httpd

init [1]

Page 20: Excep&onal Control Flow

CarnegieMellon

20

Signals¢  Asignalisasmallmessagethatno7fiesaprocessthatanevent

ofsometypehasoccurredinthesystem§  akintoexcep7onsandinterrupts(asynchronous)§  sentfromthekernel(some7mesattherequestofanotherprocess)toa

process§  signaltypeisiden7fiedbysmallintegerID’s(1-30)§  onlyinforma7oninasignalisitsIDandthefactthatitarrived

ID Name Default Action Corresponding Event2 SIGINT Terminate Interrupt (e.g., ctl-c from keyboard)9 SIGKILL Terminate Kill program (cannot override or ignore)

11 SIGSEGV Terminate & Dump Segmentation violation14 SIGALRM Terminate Timer signal17 SIGCHLD Ignore Child stopped or terminated

Page 21: Excep&onal Control Flow

CarnegieMellon

21

Signals¢  Kernelsends(delivers)asignaltoades2na2onprocessby

upda7ngsomestateinthecontextofthedes7na7onprocess

¢  Kernelsendsasignalforoneofthefollowingreasons:§  KernelhasdetectedasystemeventsuchasCtrl-C(SIGINT),divide-

by-zero(SIGFPE),orthetermina7onofachildprocess(SIGCHLD)§  Anotherprogramcalledthekill()func7on§  Theuserusedakillu7lity

Page 22: Excep&onal Control Flow

CarnegieMellon

22

Signals¢  Ades7na7onprocessreceivesasignalwhenitisforcedby

thekerneltoreactinsomewaytothedeliveryofthesignal

¢  Receivingasignalisnon-queuing§  Thereisonlyonebitinthecontextpersignal§  Receiving1or300SIGINTslooksthesametotheprocess

¢  Signalsarereceivedatacontextswitch¢  Threepossiblewaystoreact:

§  Ignorethesignal(donothing)§  Terminatetheprocess(withop7onalcoredump)§  Catchthesignalbyexecu7ngauser-levelfunc7oncalledsignal

handler§  Akintoahardwareexcep7onhandlerbeingcalledinresponsetoanasynchronousinterrupt

Page 23: Excep&onal Control Flow

CarnegieMellon

23

Signals¢  Ades7na7onprocessreceivesasignalwhenitisforcedby

thekerneltoreactinsomewaytothedeliveryofthesignal

¢  Blockingsignals§  Some7mescodeneedstorunthroughasec7onthatcan’tbe

interrupted§  Implementedwithsigprocmask()

¢  Wai7ngforsignals§  Some7mes,wewanttopauseexecu7onun7lwegetaspecific

signal§  Implementedwithsigsuspend()

¢  Can’tmodifybehaviorofSIGKILLandSIGSTOP

Page 24: Excep&onal Control Flow

CarnegieMellon

24

Signals¢  Signalhandlers

§  Canbeinstalledtorunwhenasignalisreceived§  Theformisvoidhandler(intsignum){…}§  Separateflowofcontrolinthesameprocess§  Resumesnormalflowofcontroluponreturning§  Canbecalledany&mewhentheappropriatesignalisfired

Page 25: Excep&onal Control Flow

CarnegieMellon

25

Signals¢  intsigsuspend(constsigset_t*mask)

§  Can’tusewait()twice–usesigsuspend!§  Temporarilyreplacesthesignalmaskofthecallingprocesswiththe

maskgiven§  Suspendstheprocessun7ldeliveryofasignalwhoseac7onisto

invokeasignalhandlerorterminateaprocess§  Returnsifthesignaliscaught

§  Signalmaskrestoredtothepreviousstate§  Usesigaddset(),sigemptyset(),etc.tocreatethemask

Page 26: Excep&onal Control Flow

CarnegieMellon

26

SignalExamples¢  Everyprocessbelongstoexactlyoneprocessgroup¢  Processgroupscanbeusedtodistributesignalseasily¢  Aforkedprocessbecomesamemberoftheparent’s

processgroup

Fore-groundjob

Back-groundjob#1

Back-groundjob#2

Shell

Child Child

pid=10 pgid=10

Foregroundprocessgroup20

Backgroundprocessgroup32

Backgroundprocessgroup40

pid=20 pgid=20

pid=32 pgid=32

pid=40 pgid=40

pid=21 pgid=20

pid=22 pgid=20

getpgrp()Returnprocessgroupofcurrentprocess

setpgid() Changeprocessgroupofaprocess

Page 27: Excep&onal Control Flow

CarnegieMellon

27

//sigchldhandlerinstalledpid_tchild_pid=fork();if(child_pid==0){/*childcomeshere*/execve(……);}else{add_job(child_pid);}

SignalExamples

¢  Doesadd_joborremove_job()comefirst?¢  Wherecanweblocksignalsinthiscodetoguarantee

correctexecu7on?

voidsigchld_handler(intsignum){intstatus;pid_tchild_pid=waitpid(-1,&status,WNOHANG);if(WIFEXITED(status))remove_job(child_pid);}

Page 28: Excep&onal Control Flow

CarnegieMellon

28

//sigchldhandlerinstalledpid_tchild_pid=fork();if(child_pid==0){/*childcomeshere*/execve(……);}else{add_job(child_pid);}

SignalExamples

¢  Doesadd_joborremove_job()comefirst?¢  Wherecanweblocksignalsinthiscodetoguarantee

correctexecu7on?

voidsigchld_handler(intsignum){intstatus;pid_tchild_pid=waitpid(-1,&status,WNOHANG);if(WIFEXITED(status))remove_job(child_pid);}

BlockSIGCHLD

UnblockSIGCHLD

UnblockSIGCHLD

Page 29: Excep&onal Control Flow

CarnegieMellon

29

ShellLab¢  ShellLabisout!¢  DueTuesday,November3rdat11:59pm¢  Readthecodewe’vegivenyou

§  There’salotofstuffyoudon’tneedtowriteyourself;wegaveyouquiteafewhelperfunc7ons

§  It’sagoodexampleofthecodeweexpectfromyou!

¢  Don’tbeafraidtowriteyourownhelperfunc7ons;thisisnotasimpleassignment

Page 30: Excep&onal Control Flow

CarnegieMellon

30

ShellLab¢  Readmanpages.Youmayfindthefollowingfunc7ons

helpful:§  sigemptyset()§  sigaddset()§  sigprocmask()§  sigsuspend()§  waitpid()§  open()§  dup2()§  setpgid()§  kill()

¢  Pleasedonotusesleep()tosolvesynchroniza7onissues.

Page 31: Excep&onal Control Flow

CarnegieMellon

31

ShellLab¢  Hazards

§  Racecondi7ons§  Hardtodebugsostartearly(andthinkcarefully)

§  Reapingzombies§  Racecondi7ons§  Handlingsignalscorrectly

§  Wai7ngforforegroundjob§  Thinkcarefullyaboutwhattherightwaytodothisis

Page 32: Excep&onal Control Flow

CarnegieMellon

32

ShellLabTes&ng¢  Runyourshell

§  Thisisthefunpart!¢  tshref

§  Howshouldtheshellbehave?¢  runtrace

§  Eachtracetestsonefeature.