您好,欢迎来到飒榕旅游知识分享网。
搜索
您的当前位置:首页A declarative approach to extensible interface

A declarative approach to extensible interface

来源:飒榕旅游知识分享网
Adeclarativeapproachtoextensibleinterface

compilation

NicholasFitzRoy-Dale

NationalICTAustraliaandUniversityofNewSouthWales

Sydney,Australianfd@cse.unsw.edu.au

Abstract—Inmicrokernel-basedoperatingsystems,source-to-sourcecompilersgeneratecodetoeasethepro-cessofmarshalingdataforcommunicationviamessagepass-ing.However,theruleofthumbfortheseinterfacecompilersseemstobe“simple,extensible,efficientoutput–pickanyone”.Iarguethatthemajorcauseofextensibility-limitingcomplexityininterfacecompilerscomesfromthesource-to-sourcetransformationcodeitself,andthiscomplexityisprimarilyaresultofthedifficultiesinherentinsupportingmultipletargets.Idescribeaspecification-basedapproachforgeneratinginterfacecompilers,discusstheadvantagesofsuchanapproachoveraproceduralapproach,andout-lineaproposedimplementation,withparticularreferencetotheadvantagesofaspecification-basedapproachtoin-terfacecompilationintermsofflexibilityandextensibility.

I.Introduction

Withanysystemsprogrammingtaskcomesituationsin-volvingcodethatcouldeasilybemachinegenerated.Aparticularlygoodexampleofthisinmicrokernel-basedsys-temsisinthecoderequiredforcommunicationofmessagesacrossaninterfaceboundary.Suchcodeisnotstrictlyboil-erplate,becauseitvarieswiththedatalayoutofthemes-sagebeingsent,buttheinterface-specificdifferencescaneasilybedescribedprogrammatically.Usingacodegen-eratorisnotnecessarilytherightchoice:addinganotherlayerofabstractiontothecommunicationprocessmakesdebuggingmoredifficultandencouragesnewprogrammerstoignoretheintricaciesoftheunderlyinginterface(theso-calledleakyabstractionproblem[1]).However,codegener-atorsmakeupfortheseshortcomingsinmanyways.Forexample,severalclassesofbugsarenotpossibleingener-atedcode,andallcodemakinguseofthesameinterfacewillcommunicateacrossitinthesameway.

Automatingtheprocessrequiresatoolcapableofpro-ducingcodefromaspecification,usuallyaninterfacecom-piler.Thisspecialisedtoolparsesaninterfacespecification,usuallyinaformofInterfaceDefinitionLanguage(IDL),andproducesoutputinthelanguageusedtoimplementtherestofthesystem(thetargetlanguage),typicallyintheformofstubfunctions.Codeonthecallersideoftheinter-faceusesthesestubslikeanyotherfunction:theworkofpackingfunctionparametersintoanappropriatelocationinmemory(marshaling),communicatingusinganappropri-NationalICTAustraliaisfundedbytheAustralianGovernment’sDepartmentofCommunications,InformationTechnology,andtheArtsandtheAustralianResearchCouncilthroughBackingAus-tralia’sAbilityandtheICTResearchCentreofExcellenceprograms.

ateoperatingsystemprimitive,andextractingtheresultsfrommemoryandreturningthemtothecallingfunction(unmarshaling)isperformedbythestub.Interfacecom-pilersproduceappropriatemirrorstubfunctionsfortheservicesideoftheinterface,andmayalsoproduceskeletalcodeforaserverloopimplementingtheinterface.

Interfacecompilersareusedinmanyareasofcomput-ing.Serversanddistributedsystemsmaymakeuseofacomponentsystemofwhichstubcompilationisonlyaverysmallpart,suchasanimplementationofCORBA[2],COM[3],orJavaBeans[4].Allthesecomponentsystemssupportdistributionacrossanetworkinadditiontoother“enterprise”featuressuchasloadbalancingandqualityofservice.Inmicrokernel-basedsystems,bycontrast,spaceandefficiencyconstraintstendtoresultintheneedforsafecross-domaincommunicationwithouttheoverheadsofatraditionalcomponentsystem.Inthissituation,mostoftheworkisperformedinstubsproducedbyaninterfacecompiler.

