外文翻译原文-TinyOS的接口协议_第1页
外文翻译原文-TinyOS的接口协议_第2页
外文翻译原文-TinyOS的接口协议_第3页
外文翻译原文-TinyOS的接口协议_第4页
外文翻译原文-TinyOS的接口协议_第5页
已阅读5页,还剩3页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

InterfaceContractsforTinyOSWillArcherPhilipLevisJohnRegehrSchoolofComputingDepartmentofComputerSchoolofComputingUniversityofUtahScienceUniversityofUStanfordUABSTRACTTinyOSapplicationsarebuiltwithsoftwarecomponentsthatcom-UserUserAmunicatethroughnarrowinterfaces.Sincecomponentsenablefine-Contract|grainedcodereuse,thisapproachhasbeensuccessfulincreat-Provideringapplicationsthatmakeveryefficientuseofthelimitedcoderovideranddatamemoryonsensornetworknodes.However,theotherimportantbenefitofcomponentsrapidapplicationdevelopmentthroughblack-boxreuseremainslargelyunrealizedbecauseinFigure1:AninterfacecontractenforcescorrectuseofamanycasesinterfaceshaveimpliedusageconstraintsthatcanbenesCinterfacebyinterposingbetweentheinterfacesuserandthesourceoffrustratingprogramerrors.Developersarecommonlyproviderforcedtoreadthesourcecodeforcomponents,partiallydefeatingthepurposeofusingcomponentsinthefirstplace.Ourresearchhelpssolvetheseproblemsbyallowingdeveloperstoexplicitlyspecifyandenforcecomponentinterfacecontracts.Duetothleex-spe-plctoeeomnttruhcmoetrueUnot-tpensivereusenfofrecomposentcointerfaces,implementingtseont-nately,creatingreliableTinyOSapplicationsbybuildingonexist-tensiveres.ftemsomnitefcsmlmnigcningcomponents,especiallythosewrittenbyothers,isnotoriouslytractsforasmallnumberoffrequentlyreusedinterfacespermitteddinicomponespeciallytoewisthtbyotersisnoftorinoSlustexensielychecaumbeofapplcatons.Wencovreddifficult.AprincipalchallengeisthatproperuseoftheTinyOSinterfaceshasneverbeencarefullyspecified,givingdevelopersun-somesubtleandpreviouslyunknownbugsinapplicationsthathavewanteddegreesoffreedom.Developersofreusablecomponentsbeenincommonuseforyears.areforcedtoassumethattheirinterfaceswillbemisused,requiringdefensiveprogrammingthataddsdevelopmentandresourceover-CategoriesandSubjectDescriptorshead.Similarly,thosereusingexistingcomponentsareforcedtoD.2.4SoftwareEngineering:Software/ProgramVerificationassumethatinterfacecallsmayfail,evenwhenusedproperly,ne-ProgrammingbyContract;D.2.5SoftwareEngineering:Test-cessitatingdevelopmentoverheadduetoerrorcheckingandfailureingandDebuggingTestingtoolsrecoverystrategies.Theseproblemshavebeenshowntoberele-vantfortheinterfacesinTinyOSl.x,whichwecheckedforthisGeneralTermspaper,andwebelievetheyarepresentinTinyOS2.0aswell.Asasteptowardssolvingtheseproblemswedevelopedinter-Design,Reliability,VerificationfacecontractsforTinyOS.AninterfacecontractdepictedinFig-ure1isacheckable,executablespecificationthatcodifiestheKeywords(previouslyimplicit)rulesforcorrectlyusinganinterface.Tocheckcomponentimplementationsagainsttheircontracts,weimplementedValidation,designbycontract,TinyOS,sensornetworks,automateddynamiccontractcheckingviaasource-to-sourceprogramtrans-testingformationthataddscheckstoexistingTinyOSapplicationssuchthatanerrorisraisedanytimeaninterfaceismisused.1.INTRODUCTIONContractsprovidedeveloperswithagoodvalueproposition:aTinyOShasbeenasuccessfulbasisforinterrupt-drivensensor-contractforagiveninterfacehastobespecifiedjustonceandthennetapplications.Itscomponentmodelisdesignedtominimizeap-itcanbereusedforanyinstanceoftheinterface.Similarly,thereplicationcodesizebylinkinginonlyneededfunctionality,andtoislargepotentialforreusingcontractsacrossmultipleapplicationsandforreuseovertime:thecoreTinyOSl.xinterfaceshavere-mainedfairlystableforseveralyears.IntroducinganeffectiveandefficientcontractcheckingsystemPermissiontomakedigitalorhardcopiesofallorpartofthisworkforintoexistingTinyOScodesrequiredsolvingthreedifficultprob-personalorclassroomuseisgrantedwithoutfeeprovidedthatcopiesarelems.Thefirstproblemisdefiningthecontractsthemselves.ThisnotmadeordistributedforprofitorcommercialadvantageandthatcopiesrequiresreviewingtheTinyOScodebasetolearntheexpectedcallbearthisnoticeandthefullcitationonthefirstpage.Tocopyotherwise,topatterns,manyofwhicharenonobviousandothersareusedincon-republish,topostonserversortoredistributetolists,requirespriorspecifictradictorywaysindifferentpartsofthecodebase.Retrofittingcon-permissionand/orafee.IPSN07,April25-27,2007,Cambridge,Massachusetts,USA.tractsintoasystemthathasexistedwithoutthemforyearsisfun-Copyright2007ACM978-1-59593-638-7/07/0004.$5.00.damentallyhard.Forexample,wehaverepeatedlyfoundthateven158l-interfaceSendMsgcommandresulttsend(uintl6_taddr,TOS-MsgPtr,uint8_tlen);Ieventresult_tsendDone(TOS-MsgPtr,result_tsuccess);Figure3:TheSendMsginterface-interfaceTimercommandresult_tstart(chartype,uint32_tinterval);Figure2:Withoutinterfacecontracts(left),faultisolationincommandresult_tstop();complexTinyOSapplicationsisdifficult.Contracts(right)con-eventresult_tfiredo;tinuouslycheckinterfaceinvariants,supportingrapidandeffi-cientfaultdetection.Figure4:TheTimerinterfacecontractsthatwebelievetobefartooweakareroutinelyviolatedbyapplicationsthat,forthemostpart,work.ThesecondproblemisresolvingnesCfeaturesandidiomswithtraditionalnotionsofTinyOSdoesnotsupportblocking.Instead,slowoperationscontracts.ThenesClanguagehasseveraladvancedfeatures,suchespeciallythosethatinvolvehardwarelatenciesaresplit-phase.astheabilityforafunctioncalltofan-outtomultiplecallees,Forexample,Figure3showsthebasicpacketcommunicationin-whichacontractcheckermustbeabletohandle.Thethirdchal-terface,SendMsg.Ratherthanwaituntilanoperation(e.g.,Send-lengeisdefiningacontractlanguagethatcanhandlethefirsttwoMsg.send)completes,theinterfacecommandreturnsimmediately,challenges,iseasytounderstand,anddoesnotintroducesignificantallowingtheapplicationtocontinueprocessing.Whentheopera-resourceoverheadsonhighlyconstrainedsensornetnodes.tiondoescomplete,theinterfacesignalsthecompletionevent(e.g.,Oureventualgoalisforeveryinterfacetohaveacontract,includ-SendMsg.sendDone),atwhichpointtheusercanreclaimthepacketinglow-levelhardwareabstractions.Thiswouldallowunittestsinbuffer.Thesplit-phasesemanticshasanumberofadvantagesbutitasimulationenvironment,whereonecomponentistestediniso-alsocreatesdifficultiesfordevelopers,whoareforcedtoexplicitlylationagainstarbitraryinputs.Unittestsinsimulationwilldetectmaintaincomponentstateacrossmultipleinvocations.Split-phasesomebutnotallbugs;realnodesshouldalsobeabletoefficientlyoperationisthesourceofquiteafewoftheinterfacemisusesthatenforcecontractswhilerunningfullapplications.Introducingafewwefound.hundredcyclesofoverheadperpackettransmissionmaybefeasi-Animplementationcannotnameanothercomponent:compo-ble,butnotoneveryradiobyteinterrupt.nentsinteractsolelythroughinterfaces.Thisexplicitseparational-Ourresearchhastwomainbenefits.Intheshortterm,asFig-lowsprogrammerstoeasilychangewhichimplementationisused.ure2illustrates,contractsserveascheckable,executabledocumen-Forexample,acomponentnamedAppMthatusesSendMsgcanbetationthatmakesiteasierfordeveloperstocreatecorrectcode,anddirectlyconnectedtoaradio-onlycommunicationstack,aradio-torapidlylocatebugsinincorrectcode.Inthelongerterm,weserialhybridstack,ortoasendqueuewithoutchangingAppMsexpectthatitwillbepossibletouseformalmethodstostaticallycode.checkbothindividualcomponentsandentireapplicationsagainstTheabilitytoeasilyswitchbetweendifferentimplementationsoftheirinterfacecontracts.Checkingindividualcomponentsisveryaninterfacerequiresthattheimplementationsareinterchangeable.powerfulbecauseitshowsthataparticularcomponentiscorrectinUnfortunately,atpresent,thereisnoprecisespecificationoftheanypossibleinstantiation,ratherthanjustinonespecificone.Fur-semanticsandcallpatternsofmostinterfaces.Asthereisagoodthermore,weexpectthatcomponent-levelcheckingwillbeusefuldealoflatitudeinimplementation,acomponentmustbeabletoinanassume-guaranteereasoningscheme5thatcaninductivelyhandleawiderangeofbehaviors.Thisimprecisionleadstobloatedshowthatanentireapplicationiscorrect.code,aseverycomponentmustbeprogrammeddefensively.3.DESIGNINGACONTRACTSYSTEM2.TINYOSBACKGROUNDThissectiondescribesourcontractlanguageandhowdeveloperscanuseittospecifyaninterfacessemantics.TinyOS7isacomponent-basedoperatingsysteminwhichcomponentsinteractthroughtypedinterfaces.TheOSiswritten3.1ThecontractlanguageinnesC4,adialectofCwithsupportforcomponents,interfaces,concurrencyanalysis,andnetworktypes.BuildingaTinyOSappli-OurcontractsarespecifiedinastylizedversionofC,inor-cationinvolvesconnectingtheinterfacesofcomponentstogether.dertoprovidedeveloperswithafamiliarenvironment.Figure4Interfacesarebidirectional,inthattheycandescribeboththecallshowsTinyOSstimerinterfaceandFigure5illustratesthebasicthatausercanmakeonaserviceprovider(commands)aswellascontractsyntaxbyshowingthecontractforoneoftheinterfacescallsaprovidercanmakeonauser(events).Forexample,sendingcommands.Inthisexample,theTimer.startO)commandgeneratesapacketisacommand,whilereceivingapacketisanevent.Gen-astatetransitiononlyifthecommandreturnsSUCCESS.Thecon-erally,aninterfacesupportsanarrowbutcompleteabstractionsuchtractforaninterfacecallcontainsPREandPOSTsections,whereasusingatimer,writingtoanon-volatilelog,orreceivingpackets.preconditionandpostconditioncodeisplaced.InFigure5,the159IIGlobalvariablewhichrepresentsBufferownedbyapplicationBufferownedbysendstack/timerstate.SendMsg.sendoTimer_state_tstate=IDLE;voidstart(chartype,uint32_tinterval)SendMsg.sendoneoPRE:if(stateIDLE)ERROR(NON-IDLETIMERSTARTED);SendMsg.sendDoneOSendMsg.sendoprint_dec_int(int)ID);ErrorPOST:if(R_VAL=SUCCESS)if(type=TIMER_ONE_SHOT)state=ONE-SHOT;elseif(type=TIMER-REPEAT)state=REPEATING;Figure7:StatemachineforSendMsginterfaceelsestate=IDLE;=ThisisthecasefortheSendMsginterfaceshowninFigure3.Tosupportthiskindofinterface,wepermitcontractstoaugmentdatastructureswithnewfields,andtoaccessthesefields.Forexample,Figure6showshowastatevariableisaddedtotheTinyOSpacketbufferdatastructure.Inthiscase,whenabufferispassedtoSend-Figure5:ContractfortheTimer.start(commandMsg.send(,itisassumedtobeunavailableforanadditionalsend(requestuntilthecorrespondingsendDone(eventfires.Thus,at-/StatefieldtoappendtoeachTOS_Msgtemptingtosendthesamebuffertwicebeforethefirstrequestcom-typedefstructTOS_Msgpletesisacontractviolation,althoughanattemptedsend(usingaTOS_Msg_state_tmsg_state;differentbufferisnot.TOS_Msg_attribute_(append);voidsend(TOS_Msg*msg,uint16_tlength)3.2WritingcontractsThefirst,andmostimportant,stepinproducingacontractisde-if(RPVAL=SUCCESS)terminingthestatemachinethatisimpliedbytheinterface.Whileif(msg-msg_state!=USER_OWNED)thisprocessseemsobvious,gettingthecontractswrittencorrectlyERROR(SENDERROR:SENDOS_OWNED);isnon-trivialandrequiredasignificantamountofdevelopmenttimeonourpart.Oneoftheimportantcontributionsofourtoolmsg-msg_state=OS-OWNED;isprovidingasetofcontractsforthetrickiestandmostcommonlyusedinterfaceswithinTinyOS.Byprovidingtheseweenablerel-ativelythoroughcheckingofexistingapplicationswithminimaladditionalprogramming.Onceastatemachinethatencapsulatestheinterfacesbehaviorhasbeenestablished,thetransitionscanFigure6:ContractfortheSendMsg.send(commandbetranslatedintoexecutablecontracts.ThestatemachinefortheSendMsginterface(Figure3)isshowninFigure7.Figure8showsthenumberofinterfacescontainedinoursamplesafetycheckisplacedinthepreconditioninordertogenerateaapplicationsandhowmanywearecurrentlychecking.Byrunningfailureasearlyaspossible.checksononlyafewinterestinginterfacesweareabletocoverContractsarepermittedtoexamineargumentstointerfacecalls,roughlyhalfofthetotalnumberofinterfaceinstances.Forthisandalsotoexaminedatareferencedbythesearguments.ContractspaperwefocusedoninterfacesthatwerecommonenoughtoapplymayaccessacallsreturnvalueusingaspecialR-VALvariable.AstoawidevarietyofapplicationsandinterestingenoughtohavetheFigure5shows,thereturnvalueisoftenusedtomakeconditionalpotentialtocontainworthwhilebugs.Thoughthereareasignificantchangestotheinterfacesstatebasedonthesuccessorfailureofnumberofinterfacesthatwedonotcover,themajorityofthemarenotstatefulandhencerequirenocontracts,orarespecifictothecall.Contractcodemaydeclarestatevariables;aseparatecopyiniidaapliaiosofthesevariablesisinstantiatedforeachuseofacontractinanapplication.ThespecialvariableIDismappedtotheparameterized3.3Warningsvs.errorsvalueoftheinterface,shouldonebeavailable.Itisprovidedasaconvenienceformakingerrormessagesmoreuseful.Wecametorecognizethatcontractviolationshavemultiplelev-Contractsarenotallowedtoaccesscomponent-localinforma-elsofseverity,andweadoptedtheconventionthatcontractviola-tionthatdoesnotflowacrosssomeinterface.Thiswouldviolatetionsaredividedintotwocategories.Warningsindicateusagethatourdesignprinciplethatcontractsareaboutinterfaces,notimple-isinpoortastebutthatdoesnot,asfarasweknow,directlyleadmentations.toapplicationmalfunction.Forexample,awarningisgeneratedSomeinterfacecontracts,suchastheoneinFigure5,canbeex-whenanapplicationinitializesatimercomponentthatalreadyhaspressedintermsofchecksonthestateoftheinterface.Inotheratimersettofire.Moresevereareerrors,whichindicatebehav-cases,theinterfaceitselfisstatelessandthecontractenforcespre-iorthatcannotpossiblybecorrect,suchasconcurrentlypassingaconditionsandpostconditionsondatastructuresintheapplication,singlepacketbuffertothereceivesubsystemmultipletimes.160StdControlTimerSendReceivePotClockLedsADCADCControlRouteControlOtherBlinkTask32003220003CntToLedsAndRfm1566722330023Surge258121222684323Surge-TinySec268141422684349SurgeReliable3710131222340361Figure8:NumberoftimeseachinterfaceisusedbysomeTinyOSapplications4.CHECKINGCONTRACTSnesCcompilerWecreatedasource-to-sourcetransformationtoolthatinputsacollectionofcontractsandtheCcodeemittedbythenesCcom-computepiler,andoutputsanewCprogramthat,whenrun,dynamicallycaligraph|checksinterfacecontracts.OurtoolisbasedonCIL12,aparser,typechecker,andintermediaterepresentationforC.findinstrumentationpoints4.1AddingcontractchecksOurtool,showninFigure9,performsthefollowingsteps.contractsinstrumentcode(augmentdataaddglobalDetermineinterfacealiasing.BecauseinterfacenamesareaugenaddgloblstructuresstatevariablesobscuredinthenesCcompilersoutput,ourtoolrequiressomead-ditionalinformationbeforeitcanaddcontractchecks.ThenesCcleanupandcompileroptionallydumpsthiskindofwiringinformationasXML.cileingJWeusethisfeaturetomapfunctionnamesintheemittedCcodeto_theiractualinterfaceinstances.supportgccConstructcallgraphandapplicationwiringfromsourcecodecode.ThenesCcompileruseswell-definednamemanglingsch-emes,permittingustorecovercomponentwiringinformationdi-Figure9:Ourinfrastructureforaddingdynamiccontractrectlyfromthecompileroutput.Bypullingapartthemangledfunc-checkstoaTinyOSapplicationtionnamesandknowingtheinterfacealiasingforagivenapplica-tion,weknowwhichfunctionsimplementagiveninterface,andwhichcomponenttheybelongto.Wealsobuildawhole-programusesofinterfaceswithcontractchecks,theoverheadwouldbesig-callgraphfromtheapplicationcode,supportinganoptimizationnificant.Asanoptimization,hecasewhereacomponentpassesacallfromoneinstanceofaninterfacetoanotherinstanceofthesameinterfacewithoutper-Addcontractcheckingcode.InterfacesinTinyOScontainforminganyadditionalprocessing.twodifferentkindsoffunctioncallscommandsandeventsthatrequireslightlydifferenttreatmentbyourtool.WeinstrumentInliningandcleanup.ThenesCcompilerattemptstogeneratecommandsbyincludingpreconditioncodeatthebeginningofthesmallobjectcodebyinliningsmallfunctionsandfunctionsthatfunctionandpostconditioncodebeforeallreturns.Instrumentinghaveonecallsite.Wefoundthataddingcontractcheckingcodeevents,whichoriginateinlow-levelcodeandmoveup,requiresatothenesCcompilersoutputinvalidateditsinliningdecisionsbydifferentapproach.Becausetheremaybenecessarylogicbeforemakingfunctionslarger,resultinginlargecodesizeblowup:oftentheupcalls,wecannotassumethatthestatetransitionoccursattheby400%ormore.Inpreviouswork3,14wedevelopedaninlinerbeginningoftheinterfacefunctioninquestion.Forthisreason,weandastrongdeadcodeeliminatorforC.Weusethesetoreducetheinstrumentbeforeandaftereachupcall,pluggingintheupcallscodesizeoverheadofinterfacecontracts.OurinlinermakesitsreturnvalueforRNVALwhenneeded.decisionsbasedoncodesizeaftercontractsareadded,enablingittomakemoreappropriateinliningdecisions.Addcontractstatevariables.Contractstatevariablescomeintwoflavors:per-contactandper-data-structure.Per-contract4.3Handlingcontractviolationsvariablesarestraightforwardtoadd,asnewglobalvariables.Per-Whenacontractisviolated,wehaveavarietyofoptionsforre-data-structurevariablesareappendedtotheendofexistingstructs.portingtheerrorortakingcorrectiveaction.Tosupporteasiertest-4.2OptimizationsingofapplicationsinAvrora17,acycle-accuratesensornetworksimulator,wedevelopedasimpleprintf-likefunctionfordump-ingwarningsanderrorstothesimulatorconsole.Whencontract-Avoidingredundantchecking.Wefoundthattypically,manyenabledapplicationsarerunonrealhardware,wesuppresswarn-usesofTinyOSinterfacessimplypasscallsthroughfromonecom-ingsandsignalerrorsbyusingthemotesthreeLEDstoblinkoutponenttoanotherwithoutperforminganyusefulcomputation.Nor-afailureidentificationcodeinoctal.Thiscodecanbeturnedintomallythesecallsintroducenooverheadbecausetheyareeliminatedasourcecodelocationofflineusingaseparatetool.Inadeployedthroughfunctioninlining.However,ifweinstrumentedallofthesesensornetwork,acontractviolationshouldbeloggedoverthenet-161workusingaloggingserviceandthenodeshouldberebooted;weInthissituation,BCastM,MultiHopEngineM,andMultiHop-havenotimplementedthis.LEPSMarewiredtothesameSendMsginterface.TheQueued-SendMcomponenthasnoinformationtodeterminewhichofthe5RESULTSthreeuserscalledSendMsg.send(.Therefore,whenitsignalsSend-RESULTSMsg.sendDone(),theeventhandleriscalledonallthreeusers.Be-Thissectionsummarizesourresultsfromaddingdynamiccon-causeQueuedSendMcanhavemultipleoutstandingpackets,itistractcheckingtoseveralTinyOS1.xapplications.possiblethatmorethanoneoftheusershasapacketinthesendqueue.Therefore,morethanoneofthemmightbewaitingfora5.1OverheadofdynamiccheckingSendMsg.sendDone(.IftheuserdoesnotcheckthatthebufferFigure10showsthepercentagechangeindatasize,codesize,passedintotheSendMsg.sendDone(eventisitsown,thenitm

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论