Extending a User Interface Prototyping Tool with Automatic MISRA C Code Generation GioacchinoMauro DepartmentofInformationEngineering,UniversityofPisa,Pisa,Italy [email protected] HaroldThimbleby SwanseaUniversity—PrifysgolAbertawe,Swansea/Abertawe,UK [email protected] AndreaDomenici CinziaBernardeschi DepartmentofInformationEngineering,UniversityofPisa,Pisa,Italy {cinzia.bernardeschi,andrea.domenici}@unipi.it Weareconcernedwithsystems,particularlysafety-criticalsystems,thatinvolveinteractionbetween usersanddevices,suchastheuserinterfaceofmedicaldevices. WethereforedevelopedaMISRAC code generator for formal models expressed in the PVSio-web prototyping toolkit. PVSio-web allowsdeveloperstorapidlygeneraterealisticinteractiveprototypesforverifyingusabilityandsafety requirementsinhuman-machineinterfaces. Thevisualappearanceoftheprototypesisbasedona pictureofaphysicaldevice,andthebehaviouroftheprototypeisdefinedbyanexecutableformal model. OurapproachtransformsthePVSio-webprototypingtoolintoamodel-basedengineering toolkitthat,startingfromaformallyverifieduserinterfacedesignmodel,willproduceMISRACcode thatcanbecompiledandlinkedintoafinalproduct. Aninitialvalidationofourtoolispresentedfor thedataentrysystemofanactualmedicaldevice. 1 Introduction Formalmethodsareimportantfordevelopingandunderstandingsafeandsecuresystems. ThePVSio-web framework [20, 21, 22, 26] allows developers to use formal methods in a friendly and appealing way asitprovidesrealisticanimationsandisintegratedwithagraphicaleditorfortheEmuchartslanguage [23]. (Emuchartsisastatemachineformalismwithguardsandactionsassociatedwithtransitions;itis explainedfurtherinSect.3.4below.) PVSio-web uses the formal modelling language of the Prototype Verification System (PVS) [27], includingthePVSioextension[24]. PVSisanindustrial-strengththeoremprovingsystemthatallows formalverificationofsafetyandreliabilitypropertiesofhardwareandsoftwaresystems[5,31]. Although PVS itself is very effective, it is not widely used for model-based development and analysis of user interfaces,asthetoolhasasteeplearningcurve. PVSio-websoftensthislearningcurve,makingthetool moreuser-friendlyandaccessible,providingdeveloperswithagraphicalmodellingenvironment,anda toolboxfordevelopingrealisticvisualprototypesofuserinterfaces. Theapplicationsofembeddedsoftwareinsafety-criticalapplicationsincreasecontinuously. Taking thisintoaccount,togetherwiththerequirementstoreducetimeandoverallproductioncosts,automatic code generation plays an essential role. Automatic code generation guarantees a smooth conversion C.Dubois,P.Masci,D.Méry(Eds.):F-IDE2016 EPTCS240,2017,pp.53–66,doi:10.4204/EPTCS.240.4 54 MISRACcodegeneration PVS environment PVSio−web Proof Theorem Prover Developer Emucharts PVS Model Editor Simulation Editor generator Ground Evaluator PVS theory HB Templates Emucharts C Code Model C Code Generator Figure1: CcodegenerationinthePVSio-webdevelopmentprocess. frommodeltocodeandreducesthedebuggingandtestingrequiredforsourcecode,providedthatthe correctnessofcodegenerationandofthehigh-levelmodelhavebeenverified. WethereforepresentanextensiontoPVSio-webthatgeneratesCcode. Specifically,ourextension generatesMISRAC[1],asafety-orientedsubsetofCdevelopedbytheMotorIndustrySoftwareReliability Association(MISRA). MISRACiscommonlyusedinsafety-criticalsubsystems,suchascarbrakingin automotivesystems. With this new extension, formal PVS specifications generated from Emucharts diagrams are auto- maticallyconvertedtoC,significantlyshorteningprojectdevelopmenttime. Becauseoftheapproach, thesemanticsofgeneratedCcodeisequivalenttotheformalmodels,andthereforethecoderetainsthe reliabilityandsafetypropertiesformallyverifiedforthePVSmodel. In summary, our main contribution is an approach to software development that integrates logic- andstatemachine-basedformalmodelling,validationbysimulation,andautomaticimplementationby generatingproductioncodetoberunontheactualsystemhardware,allbasedonanindustrial-strength formalmethodstoolkit. 2 Related work Model-basedapproachesarecommonlyusedinthefieldofhumancomputerinteraction,forexample[13]. Mostapproachesarefocusedondescribinguserinterfacesandtheirimplementationsatvariouslevelsof abstraction. Developersofuserinterfacesforinteractivesystemsalsohavetoaddressheterogeneityand adaptationtothecontextofuse. Forexample,in[29],amodel-baseddeclarativelanguageforthedesign ofinteractiveapplicationsbasedonWebservicesinubiquitousenvironmentswaspresented. Incontrast tothesefamiliarapproaches,thepresentworkproposesaframeworkenablingaformalverificationof userinteraction. Theframeworkismeantforsafetyanalysisofsafety-criticaldevicesandnotwithuser interfacedesignissuesasdiscussedin[29], Similarlytoourapproach,formalmodelswereusedin[6]todescribefunctionalityandcomponent interactions,wheretheywerecombinedwithuserinterfacemodelsinordertogettheentiremodelofthe G.Mauro,H.Thimbleby,A.Domenici&C.Bernardschi 55 system. Moreover,anAndroidemulatorapplicationwasgenerated,usingJavaandXMLtechnologies. Presentationmodelsandpresentationinteractionmodelswereusedin[9]tomodelinteractivesoftware systems;thesemodelswereshowntobeusablewithaformalspecificationofthesystemfunctionality. In [7]thesameformalismswereusedtomodelusermanualsofmodalmedicaldevices,provingthattheuser manualmaybenotalwaysconsistentwithactualdevicebehaviour. In [17], model checking was used to model and prove properties of specifications of interactive systemssothatpossiblyunexpectedconsequencesofinterfacemodechangescanbecheckedearlyin the design process. In [19], the complementary role of model checking and theorem proving in the analysisofinteractivedeviceswasconsidered. Recentwork[16]exploredthepathsthatauserwilltakein interactingwithmedicaldevicesfortheanalysisofpropertiesofthebehaviourofsafety-criticaldevices. Amodel-checkingapproachhasalsobeenusedtoanalysehardwarebehaviour[4]. Adiscussionofproductioncodegenerationinmodel-baseddevelopmentcanbefoundin[11]. Many papers deal with specific code generators, for example TargetLink [3]. Code generators specifically designedformedicalsystemsaredescribedin[2]and[28]. 3 PVS, model-driven development and Emucharts This section provides background information on the PVSio-web framework and its relationship to model-drivendevelopment. 3.1 PVS,thePrototypeVerificationSystem ThePVSisaninteractivetheoremproverforatypedhigher-orderlogiclanguage,providinganextensive setofinferencerulesbasedonthesequentcalculus[30]. ItsPVSioextensionisagroundevaluatorthat cancomputetheresultsofgroundfunctionapplications,thatisPVSexpressionsconsistingofafunction nameappliedtovariable-freearguments. PVSfunctionsarepurelydeclarativedefinitionsofmathematical mappings, without any procedural information on how to compute them, but the PVSio package can derive and execute an algorithm to evaluate a ground function application, turning it into a procedure call. ThePVSiopackagealsoprovidesfunctionswithsideeffects,suchasinputandoutput,whichdonot interferewiththesemanticsofatheory. A system is modelled in PVS as a theory, a collection of logical statements and definitions about thestructuralandbehaviouralaspectsofthesystem. Thesystem’srequiredpropertiesareexpressedas theoremstobeverifiedwiththePVStheoremprover. Ifthebehaviouralaspectsareexpressedasfunctions, thesystemcanalsobesimulatedwiththePVSioextension. Thesamelogicalmodelcanthenbeused bothforverificationandsimulation. 3.2 Model-drivendevelopment Model-driven development (MDD) is based on creating an executable system model by assembling functionalblocks. Anexecutablemodelmakesitpossiblebothtosimulatethesystemandtogenerate production software to control it. Together with the naturalness of the graphic language of functional blocks,thesefeaturesmakeMDDveryattractivetodevelopers. However,thisapproachhastwolimits: first,functionalblockslendthemselvestobuildingdesignmodels,butnotspecificationones;andsecondly, formalverificationofablock-basedmodelistedious,andinfactitisuncommoninindustrialpractice. A formal approach can be used to create both specification and design models and intrinsically lends itself to rigorous verification of system properties. In particular, logic specification languages, 56 MISRACcodegeneration suchasPVS,aresupportedbyautomaticorinteractivetheoremproversusedbydeveloperstocheckif systemrequirements,expressedaslogicalformulas,areimpliedbyasystem’sdescriptionexpressedina logictheory. However,formalmethodsrequireexpertiseinlanguagesandmethodsthatarenotwidely known in the wider developer community. Further, most formal languages abstract from the familiar procedure-orientedcomputationmodelofpopularprogramminglanguages,makingithardertogenerate executablesoftware. Itisthendesirabletohavetoolsandmethodsprovidingdeveloperswiththefeaturesofbothapproaches. The present work is part of a research effort aimed at this goal. With the PVSio-web framework, a developercanbuildamodelinagraphicalstate-machinelanguageoralogiclanguage,orboth(Sect.3). Thegraphicalmodelistranslatedintothelogiclanguageautomatically,andtheresultingtranslationis both verifiable and executable using the PVSio ground evaluator, which acts as an interpreter for the PVS language. The PVSio-web framework thus provides features of the formal approach: A formal specification language and a verification tool, and features of MDD, thus providing a full graphical modelling language and a simulation engine. A translator from Emucharts to C makes it possible to generate code from a state machine-based model that can be validated by simulation and verified by theoremproving. TheotherimportantfeatureofMDD—generationofproductioncodecapabletobe runontheactualsystemhardware—isakeycontributionofthispaper. 3.3 PVSio-web ThePVSio-webframeworkisasetoftools,co-ordinatedbyaweb-basedinterface,forprototypingand simulationofinteractivedevices. Itsmaincomponentsare, besidesPVSwithitsPVSioextension: (i) thePrototypeBuilder, agraphicaltoolusedtochooseapictureofanexistingoranticipateddevice’s front panel and to associate PVS functions with active areas of the picture representing device inputs (e.g., buttons or keys) and outputs (e.g., alphanumeric displays or lights); (ii) the Model Editor, a textual interface to write PVS code; (iii) the Emucharts Editor, a graphical tool to draw Emucharts statemachinediagrams;(iv)aSimulationEnvironment;and(v)CodeGeneratorsforPVSandother formallanguages(currentlyPresentationInteractionModels[8],ModalActionLogic[15],andVienna DevelopmentMethod[12])—andforMISRAC,aspresentedinthispaper. PVSio-webcanbeusedtoprototypeanewdeviceinterface,ortocreateareverse-engineeredmodel ofanexistingone. Ineithercase,adevelopercreatesformaldescriptionsofthedevice’sresponsestouser actions,usingthemodelandEmuchartseditors,andassociatesthesedescriptionswiththeactiveareasof thesimulatedinterface,usingtheprototypebuilder. Inthesimulationenvironment,thedeveloper,ora domainexpertorapotentialuser,interactswiththeprototypeclickingontheinputwidgets. Theseactions aretranslatedtoPVSfunctioncallsexecutedbythePVSiointerpreter. 3.4 Emucharts An Emucharts diagram is the representation of an extended state machine in the form of a directed graph composed of labelled nodes and transitions. Transitions are labelled with triples of the form trigger[guard]{action},wheretriggeristhenameofanevent,guard isanenablingBooleanexpression, andactionisasetofassignmentstotypedvariablesdeclaredinthestatemachine’scontext. Thedefault guardisthetruevalueandthedefaultactionisano-operation. Thestateofthemachineisdefinedbythe currentnodeandthecurrentvaluesofthecontextvariables. The code generator for PVS produces a theory containing functions that define the state machine behaviourontheoccurrenceoftriggerevents. SinceanEmuchartsdiagramusuallyrepresentsadevice G.Mauro,H.Thimbleby,A.Domenici&C.Bernardschi 57 Figure2: ThePVSio-webuserinterfacewiththePrototypeBuilderandEmuchartsEditorframes. responsetouseractions,sucheventsrepresentuseractions,suchaspressingabuttononacontrolpanel. DuringsimulationonaPC,auserclickonanactiveareaofthedevicepicturecausesthesimulatorto generateafunctionapplicationexpressionthatispassedtothePVSiogroundevaluator. 4 From Emucharts to safe C The aim of programming code generation in the PVSio-web framework is producing a module that implements the user interface of a device, which can be compiled and linked into the device software withoutanyparticularassumptionsonitsarchitecture. Inthisway,theuserinterfacemodulecanbeused withoutforcingdesignchoicesontherestofthesoftware. Inourapproach,thegeneratedmodulecontains asetofCfunctions. Themainonesare,foreachEmuchartstrigger: (i)apermissionfunction,tocheckif thetriggereventispermitted,i.e.,whetheritisassociatedwithanytransitionfromthecurrentstate,and (ii)atransitionfunctionthat,accordingtothecurrentstate,updatesit,providedthattheguardcondition ofanoutgoingtransitionholds. Thecodeincludeslogicallyredundanttests(assertmacros)toimprove robustness. Togenerateproduction-qualitycodefitforsafety-criticalapplicationsweadoptMISRAguidelines. The MISRA guidelines for the C language, originally conceived for the automotive industry, enforce programmingpracticestoimprovemaintainabilityandportabilityand,aboveall, toreducetheriskof malfunctionduetoimplementation-orplatform-dependentaspectsoftheClanguage. Forinstance,there arerulesthatbartheuseofconstructssuchasgoto,andrulesrequiringthatnumericliteralsbesuffixed toindicatetheirtypeexplicitly. Thegeneratedcodecurrentlycomplieswiththefirstversionofthe1998 MISRACguidelines. 58 MISRACcodegeneration (cid:104)headerfile(cid:105) ::= (cid:104)preprocessor_directives(cid:105) [(cid:104)constant_definitions(cid:105)] (cid:104)typedef_definitions(cid:105) (cid:104)state_labels_enum(cid:105) (cid:104)state_structure(cid:105) (cid:104)utility_functions(cid:105) (cid:104)init_function(cid:105) (cid:104)permission_functions(cid:105) (cid:104)transition_functions(cid:105) Table1: Structureofaheaderfile. Non-terminalsymbolsareenclosedbetweenanglebrackets;square bracketsencloseoptionalsymbols. 4.1 Codegeneration OurMISRACcodegeneratorwasimplementedinJavaScriptusingHandlebars[14],amacro-expansion toolforwebapplications. AHandlebarstemplateisapieceoftextcontaining“Handlebarexpressions,” whichrefertoelementsofthesurroundingcontext,typicallyanHTMLdocument. AHandlebarsexpres- sionspecifiesacharacterstringasafunctionofcontextelements,whichiscompiledintoaJavaScriptfunc- tionthatreturnsthetemplatetextwiththesubstitutionscomputedbytheHandlebarsexpressions. Forex- ample,atemplatefragmentforaCpreprocessor#includedirectiveis#include "{{filename}}.h", wheretheHandlebarsexpression{{filename}}containsthefilenameparameterthatwillbereplaced bytheactualnameofthefiletobeincluded. Thecodegeneratorproducesaheaderfile,animplementationfile,amakefile,asimpletestdriverfile, andadocumentationmanual. ThestructureoftheheaderfileisdefinedbythegrammarinTable1. Theheaderfilecontains,among otheritems,thedeclarations(typedef_definitionsinthegrammar)fortypeswithexplicitrepresentation of size and sign, e.g., UC_8, for eight-bit unsigned char, the declaration (state_labels_enum) for an enumerationtypedefiningthenodelabels,andthedeclaration(state_structure)forthestatestructuretype representingthestateoftheEmuchartsmodel. Thisstructurecontainsonecontextfieldforeachvariable definedintheEmuchartscontext,andtwomorefields(curr_nodeandprev_node)containthelabelsof thecurrentandthepreviousnode. Thedeclarationsarefollowedbythefunctionprototypesofthetwoutilityfunctionsenterandleave, theinitfunction,and,foreachtrigger,onepermissionandonetransitionfunction. Thefunctionsreceivea pointertoastructureoftypestatepassedbyacallingprogram. Theenterandleavefunctions,calledby theinitandtransitionfunctions,updatethecurr_nodeandprev_nodefields,respectively,withthetarget andsourcenodelabeloftheexecutedtransition. Theleavefunctionhasbeenintroducedtoallowfuture versionstoimplementcheckpointingalgorithms. Theinit functioninitialisesthestate’scontextfields withthevaluesofthecontextvariablesspecifiedintheEmuchartsdiagram,andthecurr_nodefieldwith thelabeloftheinitialnode. Asmentionedabove,eachpermissionfunctionchecksifthecurrentnodehas atransitionlabelledbytherespectiveevent. Then,thematchingtransitionfunctionchoosesamongthe transitionstriggeredbythatevent,accordingtotherespectiveguards(assumedtobemutuallyexclusive). The implementation file contains the function definitions. For example, consider the Emucharts diagram of the data entry system of the Medtronic MiniMed 530G System shown in Figure 3. The diagramhasacontextvariabledisplayoftypedoublerepresentedon64bits,whichholdsthevalueshown onthedevice’sdisplay. Thenodelabelsandthestatetypearedefinedas G.Mauro,H.Thimbleby,A.Domenici&C.Bernardschi 59 Figure3: EmuchartsdiagramfortheMedtronicMiniMed530Gdataentrysystem. typedef enum { off, on } node_label; typedef struct { D_64 display; node_label curr_node; node_label prev_node; } state; Thecodeforthepermissionfunctionassociatedwiththeclick_UPtriggeris UC_8 per_click_UP(const state* st) { if (st->current_state == on) { return true; } return false; } where the return type UC_8 (eight-bit unsigned character) is used to represent the Boolean type. The transitionfunctionis state click_UP(state* st) { assert(st->current_state == on); assert(st->display < 10 || st->display == 10); if (st->display < 10 && st->current_state == on) { leave(on, st); st->display = st->display + 0.1f; enter(on, st); assert(st->current_state == on); return *st; } if (st->display == 10 && st->current_state == on) { leave(on, st); st->display = 10.0f; enter(on, st); 60 MISRACcodegeneration assert(st->current_state == on); return *st; } return *st; } AproofofthecorrectnessofthistranslationschemaisshowninAppendixA. 5 Case study TheAlarisGP,madebyBectonDickinsonandCompany,wasusedasacasestudyfortheMISRACcode generator. This volumetric infusion pump is a medical device used for controlled automatic delivery of fluid medicationorbloodtransfusiontopatients,withaninfusionraterangebetween1ml/hand1200ml/h. It hasamonochromedotmatrixdisplaywiththreesignificantdigits,andhas14buttonsforoperatingthe device(seeFigure4). Thepumphasarathercomplexuserinterface,withdifferentmodesofoperation andwaysofenteringdata,includingthepossibilityofchoosingfromalistofpreloadedtreatments. For simplicity,inthispaperonlytheessentialpartofthedataentryinterface,concerningnumericalinputand display,isconsidered. Numericalinputisdonethroughthechevronsbuttons: upwardanddownwardchevronsincreaseand decrease, respectively, the displayed value. The amount by which the value is increased or decreased depends on whether a single or double chevron is pressed, and on the current displayed value. More precisely, thedisplayed valueis changedas follows: (i)If thedisplayed valueis below 100, the value changesby0.1unitsforasinglechevron,andstepsupordowntothenextdecadeforadoublechevron (e.g.,from9.1to10.0);(ii)ifthedisplayedvalueisbetween100and1,000,thevaluechangesby1unit forasinglechevron, andstepsupordowntoavalueequaltothenexthundredplusthedecadeofthe displayedvalueforadoublechevron(e.g.,from310or315to410);(iii)ifthedisplayedvalueis1,000or above,thevaluechangesby10unitsforasinglechevron,andstepsupordowntoavalueequaltothe nexthundredforadoublechevron(e.g.,from1,010or1,080to1,100). TheEmuchartsdiagramforthenumericdataentryisshowninFig.5. Triggersclick_alaris_upand click_alaris_dnrepresentclicksontheupwardanddownwardsingle-chevronbuttons,respectively,and triggers click_alaris_UP and click_alaris_DN represent clicks on the double-chevron ones. For each event,combinationsofguardsandactionsspecifytherulesdescribedabove. The PVS code generator translates the diagram into an executable logic theory, and the C code generatorproducespermissionandtransitionfunctionsforeachtrigger,asexplainedpreviously. 5.1 Mobileapplications The PVSio-web framework uses a standard web interface to integrate its tools: this approach offers a uniforminterfacethatadevelopercanaccesswithanywebbrowser. Our framework has been extended by providing the possibility to run simulations on a mobile device. Smartphonesandtabletsimproveusabilityandhelpmakeuserinteractionsimilartoactualdevice operation. Forexample,mobiledevicescouldbeusedinahospitalenvironmenttotrainmedicalpersonnel andpatients. AninteractivedevicecanbesimulatedusingtheCsourcecodeproducedbythePVSio-webgenerator, compiledandlinkedwithamobiledevice-specificapplication. Forexample,thecodefortheuserinterface G.Mauro,H.Thimbleby,A.Domenici&C.Bernardschi 61 Figure4: FrontpaneloftheAlarisGPinfusionpump. oftheAlarisinfusionpumphasbeenportedtotheAndroid[10]platformusingtheAndroidNDK[25] toolset,whichcanembedCcodeinaJavaproject,relyingontheJavaNativeInterface(JNI)[18]. 6 Conclusions WepresentedtheimplementationofourMISRACcodegeneratorforthePVSio-webprototypingtoolkit. Automaticcodegenerationsignificantlyreducesprojectdevelopmenttime. Ourapproacheliminatesa human-performedstepinthedevelopmentprocess: userinterfacesoftwareengineersnolongerneedto convertthedesignspecificationsintoexecutabletargetcode. Our tool improves the development of safe and dependable user interfaces, as it greatly facilitates usingformalmethodseasilyandreliablywithrealUIs,whichwedemonstratedwiththemedicaldevice examplesinthispaper. CurrentandfuturedirectionsincludeimprovingthisinitialintegrationwithotherfeaturesofC,still conformant to MISRA C under the most recent 2012 rules. We plan to develop code generators for programminglanguagessuchasC++,JavaandADA. 62 MISRACcodegeneration Figure5: Emuchartsdiagramfornumericdataentry. Acknowledgements ThisworkwaspartiallysupportedbythePRA2016project“AnalysisofSensoryData: fromTraditional SensorstoSocialSensors”fundedbytheUniversityofPisa. References [1] MotorIndustrySoftwareReliabilityAssociation(1998): GuidelinesfortheUseoftheCLanguageinVehicle BasedSoftware. MotorIndustryResearchAssociation. [2] Ayan Banerjee & Sandeep K. S. Gupta (2014): Model Based Code Generation for Medical Cy- ber Physical Systems. In: 1st Workshop on Mobile Medical Applications (MMA ’14), pp. 22–27, doi:10.1145/2676431.2676646. [3] M.Beine,R.Otterbach&M.Jungmann(2004): Developmentofsafety-criticalsoftwareusingautomaticcode generation. TechnicalReport,SAETechnicalPapers,doi:10.4271/2004-01-0708. [4] C.Bernardeschi,L.Cassano,A.Domenici&L.Sterpone(2013): UnexcitabilityAnalysisofSEUsAffecting theRoutingStructureofSRAM-basedFPGAs. In: Proc.ofthe23rdACMGreatLakesSymposiumonVLSI, GLSVLSI’13,pp.7–12,doi:10.1145/2483028.2483050.