Interfacecompilersformicrokernel-basedsystemsarethefocusofthispaper.Inadditiontomissingmanyofthefea-turesdescribedabove,typicalinterfacecompilersinthiscategorydifferfromtheirenterpriseequivalentsintwoma-jorways:theygenerallyproducesimplercode,becausethemicrokernelperformsthetasksofmessage-passingandqueueingandthusactsasa(partial)objectrequestbroker;andtheyaremorelikelytoberequiredtoproducemultipletypesofoutput,evenforthesamemicrokernel,becausetheprimaryconcernofmicrokernel-focusedinterfacecompilersistoproducefast,asopposedtofeature-complete,code.Historically,theseinterfacecompilershavebeenheavilytiedtotheirattendantmicrokernel.Forexample,theMachInterfaceGenerator(MIG)[5]acceptsaMach-specificin-terfacespecification,produceshighlyMach-specificcode,andcouldnotreasonablybeusedwithanotherkernel.Morerecently,interfacecompilerscapableofacceptingvar-iousIDLsandsupportingmultipletargetlanguageshaveemerged.TheseincludetheFlexibleIDLCompilerKit(Flick)[6],whichsupportsIDLssuchasCORBAIDLandONCRPCatthefrontend,andtargetsMach[7]andvar-iousincarnationsofL4[8]atthebackend.Flickachievesthismodularitythroughaseriesofprogrammer-visiblein-termediatelanguages(fiveintotal)whichcanbeoperatedonindependently.

Changesinthedesignofaninterfacecompileraretypi-callymadeeithertoimproveperformanceorimprovegener-

Fig.1.StagesintheMagpieinterfacecompiler

ality.However,interfacecompilersformicrokernelsremainremarkablydifficulttoadapttochanginginterfacerequire-ments.Therearethreemajorreasonsforthedifficulty:firstly,theytendtoremaintightly-coupledtoasmallse-lectionofkernels;secondly,thecoreinterface-generationroutinestendtobedifficulttomodify;and,finally,repre-sentationoftargetcodeisprimitivecomparedwiththatofferedbysource-to-binarycompilers.

IntherestofthispaperIdescribeextensibilityissuesandtheirvarioussolutionsincurrentinterfacecompilers.Ithenproposeanalternativeinterfacecompilerdesign,mak-inguseofspecification-directedtransformations,anddis-cusstheadvantagesanddisadvantagesofthisapproach.AlthoughIrefertoseveralpopularinterfacecompilers,thefocusisonaddingadeclarativelayertoMagpie,aninter-facecompilerusedwithNICTAL4.[9]

II.Interfacecompilers

Likesource-to-binarycompilers,interfacecompilersareallcomposedofatleastafrontend,containingtheparserforthespecificationlanguage,andabackend,containingthecodegeneratorforthetargetsystem.Itiscommontomakeuseofatleastoneintermediaterepresentation.Figure1showsthemajorstagesoftheMagpieinterfacecompiler.

Source-to-binarycompilersmaysupportmultipleplat-forms,butthetargets(platform-specificassemblylan-guages)areallverysimilar;intermediatestagesthereforeoutputsomevarietyofthree-addresscode[10],whichisbydesignquitehomogeneous.Theintermediatestageofaninterfacecompiler,however,musttargetsomehigher-levellanguage,suchaC,workingwithakernelorlibraryAPI.Unlikeprocessorassemblylanguages,kernelorlibraryAPIsareverydissimilar,evenwhendesignedforthesametask(i.e.,communicationbetweenthreads).Designinganef-fectiveintermediatestageforaninterfacecompileristhussimplyahardertask,becauseofhigherdegreeofcross-platformvariation.Acommonresponseininterfacecom-pilerdesignhasbeentoblurtheseparationbetweenin-termediatestagesandfinalcodegeneration,resultinginintermediatestageswhicharecomplicated,inflexible,orboth.

Furthercomplicatingthetaskoftheinterfacecompilerarethefrequently-changingrequirementsofapplicationsandthekernel,aparticularlysevereproblemforresearchsystems.Forexample,NICTAL4hasundergoneseveralinternalAPIchanges,eachonenecessitatinganequivalent

changetotheinterfacecompiler.Thedifficultyofimple-mentingthesechangesinthepopularIDL4interfacecom-pilerhasledtothedevelopmentofMagpie,aninterfacecompilerbasedonaflexibletemplatesystem.ThepartialsuccessofMagpieinthisregardistheprimemotivationfortheworkdescribedinthispaper.A.Codetransformation

Therealworkofaninterfacecompilerisperformedbytheintermediatestageknownasthegenerator,whichanal-ysestheinternalrepresentationoftheinterfacedefinitionandproducesoutput(eitherinthetargetlanguage,orinanintermediateformat).Inmoderninterfacecompilers,thegeneratorformsathirdstagebetweentheparserandcodeoutputstages,allowingforsomedegreeofflexibilitywithregardtoinputandoutputformats.Nonetheless,makingsizeablechangestotheformatoftheoutputrequiresmodi-fyingthegenerator,andherechoiceoflanguageandgener-atordesignbecomeimportant:inmanycommoninterfacecompilersformicrokernels,suchasFlick,IDL4,andDICE,makingevensimplechangesrequireschanginganontrivialamountofcode.B.Codeoutput

Codeoutputiswidelyregardedtobeaneasyproblemandisthusgivenlittleattentionduringinterfacecompilerdevelopment.Indeed,itiseasy(inthesensethatlittledesignisrequired)tocreateasimpleinterfacegeneratorthatgeneratesappropriatecodeforafixedinterface,tiedtoasinglemicrokernel.However,thereareseveralproblemswiththisapproachthatbothlimitthescopeofinterfacecompilersandincreasetheirmaintenanceoverhead.

Typically,aninterfacecompilerbackendiscomposedofaseriesofprintfstatementswhichtogetherproducetheentirestubfunctionormodule.Thisapproachissimpletoimplement,andtheintentofthecodeisobvious,butitisdifficulttoextendandtotest.Alternatively,theback-endmayassembleasyntaxtreeinthetargetlanguage,whichisthenwalkedasafinalsteptoproducesourcecode.Thisapproachatleastprovidessomereassurancethatthegeneratedcodewillbesyntacticallycorrect,buttheusualmethodofassemblingthetreeinaprocedurallanguage,callingclassconstructors,isdifficulttofollow,anddifficulttoextend.

Beforeconsideringparameterisedtemplatesitisimpor-tanttoconsiderboilerplatecode,thatis,codewhichdoesnotchangebetweeninvocationsofthecompiler.Gener-atedcodetypicallycontainsalotofboilerplateintheformofheadercomments,error-handlingcode,helperroutines,etc.Atypicalproceduralapproachtogeneratingthissortofcodeissimplytoinsertitatappropriatepointswhenproducingoutput.Thislooksuglyforasystemthatusesprintf-styleoutput,andpracticallyunreadable(ifitoc-cursinlargechunks)inasystemthatgeneratesaconcretesyntaxtreeon-the-fly.Ineithercase,boilerplategener-ationissimplynoiseforamaintainerattemptingtoun-derstandwhattheinterfacecompilerdoes.Thesituationgetsworseiftheprogrammerwishestoextendthesystem,

1addTo(result,newCASTDeclarationStatement(2newCASTDeclaration(

3newCASTTypeSpecifier(

4newCASTIdentifier(\"L4_ThreadId_t\")),5newCASTDeclarator(

6newCASTIdentifier(\"_dummy\"))))

7);

Fig.2.Variabledeclaration,IDL4

1L4_MsgTag_t_result;2/*-run(templates.get(

’client_function_body_pre_ipc_defs’))-*/...

3/*-run(templates.get(

’client_function_body_pre_ipc’))-*/4_result=L4_Call(_service);5/*-run(templates.get(

’client_function_body_post_ipc’))-*/

Fig.3.AnexampleoftheMagpietemplatinglanguage

perhapswithanewoutputmode.Sheisthenpresentedwithtwooptions:tocopythecode,creatingtheopportu-nityforunwanteddivergenceinthefuture;ortorefactorthecodetobemorefine-grained,makingflowlessobviousandprovidingnoguaranteethatadditionalchangeswillnotnecessitatefurtherrefactoringinthefuture.

Thedifficultiesassociatedwithcodegeneratedpiece-mealaremagnifiedforsectionsofparameterisedcode,i.e.,thesectionsofcodeinwhichthegeneratoractuallyper-formswork.Usingasyntaxtreeapproach,asinglelineof(relatively-simple)generatedcodeconsumesapproximatelysixlinesofgeneratedAST(abstractsyntaxtree)inIDL4.Figure2,extractedfromIDL4,createsanewtypeinstanceusingmultipleclassestoconstructanabstractsyntaxtree,whichislaterwalkedtoproduceoutput.Theexamplein

thefigureistheequivalentoftheCcodeL4

tCall()function,whichperformssynchronous

IPCinL4.Beforeandafterthecall,additionaltemplatesareexecutedusingtherun()function(lines2,3,and5).Thesetemplatesmaygeneratecodethatperformsaddi-tionalworktosupporttheIPCoperation.Forexample,inNICTAL4,asynchronousIPCnotificationsmustbedis-abledontheclientsidepriortoasynchronousIPCcall.

Codegeneratedbytheclient

bodyCall()completes.TheCcodeforthisfunction-alityisshowinFigure4.

Therun()commandisaconvenientextensibilitymech-anism,butconvolutestheflowofthetemplate,contrarytothestateddesigngoals(specifically,understandabilityofthebackend).Intheexamplegivenabove,fourseparatesourcefilesarerequiredtoproperlydisableandre-enableasynchronousIPC.

Magpie’stemplatingapproachisatbestonlypartiallysuccessful.Codeflowispreserved(theaboveexamplenotwithstanding),butthetemplatedcodeisdifficulttoread,anddoesnotgetsignificantlyeasierasonebecomesmorefamiliarwiththesystem.Thetemplatesarenotstand-alone:tounderstandthesystemonemustalsobefa-miliarwiththeprocedural-codegeneratorwithwhichthetemplatescommunicateand,insomecases,theabstractsyntaxtreecontainingtheparseddata.PerhapsthebestproofofboththesuccessandfailureofMagpieisthefactthataftermorethanayearofuse,manydifferenttemplatesweresuccessfullydevelopedtoaccommodatechangingre-quirements,butthesoledeveloperofnewtemplateswastheimplementorofMagpie.

III.Aspecification-basedapproach

Theinterfacecompilersdiscussedintheprevioussec-tionsalluseaproceduralapproachtoperformcodegener-ation.Thatis,aprogramwritteninaprocedurallanguage(commonlyCorC++)examinesanASTcreatedbythefrontendandgeneratescodeinthetargetlanguage,ifthecompilerdoesnotincludeaseparategenerator,oranin-termediaterepresentation,ifitdoes.Thisapproachman-agestobebothtoogeneral-purposeandtooinflexible:aprogrammerwishingtomodifythebehaviourofthestubcodemustbecomeveryfamiliarwithinterface-compilerin-ternals,andmustmodifyanontrivialamountofcodetoextendthesystem.

Theuseofaprocedurallanguagetowritethegenera-

Fig.5.MagpieandCurrawong

torsectionoftheinterfacecompilerisanobviouschoice,becausetherestoftheinterfacecompileristypicallyimple-mentedinaprocedurallanguage.However,aproceduralapproachresultsincomplicated,verbosegeneratorcode.Thecoreofaninterfacecompilerisessentiallyatree-to-treetransformation.Inthissection,Idemonstratethatusingadeclarativelanguageconfersseveralbenefitsoverthestandardapproach,particularlyintheareasofcodesize,understandability,andextensibility.Thedesigncom-prisesasetofmodificationsandextensionstotheMagpieinterfacecompiler,resultinginanewinterfacecompilernamedCurrawong.A.CurrawongandMagpie

CurrawongreplacesmostofMagpie’sgeneratorandtem-platingsections,asshowninFigure5.Magpie’sfrontendparserandgeneratorsarepreserved.Theintermediateandbackendlayersarecombinedtoformadeclarativeprocess-inglayer.TheoutputfromthislayerisessentiallyanAST,soafinalsmallstagewalksthetreetoproduceoutput.B.Proceduresanddeclarations

Asdiscussedabove,interfacecompilersarecomplicatedatleastpartlybecauseofthestrongrelationshipbetweenthetargetlanguageandcompilersforthatlanguage–suchasCandthegcccompiler.Inshort,thespecificationofanylanguagemappingmustnecessarilyconflateinterface-leveldetails,suchasthelayoutofdatainmemory,andlanguage-leveldetails,suchastheappropriatecasts,bitwiseshifting,andlogicaloperationsrequiredtocreatethislayout.Thisproblemcannotbeavoidedcompletely–atsomepoint,wemustspeakthetargetlanguage–butitsimpactongeneratorextensibilitycanbeminimisedbyseparatingthelevelsofspecification.Referringtothepreviousexample:ifagivenplatformrequiresthatparametersbemarshaledintoacertainlocationinmemory,itisplausiblethatonemaydesiretochangethemarshallocationofagiven64-bitintegerinaninterface-definedfunction,butlesslikelythatonewouldwishtochangethefactthat,inC,thelow-order32bitsofthiswordmaybeaccessedusing“theword&0xFFFFFFFF”.

Acommonresponsetothespecificationrequirementhasbeentoperformexactlytheseparationdescribedabove.TheFlickinterfacecompiler,forexample,usesfiveseparateabstractrepresentationsforlanguage-levelandinterface-levelrequirements.However,thesefiveabstractrepresen-tationshavebeendeterminedbytheimplementorsofFlick.Theycan,therefore,notbeeasilymodifiedtoaccommo-

typedefunsignedintcounter_t;typecounter_t(1,example.h:1)(meta_type)=[’alias’](indirection)=[’’]target(2,?:?)

typeunsignedint(backref)

Fig.6.AsimpleCtypedefanditsASTrepresentation

datelevel-spanningproblems,andarethusinflexible:toagainrefertotheparameter-passingexampleabove,onemaymakearbitrarychangesatthelevelofdeterminingthenamesandtypesofparameterstobemarshaled,butthelayoutandorganisationofparametersisonlyaccessi-bleatthelowestlevel,CAST,whichessentiallyencodesaC++abstractsyntaxtree.Otherinterfacecompilerstacklethesameproblemusingahighly-stratifiedgeneratorandrelyonthelanguagefeaturesoftheirinterfacecompiler’slanguagetosupplyextension.Forexample,theIDL4andDICEcompilers,writteninC++,stratifytheirgeneratorsintothegeneratorproperandasmallersectionthatsepa-ratesmessagesintochannels,allowingmessageordertobechangedthroughinterfaceinheritance.

IntheCurrawongsystem,thegeneratorappliesaseriesoftransformationstoacodetemplatewritteninthetar-getlanguageinordertotransformthetemplateintoanappropriatestubfunction.The“meat”ofthetransforma-tionsystemisspecifieddeclarativelyinPrologand,duetothetemplate,onlythetransformationsnecessarytocus-tomisethetemplatetoaparticularinterfacearespecified.Thesetwocharacteristicscombinetomakethecustomis-ableaspectsofthetransformationsystemverycompactandunderstandable.C.Typemanagement

Inordertocompileaninterfacedefinition,itmustfirstbeparsedandconvertedtoaneasy-to-manipulateform.IntheMagpieinterfacecompiler,theprimarydatastructureisanabstractsyntaxtreeproducedbythefrontend.AnexampleofthisstructureisshowninFigure6,withtheCcodethatitrepresents.Magpiecanmakeuseofanytypedeclarationpresentedinitsfrontendand,therefore,typesdefinedintheinterfacedefinitionfile,andtypesdefinedinanyincludedCfiles,areinterchangeable.

RepresentingMagpie’sASTinCurrawongisasimplematteroftransformingtheAST,producingidiomaticPro-lognestedstructures.AnexampleisshowninFigure7.Somesimplificationmaytakeplace:ASTnodesrepresent-ingaliastypes(suchasthosedefinedbytypedefinC)includeadirectreferencetothetargettypeofthealias(strictlyspeaking,the“AST”isactuallyadirectedacyclicgraph)buttheconvertedrepresentationdoesnot.Nodeattributes(meta

type(alias(counter_t,name(unsignedint)))

Fig.7.AsimpleCtypedef,Prologsyntax

Forexample,allCtypedeftypesmaybematchedusingthePrologtermtype(alias(Name,Type)).D.Specificationlanguage

TheCurrawongspecificationlanguageisadeclarativerepresentationofthegeneratorpresentinotherinterfacecompilers,suchasFlick,IDL4,andMagpie.AgeneratorintheCurrawongsyntaxisaseriesofdeclarations,eachonerepresentingasinglecodetransformation.

Ingeneral,acodetransformationmaybedescribedasconsistingofthreeparts:amatchrulethatlocatesthedesiredportionofcode,asetofrequirementswhichservestodeterminewhetherthecodeiscorrectwithregardstothetransformation,andatransformationrulewhichmaybefollowedtotransformthematchedcodeandmakeitsatisfytherequirements.InCurrawong,thesethreepartsareseparatedusingaminorextensiontoPrologsyntax,aspertheexampleshowninFigure8:asyntaxmarkerconsistingoftwocolonsseparatesthematchrulefromtherequirements.Inotherregards,thesyntaxisProlog.Inthecurrentexperimentalprototype,Currawongincludesitsowninterpreterforthislanguage,whichisessentiallyacustomPrologimplementationwiththeaboveextension.Afuture,morecomplete,versionofCurrawongwillsupportoneormoreopen-sourcePrologimplementations,suchasSWI-PrologorGNUProlog,instead.

MatchingofrulesandrequirementsisperformedusingthePrologunificationmechanism.Atransformationiscon-sideredcompletewhen,foreachitemmatchedbyamatchrule,thecorrespondingsetofrequirementsalsomatches.ReferringtotheexampleinFigure8,anysetofparametersismatched,andtheparameterlistisboundtothePrologvariableP.Thenlist

Wordservice.

Ifamatchruleisencounteredforwhichthecorrespond-ingrequirementsdonotmatch,codetransformationisper-formed.Codetransformationproceedsasfollows:

1.Takethefirstrequirementfromthelistofrequirements.2.Findthecorrespondingtransformationrule,whichistherulewhosefunctorstartswithmatch

Wordserviceasafirstparameter,thelistis

parameters(P)::list_head(P,

parameter(’L4_Word_t’,’_service’).list_head([H|T],H).

make_list_head(List,H,Result)

:-Result=[H|List].

Fig.8.AnexampleofCurrawongrulelanguage

mutatedbyacalltomakehead,andtheASTisup-dated.

Notethatthematchruleandrequirementsresideinthesameclause,oneithersideofthedouble-colonseparator–collectivelynamedthematch/requirementsclause.How-ever,thetransformationruleisaseparateclause.Thisisbecauseitisappropriatethatthetransformationrule,be-ingfarmoregeneral-purposethanthematch/requirementsclause,resideinaseparatesystem-widelibraryofmanip-ulationrules.

GiventhatCurrawongparsesatemplateandappliesitstransformationstothetemplate,thereisagreatpoten-tialforreductionofcodesizeviaeliminationofboilerplatecode.Ineffect,Currawongstatementsactasasortofas-pectlanguageforaspect-orientedprogramming(AOP)[11],specifyingtransformationsthroughmatching.Prologisanidealchoiceforanaspectlanguage,becauseitiswell-suitedtothetypesoftasks,specificallysearching,thatformalargepartofanyaspectlanguage.

IV.Examples

Thissectiondescribessomeexamplesforwhichadeclar-ativecode-transformationapproachiswell-suited.A.L4notificationmask

Manysuperficialchangestonon-parameterisedcodecanbemadesimplybychangingthecodeitself.Forexample,asynchronousnotificationwasrecentlyaddedtoNICTAL4.Itisundesirableforasynchronousnotificationstoar-riveduringasynchronousIPC,sotheyshouldbedisabledpriortotheIPCandre-enabledsubsequently,asdiscussedinSectionII-C.AnexampleCurrawongimplementationisshowninFigure9.AlthoughthisdeclarationeffectivelygeneratescodetomanageasynchronousIPC,itisessen-tiallyacorrectnesscheck,andcanbeusedassuch.

ItisworthwhiletocomparethedeclarativespecificationwiththeimplementationofthesamefunctionalityinMag-pie(Figure3).InMagpiethecodeisdistributedoversev-eraltemplates,including“hooks”(therun()command)inthebasetemplate,buttheCurrawongimplementationhastheformofanaspectintheAOPsense:boththebasecodeandtheaspectarewell-separated,andsignificantchangesmaybemadetothebasecodewithoutanyknowledgeoftheasynchronoussupport.Infact,thesortsofchangesthatwouldrequireknowledgeoftheasynchronousIPCsupportarethosethatwouldrequirerewritingthesupportanyway,suchasadecisionnottouseL4

context(expression(call(L4_Call,_)),

Before,After)::

list_contains(Before,expression(

equals(Var,call(set_notifymask(0))))),list_contains(After,expression(

call(set_notifymask(Var)))).

Fig.9.Acurrawongdeclaration:managingasynchronousIPC

1function(iguana_pd_pypd,_,Body)::2%Ensurethatwedeclarethestatic.3list_contains(Body,expression(typeinst4(’staticuintptr_t’,’mypd’,0))),56%Returnearlyifthestaticis7%initialised.8context(expression(call(L4_Call)),9Before,After),10list_contains(Before,if(expression(11notequals(mypd,0),12expression(return(mypd)))),13%Initialisethestaticafterthecall.14list_contains(After,expression(15equals(mypd,__retval))

Fig.10.Aninterface-specificoptimisationrule

B.Interface-specificoptimisations

Thepreviousexamplesdemonstratedflexiblecreationofgenericinterfacecompilers.However,notallinterfacesarethesame,andsomemaybenefitfrominterface-specificcus-tomisations–optimisationsinparticular.

Asimpleexampleoccurswhencaching.TheIguanaL4OSpersonalityseparatesthreadsintoprotectiondomains,wheretwothreadsindisjointprotectiondomainsmaynotsharedata.Athread’sprotectiondomainidentifierisrep-resentedbyanonzerointegerwhichthreadsmayobtain

usingtheiguana

mypd()function.Thisintegerdoesnotnotchangeoverthethread’slifetime.Itmightmakesense,then,toincludeadeclarationtoperformcachingontheiguanamypdinterfacefunction,whichreturnsathread’sprotectiondomainidentifier.Suchanoptimisa-tionruleisshowninFigure10.ThisruledeclaresastaticvariabletocachetheresultofanIPCcall(lines3and4),checkstoseeifitcanreturnthestaticbeforemakingthecall(lines8to12),andsetsthestatictotheresultofthecallafterwards(lines14and15).ThePrologrepresenta-tionoftheCcodeissomewhatverbose–apossiblesolutiontothisaestheticproblemisdiscussedinSectionV.

V.Relatedwork

ThedescriptionofCurrawongaboveincludesanexam-pleofinterface-specificoptimisationinC.Approachesfornon-microkernel-basedsystemshavefocusedlessonper-interfaceoptimisationandmoreonper-languageoptimi-sation.TheConcertSignatureRepresentation[12]doesnotmakeuseofanexplicitinterfacedefinitionlanguage,

butallowsdefinitionofaninterfaceusingthetargetlan-guage’sowndefinitionsub-language(forexample,func-tionprototypesinC)withextensions.Itthenreliesonadeclarativemini-languagetospecifythetypeandloca-tionofeachparameter,inasimilarfashiontoCurrawong’sdeclarativelanguage.TheexperimentalinterfacegeneratorMockingbird[13]arrivesatasimilarsolutioninadifferentway.Recognisingthattheidealpresentationofaninter-faceinC++isverydifferenttoanidealpresentationofthesameinterfaceinJava,Mockingbirdallowsprogrammerstohand-definetheidealinterfaceinbothlanguages,anden-surescorrectnessbycompilingbothinterfacestoitsownunambiguousinternalinterfacedefinitionlanguageanden-suringthattheinternalrepresentationsforbothinterfacesarethesame.

Microkernel-focusedsystemsconcentratemoreonper-interfacecustomisation.Fordetal.[14]discusstheimportanceofseparatinginterfacepresentation(theprogrammer-facingsideoftheinterface;essentiallythestubcodesignature)fromtheinterfacecontract(thedatathatmustbetransferred)anddescribeasmallspecificationlanguagetocustomisethepresentationforaninterfacegen-eratorfortheMachmicrokernel.

Currawongisnotthefirstdesigntomakeuseofdecla-rationstoperformprogrammodification,knownaslogicmetaprogramming.TheTyRuBasystem[15]isatoolforaspect-orientedprogramminginJava(aweaver)inwhichaspectsarespecifiedinavariantofProlog.Theauthorsclaimthatthisapproachallowseasyextensionsoftheas-pectlanguage.AninterestingfeatureofTyRuBanotcur-rentlyincorporatedintotheCurrawongdesignistheabilitytoembedportionsofthetargetlanguagedirectlyintoas-pectdeclarations.Judicioususeofsuchafeaturecouldsimplifyblocksofcodewithfewexternaldependencies,suchastheoptimisationexamplegivenabove.Ifthetar-getcodewereparsedbyaCurrawongimplementation,itcouldalsosimplifyexamplessuchasthefirstone,allowingallrulestobewritteninplainC.

VI.Limitationsandfuturework

Asmentionedabove,informationislostwhentypeinfor-mationisconvertedfromtheASTrepresentationsuppliedbytheparsertoProlog-styledeclarations.Thisinforma-tion,whichincludeslinenumberinformation,maybeuse-fulwhenreconstructingmodifiedfiles.Thisinformationmayberestoredinseveralways.PerhapsthemostobviousissimplytostoretheinformationasadditionalattributesinthedatastructurerepresentingaPrologatomornode.Theextrainformationcouldthenbeaccessedusingbuilt-inpredicates.

Haeberlenetal.[16]implementedanumberofoptimi-sationswhendesigningtheL4-specificinterfacecompilerIDL4.Whilesomeofthese(suchasthedirect-stacktrans-fer)arearchitecture-specific,itwouldbeinformativetoimplementtheseoptimisationsintheframeworkofCurra-wong,todeterminewhicharefeasibleinthatcontext.Al-thoughIsuspectthecompletedCurrawongimplementationtorunrelativelyslowlyinitsfirstincarnation,theruntime

speedofthegeneratedstubcodeshouldbeentirelydepen-dentontheinputpassedtoCurrawong–transformationsperformedinsideCurrawongshouldnothaveanimpactonstubperformance.

AlthoughmostofthesectionsnecessarytoimplementtheCurrawongextensionstoMagpiearecomplete,someimplementationworkisstillrequiredtoproduceaworking,testableinterfacecompiler.

VII.Conclusion

Interfacecompilers,particularlyinterfacecompilersformicrokernel-basedsystems,havesomeunusualrequire-mentsforwhichtraditionalcompilertechniquesarenotparticularlywell-suited.Therequirementtosupportalargearrayoftargets,andtodosousingarelativelyhigh-levellanguage,createsuniqueproblemsandhasproducedavarietyofnovelsolutions.Theuseofadeclarativelan-guage,combinedwithaspect-orientedtechniques,hasthepotentialtoreducethecomplexityandoverallsizeofaninterfacecompilergenerator,andisworthyoffurtherex-plorationandimplementation.

References

[1][2][3][4][5][6]

JoelSpolsky,“Thelawofleakyabstractions,”http://www.joelonsoftware.com/printerFriendly/-articles/LeakyAbstractions.html,2002.

ObjectManagementGroup,“CORBA3.0.3,CommonObjectRequestBrokerArchitecture(CoreSpecification),2004-03-01,”2004.

MicrosoftCorporationandDigitalEquipmentCorporation,TheComponentObjectModelSpecification,1995.

SunMicrosystems,“Javabeans:AcomponentarchitectureforJava,”1996.

OpenSoftwareFoundationandCarnegieMellonUniversity,Mach3ServerWriter’sGuide,Jul1992.

EricEide,KevinFrei,BryanFord,JayLepreau,andGaryLind-strom,“Flick:Aflexible,optimizingIDLcompiler,”inSIG-PLANConferenceonProgrammingLanguageDesignandIm-plementation,1997,pp.44–56.

MikeAccetta,RobertBaron,DavidGolub,RichardRashid,AvadisTevanian,andMichaelYoung,“MACH:AnewkernelfoundationforUNIXdevelopment,”Tech.Rep.,CarnegieMel-lonUniversity,ComputerScienceDept.,Pittsburgh,PA,USA,1986.

JochenLiedtke,“Onmicro-kernelconstruction,”inSOSP1995,CopperMountain,CO,USA,Dec.1995,pp.237–250.

GernotHeiser,“Secureembeddedsystemsneedmicrokernels,”in;login:,USENIX,Dec.1995.

AlfredV.Aho,RaviSethi,andJeffreyD.Ullman,Compil-ers:principles,techniques,andtools,Addison-WesleyLongmanPublishingCo.,Inc.,Boston,MA,USA,1986.

GregorKiczales,JohnLamping,AnurangMendhekar,ChrisMaeda,ChristinaLopes,Jean-MarcLoingtier,andJohnIrwin,“Aspect-orientedprogramming,”ACMComput.Surv.,vol.28,no.4es,pp.154,1996.

JoshuaS.AuerbachandJamesR.Russell,“TheConcertSig-natureRepresentation:IDLasintermediatelanguage,”ACMSIGPLANNotices,vol.29,no.8,pp.1–12,1994.

JoshuaS.Auerbach,CharlesBarton,MarkChu-Carroll,andMukundRaghavachari,“Mockingbird:Flexiblestubcompila-tionfrompairsofdeclarations,”inInternationalConferenceonDistributedComputingSystems,1999,pp.393–402.

BryanFord,MikeHibler,andJayLepreau,“UsingannotatedinterfacedefinitionstooptimizeRPC,”inSymposiumonOper-atingSystemsPrinciples,1995,p.232.

KrisDeVolder,“Aspect-orientedlogicmetaprogramming,”inMeta-LevelArchitecturesandReflection,SecondInternationalConference,Reflection’99,PierreCointe,Ed.1999,vol.1616ofLectureNotesinComputerScience,pp.250–272,SpringerVerlag.

[16]AndreasHaeberlen,JochenLiedtke,YoonhoPark,LarsReuther,

andVolkmarUhlig,“Stub-codeperformanceisbecomingimpor-tant,”inProceedingsofthe1stWorkshoponIndustrialExpe-rienceswithSystemsSoftware(WIESS),Berkeley,CA,2000,USENIXAssociation.

[7]

[8][9][10][11]

[12][13]

[14][15]

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- sarr.cn 版权所有

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务