Programming languages — Guidance to avoiding

Preview:

Citation preview

ISO/IECWD24772-2(E)

©ISO/IEC2021–Allrightsreserved

Date:2021-11-05

ISO/IEC/JTC1/SC22/WG23N1121

ISO/IECWD24772-2

Edition1

ISO/IECJTC1/SC22/WG23

Secretariat:ANSI

Programminglanguages—Guidancetoavoidingvulnerabilitiesinprogramminglanguages–Part2:VulnerabilitydescriptionsfortheprogramminglanguageAda

Langagesdeprogrammation—Conduitepouréviterlesvulnérabilitésdansleslangagesdeprogrammation—Partie2:DescriptiondesvulnérabilitéspourlelangagedeprogrammationAda

Warning

ThisdocumentisnotanISOInternationalStandard.Itisdistributedforreviewandcomment.ItissubjecttochangewithoutnoticeandmaynotbereferredtoasanInternationalStandard.

Recipientsofthisdraftareinvitedtosubmit,withtheircomments,notificationofanyrelevantpatentrightsofwhichtheyareawareandtoprovidesupportingdocumentation.

Documenttype:InternationalstandardDocumentsubtype:ifapplicableDocumentstage:(10)developmentstageDocumentlanguage:E

©ISO/IEC2021–Allrightsreserved

ii

Copyrightnotice

ThisISOdocumentisaworkingdraftorcommitteedraftandiscopyright-protectedbyISO.WhilethereproductionofworkingdraftsorcommitteedraftsinanyformforusebyparticipantsintheISOstandardsdevelopmentprocessispermittedwithoutpriorpermissionfromISO,neitherthisdocumentnoranyextractfromitmaybereproduced,storedortransmittedinanyformforanyotherpurposewithoutpriorwrittenpermissionfromISO.

RequestsforpermissiontoreproducethisdocumentforthepurposeofsellingitshouldbeaddressedasshownbelowortoISO’smemberbodyinthecountryoftherequester:

ISOcopyrightofficeCasepostale56,CH-1211Geneva20Tel.+41227490111Fax+41227490947E-mailcopyright@iso.orgWebwww.iso.org

Reproductionforsalespurposesmaybesubjecttoroyaltypaymentsoralicensingagreement.

Violatorsmaybeprosecuted.

©ISO/IEC

2022–Allrightsreserved

iii

©ISO/IEC2021–Allrightsreserved

iv

Contents

Foreword......................................................................................................................................................vii

Introduction..............................................................................................................................................viii

1.Scope............................................................................................................................................................9

2.Normativereferences............................................................................................................................9

3.Termsanddefinitions,symbolsandconventions.......................................................................9

4Usingthisdocument.............................................................................................................................14

5Generallanguageconceptsandprimaryavoidancemechanisms........................................15 5.1GeneralAdalanguageconcepts....................................................................................................15

6SpecificguidanceforAda....................................................................................................................23 6.1General..................................................................................................................................................23 6.2Typesystem[IHN].............................................................................................................................23 6.3Bitrepresentation[STR].................................................................................................................24 6.4Floating-pointarithmetic[PLF]....................................................................................................24 6.5Enumeratorissues[CCB]................................................................................................................25 6.6Conversionerrors[FLC]..................................................................................................................26 6.7Stringtermination[CJM].................................................................................................................27 6.8Bufferboundaryviolation(bufferoverflow)[HCB]..............................................................27 6.9Uncheckedarrayindexing[XYZ]..................................................................................................27 6.10Uncheckedarraycopying[XYW]...............................................................................................28 6.11Pointertypeconversions[HFC].................................................................................................28 6.12Pointerarithmetic[RVG]..............................................................................................................28 6.13Nullpointerdereference[XYH]..................................................................................................29 6.14Danglingreferencetoheap[XYK].............................................................................................29 6.15Arithmeticwrap-arounderror[FIF]........................................................................................29 6.16Usingshiftoperationsformultiplicationanddivision[PIK]...........................................30 6.17Choiceofclearnames[NAI].........................................................................................................30 6.18Deadstore[WXQ]............................................................................................................................31 6.19Unusedvariable[YZS]...................................................................................................................31 6.20Identifiernamereuse[YOW]......................................................................................................32 6.21Namespaceissues[BJL].................................................................................................................32 6.22Missinginitializationofvariables[LAV].................................................................................32 6.23Operatorprecedenceandassociativity[JCW].......................................................................34 6.24Side-effectsandorderofevaluationofoperands[SAM]...................................................34 6.25Likelyincorrectexpression[KOA]............................................................................................35 6.26Deadanddeactivatedcode[XYQ]..............................................................................................36 6.27Switchstatementsandstaticanalysis[CLL]..........................................................................36 6.28Non-demarcationofcontrolflow[EOJ]...................................................................................37

©ISO/IEC

2022–Allrightsreserved

v

6.29Loopcontrolvariableabuse[TEX].............................................................................................37 6.30Off-by-oneerror[XZH]...................................................................................................................38 6.31Unstructuredprogramming[EWD]...........................................................................................39 6.32Passingparametersandreturnvalues[CSJ]..........................................................................39 6.33Danglingreferencestostackframes[DCM]............................................................................39 6.34Subprogramsignaturemismatch[OTR]..................................................................................40 6.35Recursion[GDL]...............................................................................................................................41 6.36Ignorederrorstatusandunhandledexceptions[OYB]......................................................41 6.37Type-breakingreinterpretationofdata[AMV].....................................................................42 6.38Deepvs.shallowcopying[YAN]..................................................................................................43 6.39Memoryleakandheapfragmentation[XYL]..........................................................................43 6.40Templatesandgenerics[SYM]....................................................................................................44 6.41Inheritance[RIP]..............................................................................................................................44 6.42ViolationsoftheLiskovsubstitutionprincipleorthecontractmodel[BLP]..............44 6.43Redispatching[PPH].......................................................................................................................45 6.44Polymorphicvariables[BKK]......................................................................................................46 6.45Extraintrinsics[LRM]....................................................................................................................46 6.46Argumentpassingtolibraryfunctions[TRJ]..........................................................................46 6.47Inter-languagecalling[DJS]..........................................................................................................47 6.48Dynamically-linkedcodeandself-modifyingcode[NYY]..................................................47 6.49Librarysignature[NSQ].................................................................................................................48 6.50Unanticipatedexceptionsfromlibraryroutines[HJW].....................................................48 6.51Pre-processordirectives[NMP]..................................................................................................49 6.52Suppressionoflanguage-definedrun-timechecking[MXB].............................................49 6.53Provisionofinherentlyunsafeoperations[SKL]..................................................................49 6.54Obscurelanguagefeatures[BRS]...............................................................................................50 6.55Unspecifiedbehaviour[BQF].......................................................................................................50 6.56Undefinedbehaviour[EWF].........................................................................................................51 6.57Implementation-definedbehaviour[FAB]..............................................................................52 6.58Deprecatedlanguagefeatures[MEM].......................................................................................53 6.59Concurrency–Activation[CGA]..................................................................................................53 6.60Concurrency–Directedtermination[CGT]............................................................................54 6.61Concurrentdataaccess[CGX]......................................................................................................54 6.62Concurrency–Prematuretermination[CGS].........................................................................54 6.63Lockprotocolerrors[CGM]..........................................................................................................55 6.64Relianceonexternalformatstrings[SHL]..............................................................................56 6.65Modifyingconstants[UJO]............................................................................................................56

7LanguagespecificvulnerabilitiesforAda......................................................................................57 8Implicationsforstandardization......................................................................................................57

©ISO/IEC2021–Allrightsreserved

vi

Bibliography...............................................................................................................................................58

Index 60

©ISO/IEC

2022–Allrightsreserved

vii

Foreword

ISO(theInternationalOrganizationforStandardization)andIEC(theInternationalElectrotechnicalCommission)formthespecializedsystemforworldwidestandardization.NationalbodiesthataremembersofISOorIECparticipateinthedevelopmentofInternationalStandardsthroughtechnicalcommitteesestablishedbytherespectiveorganizationtodealwithparticularfieldsoftechnicalactivity.ISOandIECtechnicalcommitteescollaborateinfieldsofmutualinterest.Otherinternationalorganizations,governmentalandnon-governmental,inliaisonwithISOandIEC,alsotakepartinthework.Inthefieldofinformationtechnology,ISOandIEChaveestablishedajointtechnicalcommittee,ISO/IECJTC1.

InternationalStandardsaredraftedinaccordancewiththerulesgivenintheISO/IECDirectives,Part2.

ThemaintaskofthejointtechnicalcommitteeistoprepareInternationalStandards.DraftInternationalStandardsadoptedbythejointtechnicalcommitteearecirculatedtonationalbodiesforvoting.PublicationasanInternationalStandardrequiresapprovalbyatleast75%ofthenationalbodiescastingavote.

Inexceptionalcircumstances,whenthejointtechnicalcommitteehascollecteddataofadifferentkindfromthatwhichisnormallypublishedasanInternationalStandard(“stateoftheart”,forexample),itmaydecidetopublishaTechnicalReport.ATechnicalReportisentirelyinformativeinnatureandshallbesubjecttorevieweveryfiveyearsinthesamemannerasanInternationalStandard.

Attentionisdrawntothepossibilitythatsomeoftheelementsofthisdocumentmaybethesubjectofpatentrights.ISOandIECshallnotbeheldresponsibleforidentifyinganyorallsuchpatentrights.

ISO/IEC24772-2,waspreparedbyJointTechnicalCommitteeISO/IECJTC1,Informationtechnology,SubcommitteeSC22,Programminglanguages,theirenvironmentsandsystemsoftwareinterfaces.

ThisdocumentreplacesISOIECTR24772-2:2020.ThemainchangesbetweenthisdocumentandthepreviousversionarethatmaterialhasbeenaddedforsomevulnerabilitiestoreflectadditionknowledgegainedsincethepublicationofTR24772-2:2020.

©ISO/IEC2021–Allrightsreserved

viii

Introduction

Thisdocumentispartofaseriesofdocumentsthatdescribehowvulnerabilitiesariseinprogramminglanguages.ISO/IEC24772-1addressesvulnerabilitiesthatcanariseinanyprogramminglanguageandhenceislanguageindependent.Theotherpartsoftheseriesarededicatedtoindividuallanguages.

ThisdocumentprovidesguidancefortheprogramminglanguageAda,sothatapplicationdevelopersconsideringAdaorusingAdawillbebetterabletoavoidtheprogrammingconstructsthatcanleadtovulnerabilitiesinsoftwarewrittenintheAdalanguageandtheirattendantconsequences.Thisdocumentcanalsobeusedbydeveloperstoselectsourcecodeevaluationtoolsthatcandiscoverandeliminatesomeconstructsthatcouldleadtovulnerabilitiesintheirsoftware.ThisDocumentcanalsobeusedincomparisonwithcompanionDocumentsandwiththelanguage-independentreport,ISO/IEC24772-1,InformationTechnology–ProgrammingLanguages—Guidancetoavoidingvulnerabilitiesinprogramminglanguages,toselectaprogramminglanguagethatprovidestheappropriatelevelofconfidencethatanticipatedproblemscanbeavoided.

Itshouldbenotedthatthisdocumentisinherentlyincomplete.Itisnotpossibletoprovideacompletelistofprogramminglanguagevulnerabilitiesbecausenewweaknessesarediscoveredcontinually.Anysuchdocumentcanonlydescribethosethathavebeenfound,characterized,anddeterminedtohavesufficientprobabilityandconsequence.

InternationalStandard ISO/IEC24772-2:2019(E)

©ISO/IEC2016–Allrightsreserved 9

InformationTechnology—ProgrammingLanguages—Guidancetoavoidingvulnerabilitiesinprogramminglanguages–Part2:VulnerabilitydescriptionsfortheprogramminglanguageAda

1.Scope

ThisDocumentspecifiessoftwareprogramminglanguagevulnerabilitiestobeavoidedinthedevelopmentofsystemswhereassuredbehaviourisrequiredforsecurity,safety,mission-criticalandbusiness-criticalsoftware.Ingeneral,thisguidanceisapplicabletothesoftwaredeveloped,reviewed,ormaintainedforanyapplication.

VulnerabilitiesdescribedinthisDocumentrecordthewaythatthevulnerabilitydescribedinthelanguage-independentdocumentISO/IECISO/IEC24772-1:2022aremanifestedinAda.

2.Normativereferences

Thefollowingreferenceddocumentsareindispensablefortheapplicationofthisdocument.Fordatedreferences,onlytheeditioncitedapplies.Forundatedreferences,thelatesteditionofthereferenceddocument(includinganyamendments)applies.

ISO80000–2:2009,Quantitiesandunits—Part2:MathematicalsignsandsymbolstobeuseinthenaturalsciencesandtechnologyISO/IEC2382–1:1993,Informationtechnology—Vocabulary—Part1:FundamentaltermsISO/IEC24772-1:2022,Programminglanguages-Guidancetoavoidingvulnerabilitiesinprogramminglanguages-Part1:Language-independentguidanceISO/IEC8652:2022Programminglanguages–ProgramminglanguageAda

3.Termsanddefinitions,symbolsandconventions

3.1Termsanddefinitions

Forthepurposesofthisdocument,thetermsanddefinitionsgiveninISO/IEC2382–1,inTR24772-1,andthefollowingapply.Othertermsaredefinedwheretheyappearinitalictype.

10 ©ISO/IEC2022–Allrightsreserved

3.1.1abnormalstatestateofanobjectwhoseinitializationorassignmenthasbeendisruptedbyanabortorthefailureofalanguage-definedcheck

3.1.2access-to-objectpointertoanobject.

3.1.3access-to-subprogrampointertoasubprogram(functionorprocedure).

3.1.4accesstypetypeforobjectsthatdesignate(pointto)objectsorsubprograms

Note:Thisisoftencalledapointertypeinotherlanguages.

3.1.5accessvaluevalueofanaccesstypethatiseithernullordesignatesanotherobjectorsubprogram

3.1.6allocatorconstructthatallocatesstoragefromtheheaporfromastoragepool

3.1.7aspectspecificationmechanismusedtospecifyassertionsaboutthebehaviourofsubprograms,typesandobjectsaswellasoperationalandrepresentationalattributesofvariouskindsofentities

3.1.8atomiccharacteristicofavolatileobjectthatguaranteesthateveryaccesstotheobjectisanindivisibleaccesstotheentityinmemory

3.1.9attributecharacteristicofadeclaredentitythatcanbequeriedbyspecialsyntaxtoreturnavaluecorrespondingtotherequestedattribute

3.1.10bitorderingimplementationdefinedvaluethatiseitherHigh_Order_FirstorLow_Order_Firstthatpermitsthespecificationorqueryofthewaythatmemorybitsarenumberedwithinarepresentationclause

3.1.11boundederrorerrorthatneednotbedetectedeitherpriortoorduringexecution,butifnotdetectedfallswithinaboundedrangeofpossibleeffects

3.1.12casestatementstatementthatprovidesmultiplepathsofexecutiondependentuponthevalueoftheselectingexpression,butwhichwillhaveonlyoneofthealternativesequencesselected

©ISO/IEC2022–Allrightsreserved 11

3.1.13caseexpressionexpressionthatprovidesmultiplepathsofexecutiondependentuponthevalueoftheselectingexpression,butwhichwillhaveonlyoneofthealternativedependentexpressionsevaluated

3.1.14casechoicesalternativesdefinedinthecasestatementorcaseexpressionwhicharerequiredtobeofthesametypeasthetypeoftheselectingexpressioninthecasestatementorcaseexpression,andbywhichallpossiblevaluesoftheselectingexpressionmustbecovered

3.1.15compilationunitsmallestAdasyntacticconstructthatcanbesubmittedtothecompiler,andthatisusuallyheldinasinglecompilationfile

3.1.16configurationpragmadirectivetothecompilerthatisusedtoselectpartition-wideorsystem-wideoptionsandthatappliestoallcompilationunitsappearinginthecompilationorallfuturecompilationunitscompiledintothesameenvironment

3.1.17controlledtypetypedescendedfromthelanguage-definedtypecontrolledorlimited_controlledwhichisaspecializedtypeinAdawherethedeclarercantightlycontroltheinitialization,assignment,andfinalizationofobjectsofthetype

3.1.18deadstoreassignmenttoavariablethatisnotusedinsubsequentinstructions

3.1.19defaultexpressionexpressionthatisusedtoinitializeacomponent,formalobject,orformalparameterwhenanexplicitexpression,actualobject,oractualparameterisnotprovided

3.1.20discretetypeintegertypeorenumerationtype

3.1.21discriminantparameterforacompositetypethatisusedatelaborationofeachobjectofthetypetoconfiguretheobject

3.1.22endiannessbyteordering

3.1.23enumerationrepresentationclauseclauseusedtospecifytheinternalcodesforenumerationliterals

3.1.24enumerationtypediscretetypedefinedbyanenumerationofitsvalues,whicharenamedbyidentifiersorcharacterliterals,includingthetypesCharacterandBoolean

12 ©ISO/IEC2022–Allrightsreserved

3.1.25erroneousexecutionunpredictableresultofanexecutionarisingfromanerrorthatisnotboundedbythelanguage,butthatneednotbedetectedbytheimplementationeitherpriortoorduringrun-time

3.1.26exceptionmechanismtodetectanexceptionalsituationandtoinitiateprocessingdedicatedtorecoverfromtheexceptionalsituation

Note:Exceptionsareraisedexplicitlybyusercodeorimplicitlybylanguage-definedchecks.

3.1.27expandednamenamethatisdisambiguatedfromotheridenticalnamesbyprependingthenamewiththenameoftheenclosingscope

Note:Forexample,thenameofanentityEwithinapackage(oranyothernamedenclosingentity)PisexpandedordisambiguatedbyusingthealternatenameP.EinsteadofthesimplenameE

3.1.28fixed-pointtypesreal-valuedtypeswithaspecifiederrorbound(calledthe'delta'ofthetype)thatprovidearithmeticoperationscarriedoutwithfixedprecisionratherthantherelativeprecisionoffloating-pointtypes

3.1.29genericformalsubprogramparametertoagenericpackageusedtospecifyasubprogramoroperator

3.1.30hidingprocesswhereadeclarationcanbehidden,eitherfromdirectvisibility,orfromallvisibility,withincertainpartsofitsscope

3.1.31homographpropertyoftwodeclarationssuchthattheyhavethesamename,anddonotoverloadeachotheraccordingtotherulesofthelanguage

3.1.32identifiersimplestformofaname.

3.1.33idempotentbehaviourbehaviourthatisapropertyofanoperationthathasthesameeffectwhetherappliedjustonceormultipletimes

3.1.34implementationdefineddefinedbyasetofpossibleeffectsofaconstructwheretheimplementationmaychoosetoimplementanyeffectinthesetofeffects

3.1.35invalidrepresentationrepresentationofanobjectthatdoesnotrepresentanyvalidvalueoftheobject’ssubtype

©ISO/IEC2022–Allrightsreserved 13

3.1.36modulartypeintegertypewithvaluesintherange0..modulus–1withwrap-aroundsemanticsforarithmeticoperations,bit-wise"and"and"or"operations,andwhendefinedinpackageInterfaces,arithmeticandlogicalshiftoperations

3.1.37obsolescentfeaturelanguagefeaturethathasbeendeclaredtobeobsolescentordeprecatedandwhichisdocumentedinAnnexJofISO/IEC8652

3.1.38operationalandrepresentationattributesvaluesofcertainimplementation-dependentcharacteristicsobtainedbyqueryingtheapplicableattributesandpossiblyspecifiedbytheuser

3.1.39overridingindicatorindicatorthatspecifiestheintentthatanoperationdoesordoesnotoverrideancestoroperationsbythesamename,andusedbythecompilertoverifythattheoperationdoes(ordoesnot)overrideanancestoroperation

3.1.40partitionpartofaprogramthatconsistsofasetoflibraryunitssuchthateachpartitionmayexecuteinaseparateaddressspace,possiblyonaseparatecomputer,andcanexecuteconcurrentlywithandcommunicatewithotherpartitions

3.1.41pointeraccessobjectoraccessvalue

3.1.42pragmaadirectivetothecompiler

3.1.43rangecheckrun-timecheckthatensurestheresultofanoperationiscontainedwithintherangeofallowablevaluesforagiventypeorsubtype,suchasthecheckdoneontheoperandofatypeconversion.

3.1.44recordrepresentationclauseamechanismtospecifythelayoutofcomponentswithinrecords,thatis,theirorder,position,andsize

3.1.45scalartypeanyoneofnumeric,Boolean,enumeration,characterandaccesstypes

3.1.46selectingexpressionexpressionthatispartofacasestatementoracaseexpressionandthatdetermineswhichchoiceistakeninexecutingthecasestatementorevaluatingthecaseexpression;itisofadiscretetype

3.1.47staticexpressionexpressionwithstaticallyknownoperandsthatarecomputedwithexactprecisionbythecompiler

14 ©ISO/IEC2022–Allrightsreserved

3.1.48storageplaceattributeintegerattributesthatspecify,foracomponentofarecord,thecomponentpositionandsizewithintherecord

Note:Thestorageplaceattributesare:Position,First_BitandLast_Bit.

3.1.49storagepoolnamedlocationinanAdaprogramwhereallobjectsofasingleaccesstypewillbeallocated

3.1.50storagesubpoolseparatelyreclaimablesubdivisionofastoragepoolthatisidentifiedbyasubpoolhandle

3.1.51subtypedeclarationconstructthatallowsprogrammerstodeclareanamedentitythatdefinesapossiblyrestrictedsubsetofvaluesofanexistingtypeorsubtype,typicallybyimposingaconstraint,suchasspecifyingasmallerrangeofvalues

3.1.52taskseparatethreadofcontrolthatproceedsindependentlyandconcurrentlybetweenthepointswhereitinteractswithothertasksfromthesameprogram

3.1.53unusedvariablevariablethatisdeclaredbutneitherreadnorwrittentointheprogram

3.1.54volatilecharacteristicofanobjectthatguaranteesthatupdatestotheobjectarealwaysseeninthesameorderbyalltasks,andallreadsaredirectlyfrommemory

Note:allatomicobjectsarevolatile.

4Usingthisdocument

ISO/IEC24772-1:2022subclause4.2documentstheprocessofcreatingsoftwarethatissafe,secureandtrustedwithinthecontextofthesysteminwhichitisfielded.TheAdaprogramminglanguagewasexplicitlydesignedforsafety,securityandtheearlyeliminationoferrorsfromAdaprograms.Nevertheless,asthisdocumentshows,vulnerabilitiesexistintheAdaprogrammingenvironment,andorganizationsareresponsibleforunderstandingandaddressingtheprogramminglanguageissuesthatariseinthecontextofthereal-worldenvironmentinwhichtheprogramwillbefielded.

Organizationsfollowingthisdocument,inadditiontomeetingtherequirementsofsubclause4.2ofISO/IEC24772-1:

1. Identifyandanalyzeweaknessesintheproductorsystem,includingsystems,subsystems,modules,andindividualcomponents;

©ISO/IEC2022–Allrightsreserved 15

2. Identifyandanalyzesourcesofprogrammingerrors;3. Determineacceptableprogrammingparadigmsandpracticestoavoidvulnerabilitiesusing

guidancedrawnfromclauses5.3and6inthisdocument;4. Determineavoidanceandmitigationmechanismsusingclause6ofthisdocumentaswellas

othertechnicaldocumentation;5. Maptheidentifiedacceptableprogrammingpracticesintocodingstandards;6. Selectanddeploytoolingandprocessestoenforcecodingrulesorpractices;7. Implementcontrols(inkeepingwiththerequirementsofthesafety,securityandgeneral

requirementsofthesystem)thatenforcethesepracticesandprocedurestoensurethatthevulnerabilitiesdonotaffectthesafetyandsecurityofthesystemunderdevelopment.

Toolvendorsfollowthisdocumentbyprovidingtoolsthatdiagnosethevulnerabilitiesdescribedinthisdocument.Toolvendorsalsodocumenttotheirusersthosevulnerabilitiesthatcannotbediagnosedbythetool.

Programmersandsoftwaredesignersfollowtothisdocumentbyfollowingthearchitecturalandcodingguidelinesoftheirorganization,andbychoosingappropriatemitigationtechniqueswhenavulnerabilityisnotavoidable.

5Generallanguageconceptsandprimaryavoidancemechanisms

5.1GeneralAdalanguageconcepts

5.1.1Adalanguagedesign

Adahasbeendesignedwithemphasisonsoftwareengineeringprinciplesthatsupportthedevelopmentofhigh-integrityapplications.Forexample,Adaisstronglytypedtherebypreventingvulnerabilitiesassociatedwithtypemismatch.Similarly,Adaincludesboundarycheckingonarraysaspartofthestandardlanguagewhichpreventsbufferoverflowvulnerabilities.Mostofthelanguagecanbeusedtodevelopapplicationswithoutknownvulnerabilities.Otherviewsofavoidingprogrammingmistakesanddesignflawsareaddressedby[1],[2],[4],[24],[26]and[29].Forspecificguidanceregardingprogramminginsafetyand/orsecurityenvironmentssee[5][6][11][12][25][28].

5.1.2EnumerationtypeThedefiningidentifiersanddefiningcharacterliteralsofanenumerationtypearerequiredtobedistinct.Thepredefinedorderrelationsbetweenvaluesoftheenumerationtypefollowtheorderofcorrespondingpositionnumbers.

5.1.3ExceptionThereisasetofpredefinedexceptionsinAdainpackage Standard:Constraint_Error,Program_Error,Storage_Error, andTasking_Error;oneofthemisraisedwhencertain

16 ©ISO/IEC2022–Allrightsreserved

language-definedchecksfail.Thestandardlibrariesalsodefineseveralexceptionsthatareraisedwhenchecksinthelibrariesfail.Usercodecandefine,raiseandhandleexceptionsexplicitly.

5.1.4HidingWherehiddenfromallvisibility,adeclarationisnotvisibleatall(neitherusingadirect_namenoraselector_name).Wherehiddenfromdirectvisibility,onlydirectvisibilityislost;visibilityusinganexpandednameisstillpossible.

5.1.5ImplementationdefinedImplementationsarerequiredtodocumenttheirbehaviourinimplementation-definedsituations.

5.1.6TypeconversionsAdausesastrongtypesystembasedonnameequivalencerules.Itdistinguishestypes,whichembodystaticallycheckableequivalencerules,andsubtypes,whichassociatestaticordynamicpropertieswithtypes,forexample,indexrangesforarraysubtypesorvaluerangesfornumericsubtypes.Subtypesarenottypesandtheirvaluesareimplicitlyconvertibletoallothersubtypesofthesametype.Allsubtypeandtypeconversionsensurebystaticordynamicchecksthattheconvertedvalueiswithinthevaluerangeofthetargettypeorsubtype.Ifastaticcheckfails,thentheprogramisrejectedbythecompiler.Ifadynamiccheckfails,thenanexceptionConstraint_Errorisraised.

Toaffectatransitionofavaluefromonetypetoanother,threekindsofconversionscanbeappliedinAda:

a)Implicitconversions:therearefewsituationsinAdathatallowforimplicittypeconversions.Anexampleistheassignmentofavalueofatypetoapolymorphicvariableofanencompassingclass.Inallcaseswhereimplicittypeconversionsarepermitted,neitherstaticnordynamictypesafetyorapplicationtypesemantics(seebelow)areendangeredbytheconversion.

b)Explicitconversions:variousexplicitconversionsbetweenrelatedtypesareallowedinAda.Allsuchconversionsensurebystaticordynamicrulesthattheconvertedvalueisavalidvalueofthetargettype.Violationsofsubtypepropertiescauseanexceptiontoberaisedbytheconversion.

c)Uncheckedconversions:ConversionsthatareobtainedbyinstantiatingthegenericsubprogramUnchecked_Conversionareunsafeandenableallvulnerabilitiesmentionedinsubclause6.3astheresultofabreachinastrongtypesystem.Unchecked_Conversionisoccasionallyneededtointerfacewithtype-lessdatastructures,forexample,hardwareregisters.

AguidingprincipleinAdaisthat,withtheexceptionofusinginstancesofUnchecked_Conversion,noundefinedsemanticscanarisefromconversionsandtheconvertedvalueisavalidvalueofthetargettype.

©ISO/IEC2022–Allrightsreserved 17

5.1.7OperationalandRepresentationAttributesSomeattributescanbespecifiedbytheuser;forexample:

• X'Alignment:allowsthealignmentofobjectsonastorageunitboundaryatanintegralmultipleofaspecifiedvalue.

• X'Size:denotesthesizeinbitsoftherepresentationoftheobject.• X'Component_Size:denotesthesizeinbitsofcomponentsofthearraytypeX.

5.1.8User-definedtypes

Adaallowstheusualuser-definedtypessuchasrecords,classes(calledtaggedrecords),oraccesstypes.InadditionAdaallowsforuser-definedscalartypeswhichpermitspecificationofvalueranges,valueconstraints,andforfloating-pointandfixed-pointtypes,precision.Moreadvancedtypingcapabilitiesallowtheusertospecifytypesforcommunicatingconcurrentlyexecutingentities(tasks)andforsynchronizeddatastructures(protectedobjects).

Thetypingrulesofthelanguagepreventintermixingofobjectsandvaluesofdistincttypes.

5.1.9Compilerdirectives

Note:Adasupportscompilerdirectivesintheformofaspectspecifications,aspectclauses,andconfigurationpragmas.Asanobsolescentfeature,certainaspectscanbespecifiedbysimilarlynamedpragmasaswell.Wesummarizebelowtheaspectsandconfigurationpragmasthatarerelevanttothisdocument.

5.1.9.1Aspect Atomic

Specifiesthatallreadsandupdatesofanobjectareindivisible.

5.1.9.2 Aspect Atomic_Components

Specifiesthatallreadsandupdatesofanelementofanarrayareindivisible.

5.1.9.3 Aspect Convention

SpecifiesthatanAdaentityshouldusetheconventionsofanotherlanguage.

5.1.9.4 Pragma Detect_Blocking

Aconfigurationpragmathatspecifiesthatallpotentiallyblockingoperationswithinaprotectedoperationshallbedetected,resultingintheProgram_Errorexceptionbeingraised.

5.1.9.5 Pragma Discard_Names

Specifiesthatstorageusedatrun-timeforthenamesofcertainentities,particularlyexceptionsandenumerationliterals,maybereducedbyremovingnameinformationfromtheexecutableimage.

5.1.9.6 Aspect Export

18 ©ISO/IEC2022–Allrightsreserved

SpecifiesanAdaentitytobeaccessedbyaforeignlanguage,thusallowinganAdasubprogramtobecalledfromaforeignlanguage,oranAdaobjecttobeaccessedfromaforeignlanguage.

5.1.9.7 Aspect Import

SpecifiesanentitydefinedinaforeignlanguagethatthencanbeaccessedfromanAdaprogram,thusallowingaforeign-languagesubprogramtobecalledfromAda,oraforeign-languagevariabletobeaccessedfromAda.

5.1.9.8 Pragma Normalize_Scalars:

Aconfigurationpragmathatspecifiesthatanotherwiseuninitializedscalarobjectissettoapredictablevalue,butoutofrangeifpossible.

5.1.9.9 Aspect Pack

Specifiesthatstorageminimizationshouldbethemaincriterionwhenselectingtherepresentationofacompositetype.

5.1.9.10 Pragma Restrictions

Specifiesthatcertainlanguagefeaturesarenottobeusedinagivenapplication.Forexample,thepragma Restrictions (No_Obsolescent_Features)prohibitstheuseofanydeprecatedfeatures.Thispragmaisaconfigurationpragmawhichmeansthatallprogramunitscompiledintothelibraryshallobeytherestriction.

5.1.9.11 PragmaSuppress

Specifiesthatarun-timecheckneednotbeperformedbecausetheprogrammerassertsitwillalwayssucceed.

5.1.9.12 AspectUnchecked_Union

SpecifiesaninterfacecorrespondencebetweenagivendiscriminatedtypeandsomeCunion.Theaspect,ifTrue,specifiesthattheassociatedtypewillbegivenarepresentationthatleavesnospaceforitsdiscriminant(s).

5.1.9.13 AspectVolatile

Applicabletoatype,anobject,oracomponent,andspecifiesthattheassociatedobjectsarevolatile.

5.1.9.14 AspectVolatile_Components

Applicabletoanarraytypeoranarrayobject,andspecifiesthattheassociatedcomponentsarevolatile.

5.1.10SeparateCompilation

©ISO/IEC2022–Allrightsreserved 19

Adarequiresthatcallsonlibrariesarecheckedforinvalidsituationsasifthecalledroutinewerepartofthecurrentcompilation.

5.1.11StoragePool

Astoragepoolcanbesizedexactlytotherequirementsoftheapplicationbyallocatingonlywhatisneededforallobjectsofasingletypewithoutusingthecentrallymanagedheap.Exceptionsraisedduetomemoryfailuresinastoragepoolwillnotadverselyaffectstorageallocationfromotherstoragepoolsorfromtheheap.Storagepoolsfortypeswhosevaluesareofequallengthdonotsufferfromfragmentation.Storagepoolscanbedividedintosubpools,toallowefficientreclamationofaportionofastoragepool.

ThefollowingAdarestrictionspreventtheapplicationfromusingallocatorsinvariouscontexts:

pragma Restrictions(No_Allocators):preventstheuseofallallocators.

pragma Restrictions(No_Standard_Allocators_After_Elaboration):preventstheuseofallocatorsafterthemainprogramhascommenced.

pragmaRestrictions(No_Local_Allocators):preventstheuseofallocatorsexceptwithinexpressionsthatareevaluatedaspartoflibrary-unitelaboration.

pragmaRestrictions(No_Implicit_Heap_Allocations):preventstheimplicituseofheapallocationbytheAdaimplementation,butallowsexplicitallocators.

pragmaRestrictions(No_Anonymous_Allocators):preventstheuseofallocatorshavingananonymoustype.

pragmaRestrictions(No_Access_Parameter_Allocators):preventstheuseofallocatorsastheactualparameterforanaccessparameter.

pragmaRestrictions(No_Coextensions):preventstheuseofallocatorsastheinitialvalueforanaccessdiscriminant.

pragmaDefault_Storage_Pool(null):specifiesthatnoallocatorsarepermittedforaccesstypesthatdonotspecifytheirownStorage_PoolorStorage_Size.

pragmaRestrictions(No_Unchecked_Deallocations):preventsallocatedstoragefrombeingdeallocatedandhenceeffectivelyenforcesstoragepoolmemoryapproachesoracompletelystaticapproachtoaccesstypes.Storagepoolsarenotaffectedbythisrestrictionasexplicitroutinestofreememoryforastoragepoolcanbecreated

5.1.12Unsafeprogramming

20 ©ISO/IEC2022–Allrightsreserved

Inrecognitionoftheoccasionalneedtostepoutsidethetypesystemortoperform“risky”operations,Adaprovidesclearlyidentifiedlanguagefeaturestodoso.ExamplesincludethegenericUnchecked_Conversionforunsafetypeconversions,Unchecked_Deallocationforthedeallocationofheapobjectsregardlessoftheexistenceofsurvivingreferencestotheobject,andAddress_To_Access_Conversionsforconvertingaddressesintoaccessvalues.Ifunsafeprogrammingisemployedinaunit,thentheunitneedstospecifytherespectivegenericunitinitscontextclause,thusidentifyingpotentiallyunsafeunits.Similarly,therearewaystocreateapotentiallyunsafeglobalpointertoalocalobject,usingtheUnchecked_Accessattribute.ARestrictionpragmacanbeusedtodisallowusesoftheselanguage-definedgenericunits,aswellasUnchecked_Access.Thepragma Suppress allowsanimplementationtoomitcertainrun-timechecks.

5.2Primaryavoidancemechanisms

Therecommendationsofthissubclausearerestatementsofrecommendationsfromclause6thathavebeenidentifiedasthemostfrequentornoteworthyrecommendationsfromclause6.Table5.1identifiesthemostrelevantavoidancemechanismstobeusedtopreventvulnerabilitiesinAda.

InadditiontothegenericprogrammingrulesfromISO/IEC24772-1:2022subclause5.4,additionalrulesfromthissubclauseapplyspecificallytotheAdaprogramminglanguage.Clause6ofthisdocument providesguidancetomitigateagainstknownvulnerabilitiesinAda.

Number AvoidanceMechanism Reference

1 Specifypre-andpostconditionsonsubprograms. 6.32Passingparametersandreturnvalues[CSJ],6.34Subprogramsignaturemismatch[OTR],6.46Argumentpassingtolibraryfunctions[TRJ]

2 Avoidtheuseoftheabortstatement. 6.56Undefinedbehaviour[EWF],6.60Concurrency–Directedtermination[CGT],6.62Concurrency–Prematuretermination[CGS]

3 Donotusefeaturesexplicitlyidentifiedasunsafe,suchasUnchecked_Deallocation,Unchecked_Conversion,orUnchecked_Access,unlessabsolutelynecessaryandthenwithextremecaution.

6.2Typesystem[IHN],6.3Bitrepresentation[STR],6.11Pointertypeconversions[HFC],6.14Danglingreferencetoheap[XYK],6.33Danglingreferencestostackframes[DCM],6.53

©ISO/IEC2022–Allrightsreserved 21

Provisionofinherentlyunsafeoperations[SKL],6.56Undefinedbehaviour[EWF],6.3Bitrepresentation[STR]

4 Use user-defined types in preference to predefined types, including range and precision as needed.

6.2Typesystem[IHN],6.4Floating-pointarithmetic[PLF],6.6Conversionerrors[FLC],6.57Implementation-definedbehaviour[FAB]

5 Protectalldatasharedbetweentaskswithinaprotectedobject,oruseAtomicoperationstosynchronizecooperatingtasks

6.3Bitrepresentation[STR],6.56Undefinedbehaviour[EWF],6.61Concurrentdataaccess[CGX]

6 ExploitthetypeandsubtypesystemofAda,andpre-andpostconditions,toexpressconstraintsonthevaluesofparameters.

6.46Argumentpassingtolibraryfunctions[TRJ]

7 Wheneverpossible,the'First, 'Last,and'Rangeattributesshouldbeusedforlooptermination.Ifthe'Lengthattributehastobeused,thenextracareshouldbetakentoensurethatthelengthexpressionconsidersthestartingindexvalueforthearray.

6.14Danglingreferencetoheap[XYK],6.30Off-by-oneerror[XZH]

8 Useobjectsofcontrolledtypestoensurethatresourcesareproperlyreleasedifascopeisexitedprematurely.

6.14Danglingreferencetoheap[XYK],6.22Missinginitializationofvariables[LAV],6.39Memoryleakandheapfragmentation[XYL],6.60Concurrency–Directedtermination[CGT],6.62Concurrency–Prematuretermination[CGS]

9 Specifytypeinvariants. 6.44Polymorphicvariables[BKK],6.46Argumentpassingtolibraryfunctions[TRJ]

22 ©ISO/IEC2022–Allrightsreserved

10 Donotsuppressthechecksprovidedbythelanguageunlesstheabsenceoftheerrorscheckedagainsthasbeenverifiedbystaticanalysistools.

6.6Conversionerrors[FLC],6.9Uncheckedarrayindexing[XYZ]6.33Danglingreferencestostackframes[DCM],6.52Suppressionoflanguage-definedrun-timechecking[MXB],6.56Undefinedbehaviour[EWF]

11 Usestaticanalysistoolstodetecterroneousorundefinedbehavioursandtoprecludetheraisingofimplicitexceptions.

6.6Conversionerrors[FLC],6.18Deadstore[WXQ],6.19Unusedvariable[YZS],6.20Identifiernamereuse[YOW],6.24Side-effectsandorderofevaluationofoperands[SAM],6.25Likelyincorrectexpression[KOA],6.52Suppressionoflanguage-definedrun-timechecking[MXB],6.56Undefinedbehaviour[EWF]

12 UseAda'ssupportforwhole-arrayoperations,suchasforassignmentandcomparison,plusaggregatesforwhole-arrayinitialization,toreducetheuseofindexing.

6.9[XYZ],6.10Uncheckedarraycopying[XYW],6.30Off-by-oneerror[XZH]

13 Includeexceptionhandlersforeverytask,sothattheirunexpectedterminationcanbehandledandpossiblycommunicatedtotheexecutionenvironment.

6.36Ignorederrorstatusandunhandledexceptions[OYB],6.60Concurrency–Directedtermination[CGT],6.62Concurrency–Prematuretermination[CGS]

14 Forcasestatementsandaggregates,donotusetheotherschoice.

6.5Enumeratorissues[CCB],6.27Switchstatementsandstaticanalysis[CLL]

Table5-1Mostrelevantavoidancemechanismstobeusedtopreventvulnerabilities

©ISO/IEC2022–Allrightsreserved 23

Thesevulnerabilityguidelinescanbecategorizedintoseveralfunctionalgroups.Items3,10and11areapplicabletoExceptionalandErroneousBehaviours.MitigationmethodsassociatedwithTypes,Subtypes,andContractsincludeItems1,4,6,and9.ThosetechniquesappropriateforStatementsandOperationsconsistofItems7,12,and14.Finally,Items2,5,and8arepertinenttoConcurrencyinapplications.

6SpecificguidanceforAda

6.1General

ThissubclausecontainsspecificadviceforAdaaboutthepossiblepresenceofvulnerabilitiesasdescribedinISO/IEC24772-1:2022[20]andprovidesspecificguidanceonhowtoavoidtheminAdacode.ThissubclausemirrorsISO/IEC24772-1:2022clause6inthatthevulnerability“TypeSystem[IHN]”isfoundinsubclause6.2of[20],andAdaspecificguidanceisfoundinsubclause6.2inthisdocument.

6.2Typesystem[IHN]

6.2.1Applicabilitytolanguage

ThevulnerabilityasdescribedinISO/IEC24772-1subclause6.2appliestoAda.

Implicitconversionscausenoapplicationvulnerability,aslongastheresultingexceptionsareproperlyhandled.

Assignmentbetweentypescannotbeperformedexceptbyusinganexplicitconversion.

Failuretoapplycorrectunitconversionfactorswhenexplicitlyconvertingamongtypesfordifferentunitswillresultinapplicationfailuresduetoincorrectvalues.

Failuretohandletheexceptionsraisedbyfailedchecksofdynamicsubtypepropertiescausestheexecutionofthewholesystem,atask,oraninnernestedscopetohaltabruptly.

Uncheckedconversionscircumventthetypesystemandthereforecancauseunspecifiedbehaviour(see6.37Type-breakingreinterpretationofdata[AMV]).

6.2.2Guidancetolanguageusers

• Followthemitigationmechanismsofsubclause6.2.5ofISO/IEC24772-1:2022.

• Applythepredefined'Validattributeforagivensubtypetoanyvalueasneededtoascertainifthevalueisavalidvalueofthesubtype.Thisisespeciallyusefulwheninterfacingwithtype-lesssystemsorafterUnchecked_Conversion.

24 ©ISO/IEC2022–Allrightsreserved

• Considerrestrictingexplicitconversionstothebodiesofuser-providedconversionfunctionsthatarethenusedastheonlymeanstoeffectthetransitionbetweenunitsystems.Reviewthesebodiescriticallyforproperconversionfactors.

• Handleexceptionsraisedbytypeandsubtypeconversions.

• ConsiderusingtherestrictionNo_Dependence(Ada.Unchecked_Conversion) topreventcircumventingthetypesystem.

6.3Bitrepresentation[STR]

6.3.1ApplicabilitytolanguageWiththeexceptionofunsafeprogramming(see5.1Languageconcepts),thevulnerabilitiesdescribedinISO/IEC24772-1subclause6.3aremitigatedbythetypesysteminAda.

Thevulnerabilitiescausedbytheinherentconceptualcomplexityofbitlevelprogrammingareasdescribedinsubclause6.3ofISO/IEC24772-1.

Adaprovidesmechanismtoindividuallyaccessindividualbitswithouthavingtoindividuallycountormaskneighbouringbits.

Forthetraditionalapproachtobitlevelprogramming,Adaprovidesmodulartypesandliteralrepresentationsinarbitrarybasefrom2to16todealwithnumericentitiesandcorrecthandlingofthesignbit.Theuseofpragma Pack on arraysofBooleansprovidesatype-safewayofmanipulatingbitstringsandeliminatestheuseoferror-pronearithmeticoperations.

6.3.2Guidancetolanguageusers

Inordertomitigatethevulnerabilitiesassociatedwiththecomplexityofbitlevelprogramming

• Followthemitigationmechanismsofsubclause6.3.5ofISO/IEC24772-1:2022.• Userecordandarraytypeswiththeappropriaterepresentationspecificationsaddedsothat

theobjectsareaccessedbytheirlogicalstructureratherthantheirphysicalrepresentation.Theserepresentationspecificationsaddressorder,position,andsizeofdatacomponentsandfields.

• Querythedefaultobjectlayoutchosenbythecompilertodeterminetheexpectedbehaviourofthefinalrepresentation.

• UsetherestrictionNo_Dependence (Ada.Unchecked_Conversion)topreventcircumventingthetypesystem.

6.4Floating-pointarithmetic[PLF]

6.4.1Applicabilitytolanguage

ThevulnerabilityasdescribedinISO/IEC24772-1:2022subclause6.4appliestoAda.Accuracyofdatarepresentationcanbespecifiedindependentlyofanyimplementationcharacteristics.Adaprovidesbinaryanddecimalfixed-pointarithmeticasanalternativetofloatingpoints.Attributesareprovidedtoaccessmantissaandexponentsofvalues,thusreducingtheneedforbit

©ISO/IEC2022–Allrightsreserved 25

manipulations.Animplementationthatconformstothe(optional)AnnexGoftheAdastandardprovidesguaranteesontheaccuracyofarithmeticoperationsandofthestandardmathematicalfunctions.

6.4.2Guidancetolanguageusers

• Followthemitigationmechanismsofsubclause6.4.5ofISO/IEC24772-1:2022.• Ratherthanusingpredefinedtypes,suchasFloatandLong_Float,whoseprecisionmay

varyaccordingtothetargetsystem,declarefloating-pointtypesthatspecifytherequiredprecision(forexample,digits 10).Additionally,specifyingrangesofafloating-pointtypeenablesconstraintcheckswhichpreventsthepropagationofinfinitiesandNaNs.

• Avoidcomparingfloating-pointvaluesforequality.Instead,usecomparisonsthataccountfortheapproximateresultsofcomputations.Consultanumericanalystwhenappropriate.

• Makeuseofstaticarithmeticexpressionsandstaticconstantdeclarationswhenpossible,sincestaticexpressionsinAdaarecomputedatcompiletimewithexactprecision.

• UseAda'sstandardizednumericlibraries(forexample,Generic_Elementary_Functions) forcommonmathematicaloperations(trigonometricoperations,logarithms,andothers).

• UseanAdaimplementationthatsupportstheNumericsAnnexofISO/IEC8652andemploythe"strictmode"ofthatAnnexincaseswhereadditionalaccuracyrequirementsshallbemetbyfloating-pointarithmeticandtheoperationsofpredefinednumericspackages,asdefinedandguaranteedbytheAnnex.

• Avoiddirectmanipulationofbitfieldsoffloating-pointvalues,sincesuchoperationsaregenerallytarget-specificanderror-prone.Instead,makeuseofAda'spredefinedfloating-pointattributes(suchas'Exponent).

• Incaseswhereabsoluteprecisionisneeded,considerreplacementoffloating-pointtypesandoperationswithfixed-pointtypesandoperations.

6.5Enumeratorissues[CCB]

6.5.1Applicabilitytolanguage

ThevulnerabilityasdescribedinISO/IEC24772-1subclause6.5appliestoAda.

Enumerationrepresentationspecificationsareusedtospecifynon-defaultrepresentationsofanenumerationtype,forexamplewheninterfacingwithexternalsystems,ortoconfirmthedefaultrepresentationofatype.Adaspecifiesthatallofthevaluesintheenumerationtypeshallbedefinedintheenumerationrepresentationspecificationandthatthenumericvaluesoftherepresentationshallpreservetheoriginalorder.Forexample:

type IO_Types is (Null_Op, Open, Close, Read, Write, Sync); for IO_Types use (Null_Op => 0, Open => 1, Close => 2, Read => 4, Write => 8, Sync => 16);

Anarraycanbeindexedbysuchatype.Adadoesnotprescribetheimplementationmodelforarraysindexedbyanenumerationtypewithnon-contiguousvalues.Twooptionsexist:Eitherthearrayisrepresented“withholes”andindexedbythevaluesoftheenumerationtype,orthearrayisrepresentedcontiguouslyandindexedbythepositionoftheenumerationvalueratherthanthevalueitself.Intheformercase,thevulnerabilitydescribedinsubclause6.5ofISO/IEC24772-

26 ©ISO/IEC2022–Allrightsreserved

1:2022existsonlyifunsafeprogrammingisappliedtoaccessthearrayoritscomponentsoutsideof(?)theprotectionofthetypesystem.Withinthetypesystem,thesemanticsarewelldefinedandsafe.Thevulnerabilityofunexpectedbutwell-definedprogrambehaviouruponextendinganenumerationtypeexistsinAda.Inparticular,subrangesorotherschoicesinaggregatesandcasestatementsaresusceptibletounintentionallycapturingnewlyaddedenumerationvalues.

6.5.2Guidancetolanguageusers

• Followthemitigationmechanismsofsubclause6.5.5ofISO/IEC24772-1:2022.• Forcasestatementsandaggregates,donotusetheotherschoice.• Forcase statementsandaggregates,mistrustsubrangesaschoicesafterenumeration

literalshavebeenaddedanywherebutthebeginningortheendoftheenumerationtypedefinition.

6.6Conversionerrors[FLC]

6.6.1Applicabilitytolanguage

Withtheexceptionofunsafeprogramming(see5.1Languageconcepts),thevulnerabilityasdescribedinISO/IEC24772-1subclause6.6ismitigatedbyAda.

Adadoesnotpermitimplicitconversionsbetweendifferentnumerictypes,hencecasesofimplicitlossofdataduetotruncationcannotoccurastheycaninlanguagesthatallowtypecoercionbetweentypesofdifferentsizes.

• Adapermitsthedefinitionofsubtypesofexistingtypesthatcanimposearestrictedrangeofvalues,andimplicitconversionscanoccurforvaluesofdifferentsubtypesbelongingtothesametype,butsuchconversionsstillinvolverangechecksthatpreventanylossofdataorviolationoftheboundsofthetargetsubtype.

Inthecaseofexplicitconversions,Adalanguagerulespreventnumericconversionerrorsbyapplying

• Rangeboundchecks,whichraiseanexceptioniftheoperandoftheconversionexceedstheboundsofthetargettypeorsubtype.

Precisionislostonlyonexplicitconversionfromarealtypetoanintegertypeorarealtypeoflessprecision.

AsAdapermitsatypedistinctiontobemadeamongnumericorcompositevaluesindifferentunitsystems,e.g.,metersandfeet,complexnumbersorintervalsofrealnumbers,explicitconversionsbetweensuchtypesmaynotbeconsistentwithapplicationsemanticsforthetypes,unlessaccompaniedwithconversionfactors.

Onstructureddata,implicitconversionspreserveallvalues.Explicitvalueconversionsomitcomponentsnotpresentinthetargettypewheresuchdifferencesareallowedinconversions.See

©ISO/IEC2022–Allrightsreserved 27

inparticular(implicit)upcastsand(explicit)downcastsforOOPinsubclause6.44Polymorphicvariables[BKK].

6.6.2Guidancetolanguageusers

• Followthemitigationmechanismsofsubclause6.6.5ofISO/IEC24772-1:2022.• UseAda'scapabilitiesforuser-definedscalartypesandsubtypestoavoidaccidental

mixingoflogicallyincompatiblevaluesets.• Donotsuppressrangechecksonconversionsinvolvingscalartypesandsubtypesto

preventgenerationofinvaliddata.• Usestaticanalysistoolsduringprogramdevelopmenttoverifythatconversionscannot

violatetherangeoftheirtarget.

6.7Stringtermination[CJM]

Withtheexceptionofunsafeprogramming(see5.1Languageconcepts),thevulnerabilityasdescribedinISO/IEC24772-1subclause6.7doesnotapplytoAda.

StringsinAdaarenotdelimitedbyaterminationcharacter.Adaprogramsthatinterfacetolanguagesthatusenull-terminatedstringsandmanipulatesuchstringsdirectlyshouldapplythevulnerabilitymitigationsrecommendedforthatlanguage.

6.8Bufferboundaryviolation(bufferoverflow)[HCB]

Withtheexceptionofunsafeprogramming(see5.1Languageconcepts),thevulnerabilityasdescribedinISO/IEC24772-1subclause6.8doesnotapplytoAda(see6.9Uncheckedarrayindexing[XYZ]and6.10Uncheckedarraycopying[XYW]).

6.9Uncheckedarrayindexing[XYZ]

6.9.1Applicabilitytolanguage

Withtheexceptionofunsafeprogramming(see5.1Languageconcepts),thevulnerabilityasdescribedinISO/IEC24772-1subclause6.9doesnotapplytoAda.

AllarrayindexingischeckedautomaticallyinAda,andanAdaprogramraisesanexceptionwhenindexesareoutofbounds.Thisischeckedinallcasesofindexing,includingwhenarraysarepassedtosubprograms.

Anexplicitsuppressionoftherun-timecheckscanberequestedbyuseofpragma Suppress,inwhichcasethevulnerabilitywouldapply;however,suchsuppressioniseasilydetected,andgenerallyreservedfortighttime-criticalloops,eveninproductioncode.

6.9.2Guidancetolanguageusers

• Followthemitigationmechanismsofsubclause6.9.5ofISO/IEC24772-1:2022.

28 ©ISO/IEC2022–Allrightsreserved

• UseAda'ssupportforwhole-arrayoperations,suchasforassignmentandcomparison,plusaggregatesforwhole-arrayinitialization,toreducetheuseofindexing.

• Writeexplicitboundsteststopreventexceptionsforindexingoutofbounds.

6.10Uncheckedarraycopying[XYW]

Withtheexceptionofunsafeprogramming(see5.1Languageconcepts),thevulnerabilityasdescribedinISO/IEC24772-1subclause6.10doesnotapplytoAda.

Adaallowsarraystobecopiedbysimpleassignment(":=").Therulesofthelanguageensurethatnooverflowcanhappen;instead,theexceptionConstraint_Errorisraisedifthetargetoftheassignmentisnotabletocontainthevalueassignedtoit.Therulesalsoensurethatoverlappingsourceandtargetslicesarehandledcorrectly,i.e.,thetargetslicereceivestheoriginalvalueofthesourceslice.Sincearraycopyisprovidedbythelanguage,Adadoesnotprovideunsafefunctionstocopystructuresbyaddressandlength.

6.11Pointertypeconversions[HFC]

6.11.1Applicabilitytolanguage

Withtheexceptionofunsafeprogramming(see5.1Languageconcepts),thevulnerabilityasdescribedinISO/IEC24772-1subclause6.11doesnotapplytoAda.ThemechanismsavailableinAdatoalterthetypeofapointervalueareuncheckedtypeconversionsandtypeconversionsinvolvingpointertypesderivedfromacommonroottype.Inaddition,usesoftheuncheckedaddresstakingcapabilitiescancreatepointervaluesthatmisrepresentthetruetypeofthedesignatedentity(seesubclause13.10ofISO/IEC8652).

Checkedtypeconversionsthataffecttheapplicationsemanticsadverselyarepossible.Forexample,whenapointertoaclass-widetypeischangedtoapointertoaspecifictypeintheclass,arun-timecheckisrequired.

6.11.2Guidancetolanguageusers

• Followthemitigationmechanismsofsubclause6.11.5ofISO/IEC24772-1:2022.• Donotusethefeaturesexplicitlyidentifiedasunsafe.• Use‘Accesswhichisalwaystypesafe.• ConsiderusingtherestrictionNo_Dependence(Ada.Unchecked_Conversion),

No_Use_Of_Attribute(Address), No_Specification_of_Aspect(Address), and No_Unchecked_Accesstopreventcircumventingthetypesystem.

6.12Pointerarithmetic[RVG]

Withtheexceptionofunsafeprogramming(see5.1Languageconcepts),thevulnerabilityasdescribedinISO/IEC24772-1subclause6.12doesnotapplytoAda.

©ISO/IEC2022–Allrightsreserved 29

6.13Nullpointerdereference[XYH]

6.13.1Applicabilitytothelanguage

Withtheexceptionofunsafeprogramming(see5.1Languageconcepts),thevulnerabilityasdescribedinISO/IEC24772-1subclause6.13ismitigatedbyAda.Thevulnerabilityismitigatedbycompile-timeorrun-timechecksthatensurethatnonullvaluecanbedereferenced.AnyattempttodereferenceanullpointerresultsintheConstraint_Errorexceptionbeingimplicitlyraised.Vulnerabilitiesassociatedwithunhandledexceptionsareaddressedinsubclause6.36.

6.13.2Guidancetolanguageusers

• Followthemitigationmechanismsofsubclause6.13.5ofISO/IEC24772-1:2022.• Usenon-nullaccesstypeswherepossible.• Handleexceptionsraisedbyattemptstodereferencenullvalues.

6.14Danglingreferencetoheap[XYK]

6.14.1Applicabilitytolanguage

ThevulnerabilityasdescribedinISO/IEC24772-1subclause6.14appliestoAda.UseofUnchecked_Deallocationcancausedanglingreferencestotheheapwhenthisfeatureisused,sinceUnchecked_Deallocationcanbeappliedeventhoughthereareoutstandingreferencestothedeallocatedobject.

Adaprovidesamodelinwhichwholecollectionsofheap-allocatedobjectscanbedeallocatedsafely,automaticallyandcollectivelywhenthescopeoftherootaccesstypeorthescopeofanyassociatedstoragepoolobjectends.

Forglobalaccesstypes,unlessstoragepoolsareused,allocatedobjectscanonlybedeallocatedthroughaninstantiationofthegenericprocedureUnchecked_Deallocation.

6.14.2Guidancetolanguageusers

• Followthemitigationmechanismsofsubclause6.14.5ofISO/IEC24772-1:2022.• Uselocalaccesstypeswherepossible.• ConsidernotusingUnchecked_Deallocationandapplyingtherestriction

No_Unchecked_Deallocationtoenforcethis.• Usecontrolledtypesandreferencecounting.• Considertheuseofstoragepoolsandsubpools.

6.15Arithmeticwrap-arounderror[FIF]

Withtheexceptionofunsafeprogramming(see5.1Languageconcepts),thevulnerabilityasdescribedinISO/IEC24772-1subclause6.16doesnotapplytoAdaaswrap-aroundarithmeticin

30 ©ISO/IEC2022–Allrightsreserved

Adaislimitedtomodulartypes.Arithmeticoperationsonsuchtypesusemoduloarithmetic,andthusnosuchoperationcancreateaninvalidvalueofthetype.

Fornon-modulararithmetic,AdaraisesthepredefinedexceptionConstraint_Errorwheneverawrap-aroundoccursbutimplementationsareallowedtorefrainfromdoingsowhenacorrectfinalvalueisobtained.InAdathereisnoconfusionbetweenlogicalandarithmeticshifts.

6.16Usingshiftoperationsformultiplicationanddivision[PIK]

Withtheexceptionofunsafeprogramming(see5.1Languageconcepts),thevulnerabilityasdescribedinISO/IEC24772-1subclause6.16doesnotapplytoAdaasshiftoperationsinAdaarelimitedtothemodulartypesdeclaredinthestandardpackageInterfaces,whicharenotsignedentities.

6.17Choiceofclearnames[NAI]

6.17.1Applicabilitytolanguage

ThevulnerabilityasdescribedinISO/IEC24772-1subclause6.17appliestoAda.Therearetwopossibleissues:theuseoftheidenticalnamefordifferentpurposes(overloading)andtheuseofsimilarnamesfordifferentpurposes.

Thisvulnerabilitydoesnotaddressoverloading,whichiscoveredin6.20Identifiernamereuse[YOW].

Theriskofconfusionbytheuseofsimilarnamescanoccurthrough:

• Mixedcasing.Adatreatsuppercaseandlower-caselettersinnamesasidentical.Thus,noconfusioncanarisethroughanattempttouseItemandITEMasdistinctidentifierswithdifferentmeanings.

• Underscoresandperiods.Adapermitssingleunderscoresinidentifiersandtheyaresignificant.Thus,BigDogandBig_Dogaredifferentidentifiers.Butmultipleunderscores(whichcanbeconfusedwithasingleunderscore)areforbidden,thusBig__Dogisforbidden.Leadingandtrailingunderscoresarealsoforbidden.Periodsarenotpermittedinidentifiersatall.

• Singular/pluralforms.AdadoespermittheuseofidentifierswhichdiffersolelyinthismannersuchasItemandItems.However,AdaletstheprogrammerusetheidentifierItemforasingleobjectofatype TandtheidentifierItemsforanobjectdenotinganarrayofitemsthatisofatype array (…) of T.TheuseofItemwhereItemswasintendedorviceversawillbedetectedbythecompilerbecauseofthetypeviolationandtheprogramrejectedsonovulnerabilitywouldarise.

• Internationalcharactersets.AdacompilersstrictlyconformtotheappropriateInternationalStandardforcharactersets.

• Identifierlength.AllcharactersinanidentifierinAdaaresignificant.ThusLong_IdentifierAandLong_IdentifierBarealwaysdifferent.Anidentifiercannotbesplitovertheendofaline.Theonlyrestrictiononthelengthofanidentifieristhatenforcedbythelinelengthandthisisguaranteedbythelanguagestandardtobenolessthan200.

©ISO/IEC2022–Allrightsreserved 31

AdapermitstheuseofnamessuchasX,XX,andXXX(whichmayallbedeclaredasintegers)andaprogrammercaneasily,bymistake,writeXXwhereX(orXXX)wasintended.Adadoesnotattempttocatchsucherrors.

Theuseofthewrongnamewilltypicallyresultinafailuretocompilesonovulnerabilitywillarise.But,ifthewrongnamehasthesametypeastheintendedname,thenanincorrectexecutableprogramwillbegenerated.

The“incorrectexecutable”canalsohappenwhenthetwoconfusednameshavedifferenttypes,butoccurinacontextwherethetypedoesnotmatter,forexampleX’Address orX’Size,orinacontextwherethetypemattersbutonlyleadstotheselectionofadifferentoverloadedentity,forexampleFoo(X)canbelegalforbothInteger XandBooleanX,ifFooisoverloadedforbothtypes.

6.17.2Guidancetolanguageusers

• Followthemitigationmechanismsofsubclause6.17.5ofISO/IEC24772-1:2022.• Avoidtheuseofsimilarnamestodenotedifferentobjectsofthesametype.• Adoptaprojectconventionfordealingwithsimilarnames• SeetheAdaQualityandStyleGuide[1].

6.18Deadstore[WXQ]

6.18.1Applicabilitytolanguage

ThevulnerabilityasdescribedinISO/IEC24772-1subclause6.18appliestoAda.

Adacompilersdoexistthatdetectandgeneratecompilerwarningsfordeadstores.

TheerrorinISO/IEC24772-1subclause6.18.3thattheplannedreadermisspellsthenameofthestoreispossiblebuthighlyunlikelyinAdasincethelanguagespecifiesthatallobjectsshallbedeclaredandtyped,andtheexistenceoftwoobjectswithalmostidenticalnamesandcompatibletypes(forassignment)inthesamescopewouldbereadilydetectable.

6.18.2GuidancetoLanguageUsers

• Followthemitigationmechanismsofsubclause6.18.5ofISO/IEC24772-1:2022.• UseAdacompilersthatdetectandgeneratecompilerwarningsfordeadstores.• Usestaticanalysistoolstodetectsuchproblems.

6.19Unusedvariable[YZS]

6.19.1Applicabilitytolanguage

Thevulnerabilityasdescribedinsubclause6.19ofISO/IEC24772-1appliestoAda.Adacompilersexistthatdetectandgeneratecompilerwarningsforunusedvariables.

32 ©ISO/IEC2022–Allrightsreserved

6.19.2Guidancetolanguageusers

• Followthemitigationmechanismsofsubclause6.19.5ofISO/IEC24772-1:2022.• Donotdeclarevariablesofthesametypewithsimilarnames.Usedistinctiveidentifiersand

thestrongtypingofAda(forexamplethroughdeclaringspecifictypesasin type Pig_Counter is range 0 .. 1000; Pig : Pig_Counter;ratherthanjust Pig: Integer;)toreducethenumberofvariablesofthesametype.

• UseAdacompilersthatdetectandgeneratecompilerwarningsforunusedvariables.

6.20Identifiernamereuse[YOW]

6.20.1Applicabilitytolanguage

ThevulnerabilityasdescribedinISO/IEC24772-1subclause6.20appliestoAda.Adaisalanguagethatpermitslocalscope,andnameswithinnestedscopescanhideidenticalnamesdeclaredinanouterscope.Assuchitissusceptibletothevulnerability.Forsubprogramsandotheroverloadedentitiestheproblemisreducedbythefactthathidingalsotakesthesignaturesoftheentitiesintoaccount.Entitieswithdifferentsignatures,therefore,donothideeachother.

NamecollisionswithkeywordscannothappeninAdabecausekeywordsarereserved.

Themechanismoffailureidentifiedinsubclause6.20.3ofISO/IEC24772-1:2022regardingthedeclarationofnon-uniqueidentifiersinthesamescopecannotoccurinAdabecauseallcharactersinanidentifieraresignificant.

6.20.2Guidancetolanguageusers

• Followthemitigationmechanismsofsubclause6.20.5ofISO/IEC24772-1:2022.• Useexpandednameswheneverconfusionispossible.• UseAdacompilersorstaticanalysistoolsthatgeneratewarningsfordeclarationsininner

scopesthathidedeclarationsinouterscopes.

6.21Namespaceissues[BJL]

ThevulnerabilityasdescribedinISO/IEC24772-1subclause6.21doesnotapplytoAda,sinceAdadoesnotattempttodisambiguateconflictingnamesimportedfromdifferentpackages.Instead,useofanamewithconflictingimporteddeclarationscausesacompile-timeerror.Theprogrammercandisambiguatethenameusagebyusinganexpandednamethatidentifiestheexportingpackage.

6.22Missinginitializationofvariables[LAV]

6.22.1Applicabilitytolanguage

ThevulnerabilityasdescribedinISO/IEC24772-1subclause6.22appliestoAda.Asinmanylanguages,itispossibleinAdatomakethemistakeofusingthevalueofanuninitializedvariable.

©ISO/IEC2022–Allrightsreserved 33

However,asdescribedbelow,Adapreventssomeofthemostharmfulpossibleeffectsofusingthevalue.

Thevulnerabilitydoesnotexistforpointervariables(orconstants).Pointervariablesareinitializedtonullbydefault,andeverydereferenceofapointerthatisnotnull-excludingischeckedforanull value.

Thechecksmandatedbythetype-systemapplytotheuseofuninitializedvariablesaswell.Whenthecontextforusingavalueimposesasubtypewitharestrictedsetofvalues,thenvaluesofthetypethatareoutsideofthesubtypewillfailthecheckrequiredinsuchcontexts.Useofanout-of-boundsvalueinmostcontextsraisesanexception,regardlessoftheoriginofthefaultyvalue.(See6.36Ignorederrorstatusandunhandledexceptions[OYB]regardingexceptionhandling.)Inthecaseofvaluesoriginatingfromanuninitializedvariablethatarenotdetectedbysuchasubtypecheck(suchaswhenthecontextdoesnotimposeasubtypeconstraint,thevalueiswithinthesubtype’ssetofvalues,orthevaluedoesnotbelongtothetypeitself),executionmayproceedwiththatvalue,butuseofsuchvalueswillnotleadtoout-of-boundsmemorymodifications.Inparticular,useofuninitializedvalueswillnotresultinwritingoutsideoftheboundsofarrayobjects,andwillnotleadtowildjumpswhenusedastheselectingvalueofacase statementorcaseexpression.

Forscalartypes,theDefault_Valueaspectcanbespecifiedtoprovideadefaultinitialvalueforotherwiseuninitializedobjectsofthetype.

Forrecordtypes,defaultinitializationscanbespecifiedaspartofthetypedefinition.Forrecordtypes,aggregatevaluescanbeusedtoinitializeanobjecttoensurethatallcomponentsoftheobjecthavebeeninitializedwithavalue.

Forcontrolledtypes(thosedescendedfromthelanguage-definedtypeControlledorLimited_Controlled),theusercanalsospecifyanInitializeprocedurewhichisinvokedonalldefault-initializedobjectsofthetype.

Thepragma Normalize_Scalarscanbeusedtoensurethatscalarvariablesarealwaysinitializedbythecompilerinarepeatablefashion.Thispragma isdesignedtoinitializevariablestoanout-of-rangevalueifthereisone,toavoidhidingerrors.

Lastly,theusercanquerythevalidityofagivenvalue.TheexpressionX’ValidyieldstrueifthevalueofthescalarvariableXconformstothesubtypeofXandfalseotherwise.Thus,theusercanprotectagainsttheuseofout-of-boundsuninitializedorotherwisecorruptedscalarvalues.

6.22.2Guidancetolanguageusers

• Followthemitigationmechanismsofsubclause6.22.5ofISO/IEC24772-1:2022.• Ifthecompilerhasamodethatdetectsusebeforeinitialization,thenenablethismodeand

treatanysuchwarningsaserrors.• Whereappropriate,specifyexplicitinitializationsordefaultinitializations.

34 ©ISO/IEC2022–Allrightsreserved

• Usethe pragma Normalize_Scalars tocauseout-of-rangedefaultinitializationsforscalarvariables.

• Usethe‘Validattributetoidentifyout-of-rangescalarvaluescausedbytheuseofuninitializedvariables,withoutincurringtheraisingofanexception.NotethatanimplementationispermittedtoraiseanexceptionforanUnchecked_Conversioninthiscase.

Commonadvicethatshouldbeavoidedistoperforma“junkinitialization”ofvariables.Initializingavariablewithaninappropriatedefaultvaluesuchaszerocanresultinhidingunderlyingproblems,becausethecompilerorotherstaticanalysistoolswillthenbeunabletodetectthatthevariablehasbeenusedpriortoreceivingacorrectlycomputedvalue.

6.23Operatorprecedenceandassociativity[JCW]

6.23.1Applicabilitytolanguage

ThevulnerabilityasdescribedinISO/IEC24772-1subclause6.23appliestoAda.Sincethisvulnerabilityisabout"incorrectbeliefs"ofprogrammers,thereisnowaytoestablishalimittohowfarincorrectbeliefscango.However,Adaislesssusceptibletothatvulnerabilitythanmanyotherlanguages,since

• Adaonlyhassixlevelsofprecedenceandassociativityisclosertocommonexpectations.Forexample,anexpressionlikeA = B orC = Dwillbeparsedasexpected,as(A = B) or (C = D).

• Mixedlogicaloperatorsarenotallowedwithoutparentheses,forexample,"A or B or C"isvalid,aswellas"A and B and C",but"A and B or C"isnot;theusermustwrite"(A and B) or C"or"A and (B or C)".

• AssignmentisnotanoperatorinAda.

6.23.2Guidancetolanguageusers

Followthemitigationmechanismsofsubclause6.23.5ofISO/IEC24772-1:2022.

6.24Side-effectsandorderofevaluationofoperands[SAM]

6.24.1Applicabilitytolanguage

ThevulnerabilityasdescribedinISO/IEC24772-1subclause6.24appliestoAda.TherearenooperatorsinAdawithdirectsideeffectsontheiroperandsusingthelanguage-definedoperations,especiallynottheincrementanddecrementoperation.Adadoesnotpermitmultipleassignmentsinasingleexpressionorstatement,exceptinthecaseofinitializationofmultiplevariablesbyasingleexpression.Inthiscase,thedeclarationisequivalenttoasequenceofinitializingdeclarationsplacedintheorderofthevariablesinthelist.

Thereisthepossibilitythoughtohavesideeffectsthroughfunctioncallsinexpressionswherethefunctionmodifiesgloballyvisiblevariablesor“in out”or“out”parameters.Adadisallowsmultipleusesofthesamevariablewithinasingleexpressionifoneormoreoftheusesareas“in out”or“out”parameters.OperatorsinAdaarefunctionswithonly“in”parameters,so,whendefinedby

©ISO/IEC2022–Allrightsreserved 35

theuser,althoughtheycannotmodifytheirownoperands,theycanmodifyglobalstateandthereforehavesideeffects.

Adaallowstheimplementationtochoosetheorderofevaluationofexpressionswithoperandsofthesameprecedencelevel,theorderofassociationisleft-to-right.Theoperandsofabinaryoperationarealsoevaluatedinanarbitraryorder,ashappensfortheparametersofanyfunctioncall.Inthecaseofuser-definedoperatorswithsideeffectsonglobalstate,thisimplementationdependencycancauseunpredictabilityofthesideeffects.

6.24.2Guidancetolanguageusers

• Followthemitigationmechanismsofsubclause6.24.5ofISO/IEC24772-1:2022.• Makeuseofoneormoreprogrammingguidelineswhichprohibitfunctionsthatmodify

globalstate,andcanbeenforcedbystaticanalysis.• Minimizeuseof“in out”and“out”parametersforfunctions.• Alwaysusebracketstoindicateorderofevaluationofoperatorsofthesameprecedence

level.

6.25Likelyincorrectexpression[KOA]

6.25.1Applicabilitytolanguage

ThevulnerabilityasdescribedinISO/IEC24772-1subclause6.25appliestoAda.Aninstanceofthisvulnerabilityconsistsoftwosyntacticallysimilarconstructssuchthattheinadvertentsubstitutionofonefortheothercanresultinaprogramwhichisacceptedbythecompilerbutdoesnotreflecttheintentoftheauthor.

Theexamplesgiveninsubclause6.25ofISO/IEC24772-1:2022arenotproblemsinAdabecauseofAda'sstrongtypingandbecauseanassignmentisnotanexpressioninAda.

InAda,atypeconversionandaqualifiedexpressionaresyntacticallysimilar,differingonlyinthepresenceorabsenceofasinglecharacter:

Type_Name (Expression) -- a type conversion

vsType_Name'(Expression) -- a qualified expression

Typically,theinadvertentsubstitutionofonefortheotherresultsineitherasemanticallyincorrectprogramwhichisrejectedbythecompilerorinaprogramwhichbehavesinthesamewayasiftheintendedconstructhadbeenwritten.Inthecaseofaconstrainedarraysubtype,thetwoconstructsdifferintheirtreatmentofsliding(conversionofanarrayvaluewithbounds100 .. 103 toasubtypewithbounds200 .. 203willsucceed;qualificationwillfailarun-timecheck).

Similarly,atimedentrycallandaconditionalentrycallwithanelse-partthathappenstobeginwithadelaystatementdifferonlyintheuseof"else"vs"or"(oreven"then abort"inthecaseofanasynchronous_selectstatement).

36 ©ISO/IEC2022–Allrightsreserved

Probablythemostcommoncorrectnessproblemresultingfromtheuseofonekindofexpressionwhereasyntacticallysimilarexpressionshouldhavebeenusedhastodowiththeuseofshort-circuitvs.non-short-circuitBoolean-valuedoperations(forexample,"and then"and"or else"vs"and"and"or"),asin

if (P /= null) and (P.all.Count > 0) then ... end if; -- should have used "and then" to avoid dereferencing null

6.25.2Guidancetolanguageusers

• Followthemitigationmechanismsofsubclause6.25.5ofISO/IEC24772-1:2022.• Considerusingshort-circuitformsbydefault(errorsresultingfromtheincorrectuseof

short-circuitformsaremuchlesscommon),thoughthiscanmakeitmoredifficulttoexpressthedistinctionbetweenthecaseswhereshort-circuitedevaluationisknowntobeneeded(eitherforcorrectnessorforperformance)andthosewhereitisnot.

6.26Deadanddeactivatedcode[XYQ]

6.26.1Applicabilitytolanguage

ThevulnerabilityasdescribedinISO/IEC24772-1subclause6.26appliestoAda.Adaallowstheusualsourcesofdeadcodeasdescribedinsubclause6.26ofISO/IEC24772-1and[22]thatarecommontomostconventionalprogramminglanguages.

6.26.2Guidancetolanguageusers

• Followthemitigationmechanismsofsubclause6.26.5ofISO/IEC24772-1:2022.• Useimplementation-specificmechanisms,ifprovided,tosupporttheeliminationofdead

code.Insomecases,usepragmassuchasRestrictions,Suppress,orDiscard_Namestoinformthecompilerthatsomecodewhosegenerationwouldnormallyberequiredforcertainconstructswouldbedeadbecauseofpropertiesoftheoverallsystem,andthatthereforethecodeneednotbegenerated.Forexample:

package Pkg is type Enum is (Aaa, Bbb, Ccc); pragma Discard_Names( Enum ); end Pkg;

IfPkg.Enum'Imageandrelatedattributes(e.g.,Value,Wide_Image)ofthetypeEnum areneverused,andiftheimplementationnormallybuildsatableoftheenumerationliterals,thenthepragmaallowstheeliminationofthetable.

6.27Switchstatementsandstaticanalysis[CLL]

6.27.1Applicabilitytolanguage

©ISO/IEC2022–Allrightsreserved 37

Withtheexceptionofunsafeprogramming(see5.1Languageconcepts)andtheuseofdefaultcases,thevulnerabilityasdescribedinISO/IEC24772-1subclause6.27doesnotapplytoAda.

Adaensuresthatacasestatementoracaseexpressionprovideexactlyonealternativeforeachvalueoftheselectingexpression'ssubtype.Thisrestrictionisenforcedatcompiletime.Anotherschoicecanbeusedinthelastalternativeofacasestatementorcaseexpressiontocaptureanyremainingvaluesoftheselecting_expressionsubtypethatarenotcoveredbytheprecedingcasechoices.Ifthevalueoftheexpressionisoutsideoftherangeofthissubtype(e.g.,duetoanuninitializedvariable),thentheresultingbehaviouriswell-defined(ifanotherschoiceispresent,thatalternativemaybeselected,otherwiseConstraint_Errorisraised).Controldoesnotflowfromonealternativetothenext.Uponreachingtheendofanalternative,controlistransferredtotheendofthecasestatement.

Theremainingvulnerabilityisthatunexpectedvaluesarecapturedbytheothersclauseorasubrangeascasechoice.Forexample,whentherangeofthetypeCharacterwasextendedfrom128characterstothe256charactersintheLatin-1charactertype,anothersclauseforacasestatementwithaCharactertypecaseexpressionoriginallywrittentocapturecasesassociatedwiththe128characterstypenowalsocapturesthe128additionalcasesintroducedbytheextensionofthetypeCharacter.Someofthenewcharactersneededtobecoveredbytheexistingcasechoicesornewcasechoices.

6.27.2Guidancetolanguageusers

• Forcasestatements,caseexpressionsandaggregates,avoidtheuseoftheotherschoice.• Forcasestatements,caseexpressionsandaggregates,mistrustsubrangesaschoicesafter

enumerationliteralshavebeenaddedanywherebutthebeginningortheendoftheenumerationtypedefinition.15F1

6.28Non-demarcationofcontrolflow[EOJ]

ThevulnerabilityasdescribedinISO/IEC24772-1subclause6.28doesnotapplytoAda.TheAdasyntaxdescribesseveraltypesofcompoundstatementsthatareassociatedwithcontrolflowincludingifstatements,loopstatements,casestatements,selectstatements,andextendedreturnstatements.Eachoftheseformsofcompoundstatementsrequireuniquesyntaxthatmarkstheendofthecompoundstatement.

6.29Loopcontrolvariableabuse[TEX]

Withtheexceptionofunsafeprogramming(see5.1Languageconcepts),thevulnerabilityasdescribedinISO/IEC24772-1subclause6.29doesnotapplytoAda.Adadefinesafor loopwherethenumberofiterationsiscontrolledbyaloopcontrolvariable(calledaloopparameter).This

1Thiscaseissomewhatspecializedbutisimportant,sinceenumerationsaretheonecasewheresubrangesturnbadontheuser.

38 ©ISO/IEC2022–Allrightsreserved

valuehasaconstantviewandcannotbeupdatedwithinthesequenceofstatementsofthebodyoftheloop.

6.30Off-by-oneerror[XZH]

6.30.1Applicabilitytolanguage

ThevulnerabilityasdescribedinISO/IEC24772-1subclause6.30ismitigatedbyAda.

Confusion between the need for < and <= or > and >= in a test. Afor … loopinAdadoesnotrequiretheprogrammertospecifyaconditionaltestforlooptermination.Instead,thestartingandendingvalueofthelooparespecifiedwhicheliminatesthissourceofoff-by-oneerrors.Therearealsospecialfor … loopstructuresthatiteratethroughanentirearrayorcontainer.Theseavoidtheneedtospecifyanyboundsfortheiteration.A while … loophowever,letstheprogrammerspecifytheloopterminationexpression,whichcanbesusceptibletoanoff-by-oneerror.

Confusion as to the index range of an algorithm. Althoughtherearelanguagedefinedattributestosymbolicallyreferencethestartandendvaluesforaloopiteration,thelanguagedoesallowtheuseofexplicitvaluesandloopterminationtests.Off-by-oneerrorscanresultinthesecircumstances.

Careshouldbetakenwhenusingthe'Lengthattributeintheloopterminationexpression.Theexpressionshouldgenerallyberelativetothe'Firstvalue.

ThestrongtypingofAdaeliminatesthepotentialforbufferoverflowassociatedwiththisvulnerability.Iftheerrorisnotstaticallycaughtatcompiletime,thenarun-timecheckgeneratesanexceptionifanattemptismadetoaccessanelementoutsidetheboundsofanarray.

Failing to allow for storage of a sentinel value. Adadoesnotuselanguage-definedsentinelvaluestoterminatearrays.Thereisnoneedtoaccountforthestorageofasentinelvalue,thereforethisparticularvulnerabilityconcerndoesnotapplytoAda.

6.30.2Guidancetolanguageusers

• Followthemitigationmechanismsofsubclause6.30.5ofISO/IEC24772-1:2022.• Wheneverpossible,useafor … loopinsteadofawhile … loop.• Wheneverpossible,useAdaconstructsthateliminatetheneedforloopstatements,suchas

arrayaggregates,qualifiedexpressions,andreductionexpressions.• Wheneverpossible,usetheformofiterationthattakesthenameofthearrayorcontainer

andnothingmore.• Whenindicesarenecessary,usethe'First,'Last,and'Rangeattributesforloop

termination,e.g.for I in MyArray'Range loop….

©ISO/IEC2022–Allrightsreserved 39

• Ifthe'Lengthattributeisrequiredtobeused,takeextracaretoensurethattheindexcomputationconsidersthestartingindexvalueforthearray.

6.31Unstructuredprogramming[EWD]

6.31.1Applicabilitytolanguage

ThevulnerabilityasdescribedinISO/IEC24772-1subclause6.31appliestoAda.Adaprogramscanexhibitmanyofthevulnerabilitiesdocumented,suchasleavingaloopatanarbitrarypoint,localjumps(goto),andmultipleexitpointsfromsubprograms.

Adahoweverdoesnotsufferfromnon-localjumpsandmultipleentriestosubprograms.

6.31.2Guidancetolanguageusers

Followthemitigationmechanismsofsubclause6.31.5ofISO/IEC24772-1:2022.

6.32Passingparametersandreturnvalues[CSJ]

6.32.1Applicabilitytolanguage

ThevulnerabilityasdescribedinISO/IEC24772-1subclause6.32doesnotapplytoAda,exceptwhenparameterpassingbyreferenceisused.Adaemploysthemechanisms(forexample,modesin,outandin out)thatarerecommendedinsubclause6.32ofISO/IEC24772-1:2022.Thesemodedefinitionsarenotoptional,modeinbeingthedefault.

6.32.2Guidancetolanguageusers

Followmitigationmechanismsofsubclause6.32.5ofISO/IEC24772-1:2022.

6.33Danglingreferencestostackframes[DCM]

6.33.1Applicabilitytolanguage

ThevulnerabilityasdescribedinISO/IEC24772-1subclause6.35doesnotapplytoAda,exceptwhenthe‘Addressor‘Unchecked_Accessattributesareused.

InAda,theattribute'Addressyieldsavalueofsomesystem-specifictypethatisnotequivalenttoapointer.Theattribute'Accessprovidesanaccessvalue(whatotherlanguagescallapointer).Addressesandaccessvaluesarenotautomaticallyconvertible,althoughapredefinedsetofgenericfunctionscanbeusedtoconvertoneintotheother.Accessvaluesaretyped,thatistosay,theycanonlydesignateobjectsofaparticulartypeorclassoftypes.

Asinotherlanguages,itispossibletoapplythe'Addressattributetoalocalvariable,andtomakeuseoftheresultingvalueoutsideofthelifetimeofthevariable.However,'AddressisveryrarelyusedinthisfashioninAda.Mostcommonly,programsuse'Accesstodesignateobjectsandsubprograms,andthelanguageenforcesaccessibilitycheckswhenevercodeattemptstousethis

40 ©ISO/IEC2022–Allrightsreserved

attributetoprovideaccesstoalocalobjectoutsideofitsscope.Theseaccessibilitycheckseliminatethepossibilityofdanglingreferences.

Asforallotherlanguage-definedchecks,accessibilitycheckscanbedisabledoveranyportionofaprogrambyusingpragma Suppress.TheattributeUnchecked_Accessproducesvaluesthatareexemptfromaccessibilitychecks.

6.33.2Guidancetolanguageusers

• Followthemitigationmechanismsofsubclause6.33.5ofISO/IEC24772-1:2022.• Onlyusethe'Addressattributeonstaticobjects(forexample,aregisteraddress).• Donotuse'Addresstoprovideindirectuntypedaccesstoanobject.• Donotconvertbetween'Addressandaccesstypes.• Useaccesstypesinallcircumstanceswhenindirectaccessisneeded.• Donotsuppressaccessibilitychecks.• Avoiduseoftheattribute'Unchecked_Access.• Use'Accessattributeinpreferenceto'Address.• ConsiderapplyingtherestrictionNo_Use_Of_Attribute(Address)toprohibituseof

'Address.• ConsiderapplyingtherestrictionNo_Unchecked_Accesstoenforcethat'Unchecked_Access

isnotused.

6.34Subprogramsignaturemismatch[OTR]

6.34.1Applicabilitytolanguage

ThevulnerabilityasdescribedinISO/IEC24772-1subclause6.34appliestoAda.

Therearetwoconcernsidentifiedwiththisvulnerability.Thefirstisthecorruptionoftheexecutionstackduetotheincorrectnumberortypeofactualparameters.Thesecondisthecorruptionoftheexecutionstackduetocallstoexternallycompiledmodules.Adadoesnotsupportvariadicsubprograms,whicheliminatesacommonsourceforthisvulnerability.Thecaseofcallstolibrarieswritteninotherlanguagesiscoveredin6.47.

InAda,atcompilationtime,theparameterassociationischeckedtoensurethatthetypeofeachactualparametermatchesthetypeofthecorrespondingformalparameter.Inaddition,theformalparameterspecificationcanincludedefaultexpressionsforaparameter.Hence,theprocedurecanbecalledwithsomeactualparametersmissing.Inthiscase,ifthereisadefaultexpressionforthemissingparameter,thenthecallwillbecompiledwithoutanyerrors.Ifdefaultexpressionsarenotspecified,thentheprocedurecallwithinsufficientactualparameterswillbeflaggedasanerroratcompilationtime.

Cautionisadvisedwhenspecifyingdefaultexpressionsforformalparameters,astheirusecanresultinsuccessfulcompilationofsubprogramcallswithanunintendedsignature.Theexecutionstackwillnotbecorruptedinthisevent,buttheprogramcanbeexecutingwithunexpectedvalues.Themostappropriateuseofdefaultexpressionsiswhen,withoutthem,therewouldendupbeing

©ISO/IEC2022–Allrightsreserved 41

anoverloadingofthesamenamewithfewerparametersthatperformedessentiallythesameoperation.WhencallingexternallycompiledmodulesthatareAdaprogramunits,thetypematchingandsubprograminterfacesignaturesaremonitoredandcheckedaspartofthecompilationandlinkingofthefullapplication.Whencallingexternallycompiledmodulesinotherprogramminglanguages,additionalstepsareneededtoensurethatthenumberandtypesoftheparametersfortheseexternalmodulesarecorrect.

6.34.2Guidancetolanguageusers

• Followthemitigationmechanismsofsubclause6.34.5ofISO/IEC24772-1:2022.• Minimizetheuseofdefaultexpressionsforformalparameters.

6.35Recursion[GDL]

6.35.1Applicabilitytolanguage

Withtheexceptionofunsafeprogramming(see5.1Languageconcepts),thevulnerabilityasdescribedinISO/IEC24772-1subclause6.35ismitigatedbyAdaastheexceptionStorage_Errorisraisedwhentherecursiveexecutionresultsininsufficientstorage.Itisalsopossibletousearecursion-depthcountertocontrolrecursivebehavior.

6.35.2Guidancetolanguageusers

• Followthemitigationmechanismsofsubclause6.35.5ofISO/IEC24772-1:2022.• Ifrecursionisused,thenuseaStorage_Errorexceptionhandlertohandleinsufficient

storageduetorecursiveexecution.• Usearecursion-depthcountertoputalimitonrecursiondepth(forexampleraisingan

exceptionifthecheckfails).• Considerusingtheasynchronouscontrolconstructtotimetheexecutionofarecursivecall

andtoterminatethecallifthetimelimitisexceeded.

6.36Ignorederrorstatusandunhandledexceptions[OYB]

6.36.1Applicabilitytolanguage

ThevulnerabilityasdescribedinISO/IEC24772-1subclause6.36appliestoAda.Adaoffersasetofpredefinedexceptionsforerrorconditionsthataredetectedbychecksthatarecompiledintoaprogram.Inaddition,theprogrammercandefineexceptionsthatareappropriatefortheirapplication.

Exceptionsarehandledusinganexceptionhandler.Exceptionscanbehandledinthescopewheretheexceptionoccurs,ortheyarepropagatedtoanenclosingscopeorthecaller.However,exceptionsthatarenothandledbyataskbodyresultinsilenttasktermination.Similarly,exceptionsthatoccurduringtheelaborationofalibrary-levelpackageresultinprogramtermination.

6.36.2Guidancetolanguageusers

42 ©ISO/IEC2022–Allrightsreserved

• Followthemitigationmechanismsofsubclause6.36.5ofISO/IEC24772-1:2022.• Usetheresultofthe'ValidattributetocheckforthevalidityofvaluesdeliveredtoanAda

programfromanexternaldevicepriortouse.• Considerusingthecall

Ada.Task_Termination.Set_Dependents_Fallback_Handlertoinstallahandlerthatwillbeinvokedwheneverataskterminates,includingduetoexceptionpropagation.

• Considerincludinganexceptionhandlerintheoutermostblockofthemainsubprogramandeachtaskbodytouseasalast-chanceexceptionhandler.

• Documentanyexceptionsthatareexpectedtobepropagatedoutofagivensubprogramortheelaborationofalibrary-levelpackage.

6.37Type-breakingreinterpretationofdata[AMV]

6.37.1Applicabilitytolanguage

ThevulnerabilityasdescribedinISO/IEC24772-1subclause6.37appliestoAdabutonlyifthemechanismsofUnsafeProgramming(5.1Languageconcepts)areused.Unchecked_Conversioncanbeusedtobypassthetype-checkingrules,anditsuseisthusunsafe,asisitsequivalentinanyotherlanguage.ThesameappliestotheuseofUnchecked_Union,eventhoughthelanguagespecifiesvariousinferencerulesthatthecompilershallusetocatchstaticallydetectableconstraintviolations.ThefactthatUnchecked_Conversionisagenericfunctionthatmustbeinstantiatedexplicitly(andgivenameaningfulname)hindersitsundisciplineduseandplacesaloudmarkerinthecodewhereveritisused.Well-writtenAdacodewillhaveasmallsetofinstantiationsofUnchecked_Conversion.Mostimplementationsrequirethesourceandtargettypestohavethesamesizeinbits,topreventaccidentaltruncationormissingsignextensions.

Typereinterpretationisauniversalprogrammingneed,andnousableprogramminglanguagecanexistwithoutsomemechanismthatbypassesthetypemodel.Adaprovidesthesemechanismswithsomeadditionalsafeguards,andmakestheirusepurposelyverbose,toalertthewriterandthereaderofaprogramtothepresenceofanuncheckedoperation.

6.37.2Guidancetolanguageusers

• Followthemitigationmechanismsofsubclause6.37.5ofISO/IEC24772-1:2022.• UseUnchecked_Uniononlyinmulti-languageprogramsthatneedtocommunicatedata

betweenAdaandCorC++.Otherwisetheuseofdiscriminatedtypesprevents"punning"betweenvaluesoftwodistincttypesthathappentosharestorage.

• AvoidusingtheAddressaspectoraddressclausestoobtainoverlays,includingavoidingAddress_to_Access_Conversions.Ifthetypesoftheobjectsarethesame,thenarenamingdeclarationispreferable.Otherwise,usethepragma Importtoinhibittheinitializationofoneoftheentitiessothatitdoesnotinterferewiththeinitializationoftheotherone.

• Considerapplying pragma Restrictions (No_Specification_Of_Aspect => Unchecked_Union), pragma Restrictions (No_Use_Of_Attribute => Address), and pragma Restrictions (No_Dependence => System.Address_to_Access_Conversions) toensurethisvulnerabilitycannotarise.

©ISO/IEC2022–Allrightsreserved 43

6.38Deepvs.shallowcopying[YAN]

6.38.1Applicabilitytolanguage

Thevulnerabilitydescribedinsubclause6.38ofISO/IEC24772-1appliestoAda.Itcanbemitigatedsomewhatbylanguageconstructsthatallowthecreationofabstractionsandtheadditionofuser-definedcopyingoperations,suchthatinadvertentaliasingproblemscanbecontainedwithintheabstraction.Thedefaultsemanticsofassignmentcreateashallowcopy,whenappliedtotherootofagraphstructure.

6.38.2Guidancetolanguageusers

• Followthemitigationmechanismsofsubclause6.38.5ofISO/IEC24772-1:2022.• UsecontrolledtypesandappropriateredefinitionsoftheInitialize,Adjust,andFinalize

operationtocreatedeepcopieswhenneeded.• Useapre-existingContainertypefortrees.

6.39Memoryleakandheapfragmentation[XYL]

6.39.1Applicabilitytolanguage

ThevulnerabilityasdescribedinISO/IEC24772-1subclause6.39appliestoAda.Forobjectsthatareallocatedfromtheheapwithouttheuseofreferencecounting,thememoryleakvulnerabilityispossibleinAda.Forobjectsthatallocatefromastoragepool,thevulnerabilityispresentbutisrestrictedtothissinglepool,whichmakesiteasiertodetectmemoryleaksbyverification.Subpoolscanbeusedtofurtherreducethepossibilityformemoryleaks.Forobjectsofacontrolledtypethatusesreferencingcountingandthatarenotpartofacyclicreferencestructure,thevulnerabilitydoesnotexist.

Adaensuresthatobjectsdesignatedbyanaccesstypedeclaredinanestedscopearefinalizedwhenexecutionleavesthenestedscope,however,itisimplementationdefinedwhetherstorageisreclaimedforthiscase.Associatinganaccesstypewithastoragepoolcanensurethatthestoragereclamationtakesplace.

Adadoesnotmandatetheuseofagarbagecollector,butAdaimplementationsarefreetoprovidesuchmemoryreclamation.Forapplicationsthatuseandreturnmemoryonanimplementationthatprovidesgarbagecollection,theissuesassociatedwithgarbagecollectionexistinAda.

6.39.2Guidancetolanguageusers

• Followthemitigationmechanismsofsubclause6.39.5ofISO/IEC24772-1:2022.• Usecontrolledtypesandreferencecountingtoimplementexplicitstoragemanagement

systemsthatcannothavestorageleaks.• Declareaccesstypesinanestedscopewherepossible.• Considertheuseofpredefinedcontainerlibrarieswherepossible.• Considertheuseofuser-definedstoragepoolsandsubpools.

44 ©ISO/IEC2022–Allrightsreserved

• Useacompletelystaticmodelwhereallstorageisallocatedfromglobalmemoryandexplicitlymanagedunderprogramcontrol.

6.40Templatesandgenerics[SYM]

Withtheexceptionofunsafeprogramming(see5.1Languageconcepts),thevulnerabilityasdescribedinISO/IEC24772-1subclause6.40doesnotapplytoAdaastheAdagenericsmodelisbasedonimposingacontractonthestructureandoperationsofthetypesthatcanbeusedforinstantiation.Also,explicitinstantiationofthegenericisrequiredforeachparticulartype.

Therefore,thecompilerisabletocheckthegenericbodyforprogrammingerrors,independentlyofactualinstantiations.Ateachactualinstantiation,thecompilerwillalsocheckthattheinstantiatedtypemeetsalltherequirementsofthegenericcontract.

Adaalsodoesnotallowfor‘specialcase’genericsforaparticulartype,thereforebehaviourisconsistentforallinstantiations.

6.41Inheritance[RIP]

6.41.1Applicabilitytolanguage

ThevulnerabilitydocumentedinISO/IEC24772-1subclause6.41appliestoAda.

Adaallowsonlyarestrictedformofmultipleinheritance,whereonlyoneofthemultipleancestors(theparent)ispermittedtoimplementoperations.Allotherancestors(interfaces)canonlyspecifytheoperations’signature,andwhethertheoperationisrequiredtobeoverridden,orcansimplydonothingifneverexplicitlydefined.Therefore,Adadoesnotsufferfrommultipleinheritancerelatedvulnerabilities.

Adahasnopreferencerulestoresolveambiguitiesofcallsonprimitiveoperationsoftaggedtypes.HencetherelatedvulnerabilitydocumentedinISO/IEC24772-1:2022subclause6.41doesnotapplytoAda.

6.41.2Guidancetolanguageusers

• Followthemitigationmechanismsofsubclause6.41.5ofISO/IEC24772-1:2022.• Usetheoverridingindicatorsonpotentiallyinheritedsubprogramstoensurethatthe

intendedsetofoperationsareoverridden,thuspreventingtheaccidentalredefinitionorfailuretoredefineanoperationoftheparent.

• Specifyaspect Pre’Classandaspect Post’Classaspectswhenaprimitiveoperationisinitiallydefined,toindicatethepropertiesofinputsthatanyoverridingsshallaccept,andthepropertiesofoutputsthatanyoverridingsshallproduce.

6.42ViolationsoftheLiskovsubstitutionprincipleorthecontractmodel[BLP]

6.42.1Applicabilitytolanguage

©ISO/IEC2022–Allrightsreserved 45

ThevulnerabilityasdescribedinISO/IEC24772-1subclause6.42appliestoAda.Thevulnerabilitiesmaybemitigatedbytheuseoflanguageconceptsofspecified/enforcedpre-andpostconditionsofmethods.

Whendefiningonetypeasadescendantofanotherandoverridingexistingprimitiveoperationsoftheancestortype,theLiskovSubstitutionPrinciple(LSP)arguesforensuringthattheimportantpropertiesoftheoperationsarepreservedinthedescendanttypes,accordingtotherulesofbehaviouralsubtyping.InAda,thiscanbeenforcedbyspecifyingthesepropertiesusingthePre’ClassandPost’Class aspectswhentheoperationisfirstdefined,todefinetherelevantpre-andpostconditions(respectively)whicharetoapplytotheoperationsandanyoverridings.Run-timecheckswillbeprovidedbytheAdaimplementationonallcallsoftheseoperationsandtheiroverridings,toverifythattheinputsprovidedbythecallersatisfytherequiredpreconditions,andthattheoutputsproducedbytheoperationsatisfytherequiredpostconditions.Adaallowstheseaspectstoberefinedinoverridings,butonlyinwaysthatareconsistentwithLSP,meaningthattheeffectiveclass-widepreconditionscanonlyberelaxedinoverridings,nevermademorestringent,andtheeffectiveclass-widepostconditionscanonlybetightened,nevermadelooser.ThisensuresthatifacallerisreachinganoperationofadescendanttypewhilebeingonlyawareofthePre’ClassandPost’Classaspectsofanancestoroperation,anyinputthatsatisfiestheancestorPre’ClasswillstillsatisfythedescendanteffectivePre’Class,andanyoutputthatsatisfiesthedescendanteffectivePost’Classwillalsosatisfytheancestor’sPost’Class.

6.42.2GuidancetoLanguageUsers

• Followthemitigationmechanismsofsubclause6.42.5ofISO/IEC24772-1:2022.• SpecifyPre’ClassandPost’Classforallprimitiveoperationsoftaggedtypes.

6.43Redispatching[PPH]

6.43.1Applicabilitytolanguage

ThevulnerabilityasdescribedinISO/IEC24772-1subclause6.43appliestoAda.Thedefaultbehaviouroftherelevantcallsisnon-dispatchinginAda,whichisnotsubjecttothisvulnerability,butuponexplicitlycodingaredispatchingcall,thisvulnerabilitymayoccur.

Adadistinguishesbetweenaspecifictype Tandaclass-widetype T’Class.Ifdispatchingisbeingperformedwithinaroutineonaparticularformalparameter,itispreferablethattheparameterbedeclaredasclass-widetodocumentthisinternaluseofdispatching.Adapermitsanexplicitconversionfromaspecifictypetoaclass-widetypetoperformre-dispatching,butthisshouldbeavoidedwhenpossible,anddocumentedexplicitlywhennecessary.

6.43.2GuidancetoLanguageUsers

• Followthemitigationmechanismsofsubclause6.43.5ofISO/IEC24772-1:2022.• Ifredispatchingisnecessary,documentthebehaviourexplicitly.

46 ©ISO/IEC2022–Allrightsreserved

6.44Polymorphicvariables[BKK]

6.44.1Applicabilitytolanguage

Withtheexceptionofunsafeprogramming(see5.1Languageconcepts),thevulnerabilitydescribedinISO/IEC24772-1subclause6.44ismitigatedbyAdaasrun-timeschecksidentifyfaultyuses.

Adachecksallconversionstodescendanttaggedtypes(downwardconversions)tobesuretherun-timetagoftheobjectbeingconvertedmatchesthatofthetargettype,oroneofitsdescendants.Toavoidthefailureofsuchatagcheck,theprogrammershoulduseaclass-widemembershiptest(“ObjinTarget’Class”)orrelyonadispatchingcalltoperformtheappropriatedownwardconversionimplicitly.

Althoughconversionsuptoancestorsarealwaysstructurallysafe(upwardconversions),inthattheancestorhasasubsetofthedatacomponentsofanydescendant,aconversiontoaspecific(asopposedtoclass-wide)ancestortypemayviolatesemanticrequirementsofthedescendanttype,particularlyifthedescendanttypeisaprivateextensionoftheancestorandhascertaindesiredrelationshipsbetweencomponentsoftheextensionandthoseinheritedfromtheancestor.ByspecifyingaType_Invariantaspectonaprivateextension,theprogrammercanensurethatthesemanticrequirementsoftheprivateextension,ascapturedbythetypeinvariant,arepreservedacrosssuchconversionstoanancestorspecifictype,inthattheyarere-checkedaftertheconstructmanipulatingtheupwardconversioniscomplete.

6.44.2GuidancetoLanguageUsers

Followthemitigationmechanismsofsubclause6.44.5ofISO/IEC24772-1:2022.

6.45Extraintrinsics[LRM]

ThevulnerabilityasdescribedinISO/IEC24772-1subclause6.45doesnotapplytoAda.InAda,allsubprograms,whetherintrinsicornot,belongtothesamenamespace.Adaspecifiesthatallsubprogramsshallbeexplicitlydeclared,andthesamenameresolutionrulesapplytoallofthem,whethertheyarepredefinedoruserdefined.Iftwosubprogramswiththesamenameandsignaturearevisible(thatistosaynameable)atthesameplaceinaprogram,thenacallusingthatnamewillberejectedasambiguousbythecompiler,andtheprogrammerwillhavetospecify(forexample,bymeansofanexpandedname)whichsubprogramismeant.

6.46Argumentpassingtolibraryfunctions[TRJ]

6.46.1Applicabilitytolanguage

ThevulnerabilityasdescribedinISO/IEC24772-1appliestoAda.Adaparametersmayhavevaluesprecludedbypreconditionsofthecalledroutine.

©ISO/IEC2022–Allrightsreserved 47

TotheextentthatthepreclusionofvaluescanbeexpressedaspartofthetypesystemofAda,however,thepreconditionsarecheckedbythecompilerstaticallyordynamicallyandthusarenolongervulnerabilities.Forexample,anyrangeconstraintonvaluesofaparametercanbeexpressedinAdabymeansoftypeorsubtypedeclarations.Typeviolationsaredetectedatcompiletime,subtypeviolationscauserun-timeexceptions.Inaddition,preconditions,postconditions,typeinvariants,andsubtypepredicatescanbespecifiedexplicitlytoexpressmorecomplexrestrictionstobeobservedbycallers.Thesearecheckedatrun-timedependingontheAssertion_Policyineffect,andcanberecognizedbyotherstaticanalysistoolsaspartofprogramverification.

6.46.2Guidancetolanguageusers

• Followthemitigationmechanismsofsubclause6.46.5ofISO/IEC24772-1:2022.• ExploitthetypeandsubtypesystemofAdatoexpressrestrictionsonthevaluesof

parametersandresults.• Specifyexplicitpreconditionsandpostconditionsforsubprogramswhereverpractical.• Specifysubtypepredicatesandtypeinvariantsforsubtypesandprivatetypeswhen

appropriate.• Specifytheexceptionraisedorotherresponsetovaluesthatdonotsatisfytheprecondition.

6.47Inter-languagecalling[DJS]

6.47.1ApplicabilitytoLanguage

ThevulnerabilityasdescribedinISO/IEC24772-1subclause6.47ismitigatedbyAdaasAdaprovidesmechanismstointerfacewithcommonlanguages,suchasC,C++,FortranandCOBOL,sothatvulnerabilitiesassociatedwithinterfacingwiththeselanguagescanbeavoided.

6.47.2GuidancetoLanguageUsers

• Followthemitigationmechanismsofsubclause6.47.5ofISO/IEC24772-1:2022.• Usetheinter-languagemethodsandsyntaxspecifiedbyISO/IEC8652whentheroutinesto

becalledarewritteninlanguagesthatISO/IEC8652specifiesaninterfacewith,includingaspectsImport,Export,andConvention.

• UseinterfacestotheCprogramminglanguagewheretheotherlanguagesystem(s)arenotcoveredbyISO/IEC8652,buttheotherlanguagesystemshaveinterfacingtoC.

• Makeexplicitchecksonallreturnvaluesfromforeignsystemcodeartifacts,forexamplebyusingthe'Validattributeorbyperformingexplicitteststoensurethatvaluesreturnedbyinter-languagecallsconformtotheexpectedrepresentationandsemanticsoftheAdaapplication.

• ConsiderhandlinganyexceptionsthatmayberaisedinAdacodebeforereturningtoaroutinefromaforeignlanguage,topreventpossiblestackcorruptioniftheforeignlanguagecannothandleexceptionsraisedinAdacode.

6.48Dynamically-linkedcodeandself-modifyingcode[NYY]

Withtheexceptionofunsafeprogramming(see5.1Languageconcepts),thevulnerabilitydescribedinISO/IEC24772-1subclause6.48doesnotapplytoAdaasAdadoesnotsupporteitherdynamic

48 ©ISO/IEC2022–Allrightsreserved

linkingorself-modifyingcode.Thelatterispossibleonlybyexploitingothervulnerabilitiesofthelanguageinthemostmaliciouswaysandeventhenitisstillverydifficulttoachieve.

6.49Librarysignature[NSQ]

6.49.1Applicabilitytolanguage

ThevulnerabilityasdescribedinISO/IEC24772-1subclause6.49appliestoAda.Adaprovidesmechanismstoexplicitlyinterfacetomoduleswritteninotherlanguages.AspectsImport,Export,andConventionpermitthenameoftheexternalunitandtheinterfacingconventiontobespecified.

EvenwiththeuseofaspectsImport,Export,andConvention,thevulnerabilitiesstatedinsubclause6.49ofISO/IEC24772-1:2022arepossible.Namesandnumberofparameterschangeundermaintenance;callingconventionschangeascompilersareupdatedorreplaced,orlanguagesareusedforwhichAdadoesnotspecifyacallingconvention.

6.49.2Guidancetolanguageusers

Followthemitigationmechanismsofsubclause6.49.5ofISO/IEC24772-1:2022.

6.50Unanticipatedexceptionsfromlibraryroutines[HJW]

6.50.1Applicabilitytolanguage

ThevulnerabilityasdescribedinISO/IEC24772-1subclause6.50appliestoAda.Adaprogramsarecapableofhandlingexceptionsatanylevelintheprogram,aslongasanyexceptionnaminganddeliverymechanismsarecompatiblebetweentheAdaprogramandthelibrarycomponents.InsuchcasesthenormalAdaexceptionhandlingprocesseswillapply,andeitherthecallingunitorsomesubprogramortaskinitscallchainwillcatchtheexceptionandtakeappropriateprogrammedaction.Ifnoactionistakentohandletheexception,thetaskorprogramwheretheexceptionoccurredwillterminate.

Ifthelibraryconventionistoreporterrorsbymeansoferrorcodesandnotbyexceptions,thenifthelibrarycomponentsthemselvesarewritteninAda,thenAda'sexceptionhandlingmechanismsletallcalledunitstrapanyexceptionsthataregeneratedandreturnerrorcodesinstead.

IftheinterfacebetweentheAdaunitsandthelibraryroutinebeingcalleddoesnotadequatelyaddresstheissueofnaming,generationanddeliveryofexceptionsacrosstheinterface,thenthevulnerabilitiesasexpressedinsubclause6.50ofISO/IEC24772-1:2022apply.

6.50.2Guidancetolanguageusers

• Followthemitigationmechanismsofsubclause6.50.5ofISO/IEC24772-1:2022.• Ensurethattheinterfaceswithlibrarieswritteninotherlanguagesarecompatibleinthe

namingandgenerationofexceptions.

©ISO/IEC2022–Allrightsreserved 49

• Putappropriateexceptionhandlersinallroutinesthatcalllibraryroutines,includingthecatch-allexceptionhandlerwhen others=>.

• Putappropriateexceptionhandlersinallroutinesthatarecalledbylibraryroutines,includingthecatch-allexceptionhandlerwhen others=>.

• DocumentanyexceptionsthatmayberaisedbyanyAdaunitsbeingusedaslibraryroutines.

6.51Pre-processordirectives[NMP]

ThevulnerabilityasdescribedinISO/IEC24772-1subclause6.51doesnotapplytoAdaasAdadoesnothaveapre-processor.

6.52Suppressionoflanguage-definedrun-timechecking[MXB]

6.52.1ApplicabilitytoLanguage

ThevulnerabilityasdescribedinISO/IEC24772-1subclause6.52appliestoAda.TheAdapragma Suppress()permitsexplicitsuppressionoflanguage-definedchecksonaunit-by-unitbasisoronpartitionsorprogramsasawhole.(Thelanguage-defineddefault,however,istoperformtherun-timechecksthatpreventrun-timevulnerabilities.)Pragma Suppresscansuppressalllanguage-definedchecksorindividualcategoriesofchecks(seesubclause11.5ofISO/IEC8652).

6.52.2GuidancetoLanguageUsers

Followthemitigationmechanismsofsubclause6.52.5ofISO/IEC24772-1:2022.

6.53Provisionofinherentlyunsafeoperations[SKL]

6.53.1ApplicabilitytoLanguage

ThevulnerabilityasdescribedinISO/IEC24772-1subclause6.53appliestoAda.Inrecognitionoftheoccasionalneedtostepoutsidethetype-systemortoperform“risky”operations,Adaprovidesclearlyidentifiedlanguagefeaturestodoso.ExamplesincludethegenericUnchecked_ConversionforunsafetypeconversionsorUnchecked_Deallocation forthedeallocationofheapobjectsregardlessoftheexistenceofsurvivingreferencestotheobject.Ifunsafeprogrammingisemployedinaunit,thentheunitneedstospecifytherespectivegenericunitinitscontextclause,thusidentifyingpotentiallyunsafeunits.Similarly,therearewaystocreateapotentiallyunsafeglobalpointertoalocalobject,usingtheUnchecked_Accessattribute.

6.53.2Guidancetolanguageusers

• Followthemitigationmechanismsofsubclause6.53.5ofISO/IEC24772-1:2022.• Avoidtheuseofunsafeprogrammingpractices,usethepragma Restrictions()toprevent

theinadvertentuseofunsafelanguageconstructs.• Carefullyscrutinizeanycodethatreferstoaprogramunitexplicitlydesignatedtoprovide

uncheckedoperations.

50 ©ISO/IEC2022–Allrightsreserved

6.54Obscurelanguagefeatures[BRS]

6.54.1Applicabilitytolanguage

ThevulnerabilityasdescribedinISO/IEC24772-1subclause6.54appliestoAda.Adaisarichlanguageandprovidesfacilitiesforawiderangeofapplicationareas.Becausesomeareasarespecialized,itislikelythataprogrammernotversedinaspecialareacanmisusefeaturesforthatarea.Forexample,theuseoftaskingfeaturesforconcurrentprogrammingrequiresknowledgeofthisdomain.Similarly,theuseofexceptionsandexceptionpropagationandhandlingrequiresadeeperunderstandingofcontrolflowissuesthansomeprogrammerspossess.

6.54.2Guidancetolanguageusers

• Followthemitigationmechanismsofsubclause6.54.5ofISO/IEC24772-1:2022.• Usethepragma Restriction()topreventtheuseofobscurefeaturesofthelanguage.• Similarly,avoidfeaturesinaSpecializedNeedsAnnexofISO/IEC8652unlessthe

applicationareaconcernediswell-understood.• TherestrictionNo_Dependencepreventstheuseofspecifiedpre-definedoruser-defined

libraries.

6.55Unspecifiedbehaviour[BQF]

6.55.1Applicabilitytolanguage

ThevulnerabilityasdescribedinISO/IEC24772-1subclause6.55appliestoAda.InAda,therearetwomaincategoriesofunspecifiedbehaviour,onehavingtodowithunspecifiedaspectsofnormalrun-timebehaviour,andonehavingtodowithboundederrors,errorsthatneednotbedetectedatrun-timebutforwhichthereisalimitednumberofpossiblerun-timeeffects(thoughalwaysincludingthepossibilityofraisingProgram_Errorexception).

Forthenormalbehaviourcategory,thereareseveraldistinctaspectsofrun-timebehaviourthatmaybeunspecified,including:

• Orderinwhichcertainactionsareperformedatrun-time;• Numberoftimesagivenelementoperationisperformedwithinanoperationinvokedona

compositeorcontainerobject;• Resultsofcertainoperationswithinalanguage-definedgenericpackageiftheactual

associatedwithaparticularformalsubprogramdoesnotmeetstatedexpectations(suchas“<”providingastrictweakorderingrelationship);

• Whetherdistinctinstantiationsofagenericordistinctinvocationsofanoperationproducedistinctvaluesfortagsoraccess-to-subprogramvalues.

TheindexentryintheISO/IEC8652forunspecifiedprovidesthefulllist.Similarly,theindexentryforboundederrorprovidesthefulllistofreferencestoplacesinISO/IEC8652whereaboundederrorisdescribed.

©ISO/IEC2022–Allrightsreserved 51

Failurecanoccurduetounspecifiedbehaviourwhentheprogrammerdidnotfullyaccountforthepossibleoutcomes,andtheprogramisexecutedinacontextwheretheactualoutcomewasnotoneofthosehandled,resultingintheprogramproducinganunintendedresult.

6.55.2Guidancetolanguageusers

• Followthemitigationmechanismsofsubclause6.55.5ofISO/IEC24772-1:2022.• Forsituationsinvolvinggenericformalsubprograms,ensurethattheactualsubprogram

satisfiesallofthestatedexpectations.• Forsituationsinvolvingunspecifiedvalues,avoiddependingonequalitybetweenpotentially

distinctvalues.• Forsituationsinvolvingboundederrors,avoidtheproblemcompletely,byensuringinother

waysthatallrequirementsforcorrectoperationaresatisfiedbeforeinvokinganoperationthatcanresultinaboundederror.Seesubclause6.22Initializationofvariables[LAV]foradiscussionofuninitializedvariablesinAda,acommoncauseofaboundederror.

6.56Undefinedbehaviour[EWF]

6.56.1Applicabilitytolanguage

ThevulnerabilityasdescribedinISO/IEC24772-1subclause6.56appliestoAda.InAda,undefinedbehaviouriscallederroneousexecution,andcanarisefromcertainerrorsthatarenotrequiredtobedetectedbytheimplementation,andwhoseeffectsarenotingeneralpredictable.

Therearevariouskindsoferrorsthatcanleadtoerroneousexecution,including:

• Changingadiscriminantofarecord(byassigningtotherecordasawhole)whilethereremainactivereferencestosubcomponentsoftherecordthatdependonthediscriminant;

• Referringviaanaccessvalue,taskid,ortag,toanobject,task,ortypethatnolongerexistsatthetimeofthereference;

• Referringtoanobjectwhoseassignmentwasdisruptedbyanabortstatement,priortoinvokinganewassignmenttotheobject;

• Sharinganobjectbetweenmultipletaskswithoutadequatesynchronization;• Suppressingalanguage-definedcheckthatisinfactviolatedatrun-time;• Specifyingtheaddressoralignmentofanobjectinaninappropriateway;• UsingUnchecked_Conversion,Address_To_Access_Conversions,orcallinganimported

subprogramtocreateavalue,orreferencetoavalue,thathasaninvalidrepresentation.ThefulllistisgivenintheindexofISO/IEC8652undererroneousexecution.

Anyoccurrenceoferroneousexecutionrepresentsafailuresituation,astheresultsareunpredictable,andmayinvolveoverwritingofmemory,jumpingtounintendedlocationswithinmemory,andotheruncontrolledevents.

6.56.2Guidancetolanguageusers

• Followthemitigationmechanismsofsubclause6.56.5ofISO/IEC24772-1:2022.

52 ©ISO/IEC2022–Allrightsreserved

• Ensurethatalldatasharedbetweentasksareeitherprivatewithinaprotectedobjectormarkedatomic;

• Uponanyuseof Unchecked_Deallocation,carefullychecktobesurethattherearenoremainingreferencestotheobject;

• Usepragma Suppresssparingly,andonlyafterthecodehasundergoneextensiveverification.Theothererrorsthatcanleadtoerroneousexecutionarelesscommon,butclearlyinanygivenAdaapplication,careisrequiredwhenusingfeaturessuchas:

• abort;• Unchecked_Conversion;• Address_To_Access_Conversions;• Theresultsofimportedsubprograms;• Discriminant-changingassignmentstoglobalvariables.

6.57Implementation-definedbehaviour[FAB]

6.57.1Applicabilitytolanguage

ThevulnerabilityasdescribedinISO/IEC24772-1subclause6.57appliestoAda.ThereareanumberofsituationsinAdawherethelanguagesemanticsareimplementationdefined,toallowtheimplementationtochooseanefficientmechanism,ortomatchthecapabilitiesofthetargetenvironment.EachofthesesituationsisidentifiedinAnnexMofISO/IEC8652,andimplementationsarerequiredtoprovidedocumentationassociatedwitheachiteminAnnexMtoprovidetheprogrammerwithguidanceontheimplementationchoices.

AfailurecanoccurinanAdaapplicationduetoimplementation-definedbehaviouriftheprogrammerpresumedtheimplementationmadeonechoice,wheninfactitmadeadifferentchoicethataffectedtheresultsoftheexecution.Inmanycases,acompiletimemessageorarun-timeexceptionwillindicatethepresenceofsuchaproblem.Forexample,therangeofintegerssupportedbyagivencompilerisimplementationdefined.However,iftheprogrammerspecifiesarangeforanintegertypethatexceedsthatsupportedbytheimplementation,thenacompiletimeerrorwillbeindicated,andifatrun-timeacomputationexceedsthebaserangeofanintegertype,thenConstraint_Errorisraised.

Asindicatedabove,manysuchfailuresareindicatedbycompiletimeerrormessagesorrun-timeexceptions.However,therearecaseswheretheimplementation-definedbehaviourmaybesilentlymisconstrued,suchasiftheimplementationpresumesAda.Exceptions.Exception_Informationreturnsastringwithaparticularformat,wheninfacttheimplementationdoesnotusetheexpectedformat.IfaprogramisattemptingtoextractinformationfromAda.Exceptions.Exception_Informationforthepurposesofloggingpropagatedexceptions,thenthelogmayendupwithmisleadingoruselessinformationifthereisamismatchbetweentheprogrammer’sexpectationandtheactualimplementation-definedformat.

Manyimplementation-definedlimitshaveassociatedconstantsdeclaredinlanguage-definedpackages,generallypackage System.Inparticular,themaximumrangeofintegersisgivenbySystem.Min_Int .. System.Max_Int,andotherlimitsareindicatedbyconstantssuchas

©ISO/IEC2022–Allrightsreserved 53

System.Max_Binary_Modulus,System.Memory_Size,System.Max_Mantissa,andsimilar.Otherimplementation-definedlimitsareimplicitinnormal‘Firstand‘Lastattributesoflanguage-defined(sub)types,suchasSystem.Priority'FirstandSystem.Priority'Last.Furthermore,theimplementation-definedrepresentationaspectsoftypesandsubtypescanbequeriedbylanguage-definedattributes.Thus,codecanbeparameterizedtoadjusttoimplementation-definedpropertieswithoutmodifyingthecode.

6.57.2Guidancetolanguageusers

• Followthemitigationmechanismsofsubclause6.57.5ofISO/IEC24772-1:2022.• BeawareofthecontentsofAnnexMofISO/IEC8652andavoidimplementation-defined

behaviourwheneverpossible.• Makeuseoftheconstantsandsubtypeattributesprovidedinpackage Systemand

elsewheretoavoidexceedingimplementation-definedlimits.• Minimizeuseofanypredefinednumerictypes,astherangesandprecisionsoftheseareall

implementationdefined.Instead,declareyourownnumerictypestomatchyourparticularapplicationneeds.

• Whenthereareimplementation-definedformatsforstrings,suchasException_Information,localizeanynecessaryprocessinginpackageswithimplementation-specificvariants.

6.58Deprecatedlanguagefeatures[MEM]

6.58.1Applicabilitytolanguage

ThevulnerabilityasdescribedinISO/IEC24772-1clause6.58appliestoAda.Adahasobsolescentfeaturesthatcanbeusedbutprovidesastrongmitigation,intheformofthecompilationpragmaRestrictions (No_Obsolescent_Features)whichpreventstheuseofanyofthesefeatures.

6.58.2Guidancetolanguageusers

• Followthemitigationmechanismsofsubclause6.58.5ofISO/IEC24772-1:2022.• Usepragma Restrictions (No_Obsolescent_Features)topreventtheuseofany

obsolescentfeatures.• RefertoAnnexJoftheISO/IEC8652todeterminewhetherafeatureisobsolescent.

6.59Concurrency–Activation[CGA]

6.59.1Applicabilitytolanguage

ThevulnerabilityasdescribedinISO/IEC24772-1subclause6.59appliestoAda.Adaisopentothisvulnerabilitybutprovidesfeaturesforitsmitigation.Ataskfailingduringactivationwillalwaysraiseanexceptionintheactivatingtask(i.e.,Tasking_Error).Theactivatingtaskdoesnotcontinueexecutinguntilallitsdependenttaskshavecompletedactivation.Ataskcanalwayscheckthatanothertaskhassuccessfullyactivated.

6.59.2Guidancetolanguageusers

54 ©ISO/IEC2022–Allrightsreserved

• Followthemitigationmechanismsofsubclause6.59.5ofISO/IEC24772-1:2022.• Provideahandlertocatchactivationfailuresoflocaltasks.• Ifpossible,declarealltasksstaticallyatthelibrarylevelanduselanguage-providedmeans

toverifysuccessfulactivation.

6.60Concurrency–Directedtermination[CGT]

6.60.1Applicabilitytolanguage

ThevulnerabilityasdescribedinISO/IEC24772-1subclause6.60appliestoAda.Adadefinesabort-deferredregionsinwhichtaskterminationwillnotoccur.Onasingleprocessor,abortisdefinedtobeimmediateifthetaskisnotinsucharegion.Onmultiprocessors,abortmaynotbeimmediatebutwillbebeforeanysynchronization(dispatching)point.

6.60.2Guidancetolanguageusers

• Followthemitigationmechanismsofsubclause6.60.5ofISO/IEC24772-1:2022.• Usethe'Terminatedand'Callableattributestocheckthatataskhasterminated.• Minimizethesizeofanyabort-deferredregion.• Removeanypossibilityofunboundedloopsinabort-deferredregions.• Wherepossible,applypragma Restrictions (No_Abort_Statements)toeliminatetheuse

ofthisconstruct.

6.61Concurrentdataaccess[CGX]

6.61.1Applicabilitytolanguage

ThevulnerabilityasdescribedinISO/IEC24772-1subclause6.61appliestoAda.Adadoesallowtaskstoaccessunprotectedsharedvariables.However,thestandardmeansofprogrammingdatathatissharedbetweentasksistouseaprotectedobjectthatenforcesserialaccess.Atomicaccessesonsomesimpletypesaresupported(ifsupportedbythehardware).

6.61.2Guidancetolanguageusers

• Followthemitigationmechanismsofsubclause6.61.5ofISO/IEC24772-1:2022.• Preferprotectedobjectsforshareddatainpreferencetoatomic,volatileorunmarkeddata.• Staticallydeterminethatnounprotecteddataisuseddirectlybymorethanonetask.• Whensharedvariablesareused,employmodelcheckingorequivalentmethodologiesto

provetheabsenceofraceconditions.• Usepragma Atomicandpragma Atomic_Componentstoensurethatallaccessestoobjects

andcomponentshappenatomically.• Usepragma Volatileandpragma Volatile_Components toensurethatalltasksseewrites

totheassociatedobjectsorarraycomponentsinthesameorder.

6.62Concurrency–Prematuretermination[CGS]

6.62.1Applicabilitytolanguage

©ISO/IEC2022–Allrightsreserved 55

ThevulnerabilityasdescribedinISO/IEC24772-1subclause6.62appliestoAda.AnAdataskcanterminatesilently,howeveringeneralthetaskingmodelisrobustandanumberoffeaturesareavailabletomitigateagainstthisvulnerability–seeguidancebelow.

6.62.2Guidancetolanguageusers

• Followthemitigationmechanismsofsubclause6.62.5ofISO/IEC24772-1:2022.• Ifpossible,applypragma Restrictions (No_Abort_Statements)toeliminatetheuseofthis

construct.• Alltasksshouldcontainanexceptionhandlerattheouterleveltopreventsilenttermination

duetounhandledexceptions.• Makeuseofpackage Ada.Task_Terminationtoforceahandlertobeexecutedwhenatask

terminates.• Useattributes'Terminatedand'Callabletoconfirmthatataskhasnotterminated

(althoughcareisneededhereasataskcanterminateimmediatelyafterthiscallismade).• Ensurethatallaccessesandupdatestodatathatisvulnerabletoprematuretask

terminationareexecutedinabort-deferredregions(e.g.,protectedoperations).• Makeuseoftimedtaskcommunicationthatwilltime-outifthecalledtaskdoesnotrespond.

6.63Lockprotocolerrors[CGM]

6.63.1Applicabilitytolanguage

Withtheexceptionofunsafeprogramming(see5.1Languageconcepts),thevulnerabilityasdescribedinISO/IEC24772-1subclause6.63ismitigatedbyAda.LocksareimplicitinAdaprotectedobjects,andexplicitlocks(likesemaphoresormutexes)canbeimplementedbycodingprotectedobjectsortaskswithexplicit“lock”and“unlock”operations.Forexplicitlycodedlocks,anyofthewell-knownlockprotocolerrorscanoccur.Forthelocksimplicitinprotectedobjects,protocolerrorscanoccurinthefollowingways:

• Byan“external”call,or“external”requeue,toaprotectedobjectthatisalreadylockedbythecaller.Acallorrequeuetoaprotectedobjectis“external”whenthecalleeobjectisnotstaticallyknowntobethe“currentobject”,whichmeansthatthecallorrequeuetriestoacquiretheimplicitlockofthecalleeobject.

• Bydirectlyorindirectlyinvokinganyotherpotentiallyblockingoperation,suchasadelaystatement,duringaprotectedaction(thatis,fromcodeexecutedinaprotectedobject).

• Byacallfromataskthathasapriorityhigherthantheceilingpriorityofthecalleeprotectedobject,whenlockingisimplementedbyceilingpriorities(theCeiling_Lockingpolicy).

Thefirsttwocases,invokingpotentiallyblockingoperations,arebydefaultboundederrorsthatarenotrequiredtobedetected,neitheratcompiletimenoratrun-time.Ifnotdetected,theresultcanbedeadlockorviolationofmutualexclusion.DifferentimplementationsofAdamaybehavedifferentlyandunpredictably.However,usingthepragma Detect_Blockingforcesarun-timecheck,whichraisestheProgram_Errorexceptionincaseoffailure.Forthelastcase,ceilingpriorityviolation,sucharun-timecheckisalwaysperformed.

56 ©ISO/IEC2022–Allrightsreserved

Ingeneral,whetheranAdaprogramrisksanyoftheseerrorscanbedeterminedonlybyaglobalanalysisoftheprogram,includingthefullcaller-calleerelationship.Suchananalysisbecomesmuchharder,andoftenimpossible,ifcalleesaredefineddynamicallybyaccessvaluesoriftaskprioritiesorceilingprioritiesaremodifieddynamically.

6.63.2Guidancetolanguageusers

• Followthemitigationmechanismsofsubclause6.63.5ofISO/IEC24772-1:2022.• Makeuseoflooselycoupledcommunicationusingprotectedobjects.• WherepossiblestaywithintheconstraintsdefinedbytheRavenscartaskingprofile

[19][24].• Usepragma Detect_Blockingtoensureblockingerrorsaredetected.• Ifsynchronouscommunication(rendezvous)isemployed,usemodelcheckingorequivalent

toprovethattheprogramisfreefromdeadlocksetc.• Alwayshandleexceptionsthatcanarrivefromrendezvousorprotectedobjects(unlessthey

canbeprovedtonotberaised).• Guardagainstprotocolfailuresbyusingtimedcommunication,watchdogtimers

(programmedusingAda’stimedevents)andtime-stampeddata(usingAda’sclockfacilities).Donotuseunprotectedshareddataforsynchronizationbetweentasks.

6.64Relianceonexternalformatstrings[SHL]

ThevulnerabilityasdescribedinISO/IEC24772-1subclause6.63doesnotapplytoAda,becauseAdadoesnotprovideformatstrings.

6.65Modifyingconstants[UJO]

6.65.1Applicabilitytolanguage

ThevulnerabilitydescribedinISO/IEC24772-1appliestoAda.CertainkindsoftypesinAdapermitthecreationofaself-referenceduringobjectinitialization,evenforaconstant.Forsuchtypes(immutablylimitedandcontrolledtypes),thepotentialfortheerrorsidentifiedinthisvulnerabilityexists,buttherearevariouswaystomitigatethispotential–seeguidancebelow.Withtheexceptionofunsafeprogramming(see5.1Languageconcepts),thisvulnerabilityispreventedinothercasesbyrulesthatpreventobtainingareferencewithupdateaccessgivenaconstantviewofanobject.

6.65.2Guidancetolanguageusers

• Followthemitigationmechanismsofsubclause6.65.5ofISO/IEC24772-1:2022.• DonotusetheAccessattributetocreateaself-referencewithupdateaccesswhen

initializinganimmutablylimitedtype.• DonotusetheUnchecked_Accessattributewhenitcouldcreateaself-referencewithupdate

accessduringaninitializationroutine,ortheAdjustprocedureofacontrolledtype.• Ifaself-referencewithupdateaccessisimportanttothefunctionalityofagiven(private)

type,ensurethatallprimitiveoperationsofthetypeuse“inout”modeforparametersofthe

©ISO/IEC2022–Allrightsreserved 57

type,iftheymakeanyuseofthisself-referencetopotentiallyupdatetheparameter.Thiswillensurethatconstantsarenotinadvertentlyalteredbysuchaprimitiveoperation.

7LanguagespecificvulnerabilitiesforAda

Thisclauseisintentionallyleftblank.

8Implicationsforstandardization

FuturestandardizationeffortsshouldconsiderthefollowingitemstoaddressvulnerabilityissuesidentifiedearlierinthisAnnex:

• Pragma Restrictionsmaybeextendedtostaticallyconstraindubioususesofcontrolstructures(see6.31Unstructuredprogramming[EWD]).

• Whenappropriate,language-definedchecksshouldbeaddedtoreducethepossibilityofmultipleoutcomesfromasingleconstruct,suchasbydisallowingside-effectsincaseswheretheorderofevaluationmayaffecttheresult,similartothosespecifiedforuseof“in out”or“out”parametersoffunctions(see6.24Side-effectsandorderofevaluation[SAM]and6.55Unspecifiedbehaviour[BQF]).

• Whenappropriate,language-definedchecksshouldbeaddedtoreducethepossibilityoferroneousexecution,suchasbydisallowingunsynchronizedaccesstosharedvariables(see6.56Undefinedbehaviour[EWF]).

• Languagestandardsshouldspecifyrelativelytightboundariesonimplementation-definedbehaviourwheneverpossible,andthestandardshouldhighlightwhatlevelsrepresentaportableminimumcapabilityonwhichprogrammerscanrely.ForlanguageslikeAdathatallowuserdeclarationofnumerictypes,thenumberofpredefinednumerictypesshouldbeminimized(forexample,stronglydiscourageordisallowdeclarationsofByte_Integer,Very_Long_Integer,andsimilar,inpackage Standard)(see6.57Implementation-definedbehaviour[FAB]).

• Adacandefinea pragma RestrictionsidentifierNo_Hidingthatforbidstheuseofadeclarationthatresultinalocalhomograph(see6.20Identifiernamereuse[YOW]).

• Adacanaddtheabilitytodeclareinthespecificationofafunctionthatitispure,thatis,ithasnosideeffects(see6.24Side-effectsandorderofevaluationofoperands[SAM]).

• Pragma Restrictions canbeextendedtorestricttheuseof'Addressattributetolibrarylevelstaticobjects(see6.33Danglingreferencestostackframes[DCM]).

• FuturestandardizationofAdashouldconsiderimplementingalanguage-providedreferencecountingstoragemanagementmechanismfordynamicobjects(see6.38Deepvs.shallowcopying[YAN]).

58 ©ISO/IEC2022–Allrightsreserved

Bibliography

[1] AQSG,AdaQualityandStyleGuide,GuidelinesforProfessionalProgrammers.Availablefrom:https://en.wikibooks.org/wiki/Ada_Style_Guide.

[2] Barnes,John,HighIntegritySoftware-theSPARKApproachtoSafetyandSecurity.Addison-Wesley.2002.

[3] Barnes,John,LectureNotesonComputerScience8338,Ada2012Rationale:TheLanguage—TheStandardLibraries,Springer,2013.

[4] Bhansali,P.V.,Asystematicapproachtoidentifyingasafesubsetforsafety-criticalsoftware,ACMSIGSOFTSoftwareEngineeringNotes,v.28n.4,July2003

[5] Christy,Steve,VulnerabilityTypeDistributionsinCVE,V1.0,2006/10/04

[6] CWE.TheCommonWeaknessEnumeration(CWE)Initiative,MITRECorporation,(http://cwe.mitre.org/)

[7] Einarsson,Boed.AccuracyandReliabilityinScientificComputing,SIAM,July2005http://www.nsc.liu.se/wg25/book

[8] GAOReport,PatriotMissileDefense:SoftwareProblemLedtoSystemFailureatDhahran,SaudiArabia,B-247094,Feb.4,1992,http://archive.gao.gov/t2pbat6/145960.pdf

[9] Ghassan,A.,&Alkadi,I.(2003).ApplicationofaRevisedDITMetrictoRedesignanOODesign.JournalofObjectTechnology,127-134.

[10] Goldberg,David,WhatEveryComputerScientistShouldKnowAboutFloating-PointArithmetic,ACMComputingSurveys,vol23,issue1(March1991),ISSN0360-0300,pp5-48.

[11] Holzmann,GarardJ.,Computer,vol.39,no.6,pp95-97,Jun.,2006,ThePowerof10:RulesforDevelopingSafety-CriticalCode

[12] IEC61508Parts1-7,Functionalsafety:safety-relatedsystems.1998.(Part3isconcernedwithsoftware).

[13] ISO10241(allparts),Internationalterminologystandards

[14] ISO/IECDirectives,Part2,RulesforthestructureanddraftingofInternationalStandards,2017

[15] ISO/IEC8652:1995,Informationtechnology—Programminglanguages—Ada

[16] ISO/IECTR10000-1,Informationtechnology—FrameworkandtaxonomyofInternationalStandardizedProfiles—Part1:Generalprinciplesanddocumentationframework

©ISO/IEC2022–Allrightsreserved 59

[17] ISO/IEC15291:1999,Informationtechnology—Programminglanguages—AdaSemanticInterfaceSpecification(ASIS)

[18] ISO/IECTR15942:2000,Informationtechnology—Programminglanguages—Guidefortheuseofthe Adaprogramminglanguageinhighintegritysystems

[19] ISO/IECTR24718:2005,Informationtechnology—Programminglanguages—GuidefortheuseoftheAdaRavenscarProfileinhighintegritysystems

[20] ISO/IEC24772-1,–ProgrammingLanguages—Guidancetoavoidingvulnerabilitiesinprogramminglanguages–Part1:Languageindependentguidelines

[21] IEC/IEEE60559:2011,Informationtechnology–MicroprocessorSystems–Floating-Pointarithmetic(3parts)

[22] ISO/IEC15408:1999Informationtechnology.Securitytechniques.EvaluationcriteriaforITsecurity.

[23] Lions,J.L.ARIANE5Flight501FailureReport.Paris,France:EuropeanSpaceAgency(ESA)&NationalCenterforSpaceStudy(CNES)InquiryBoard,July1996.

[24] Lundqvist,KandAsplund,L.,“AFormalModelofaRun-TimeKernelforRavenscar”,The6thInternationalConferenceonReal-TimeComputingSystemsandApplications–RTCSA1999

[25] RTCASC167DO178-C/EUROCAEED-12C,SoftwareConsiderationsinAirborneSystemsandEquipmentCertification.IssuedintheUSAbytheRequirementsandTechnicalConceptsforAviation)andinEuropebytheEuropeanOrganizationforCivilAviationElectronics.December1992.

[26] Sebesta,RobertW.,ConceptsofProgrammingLanguages,8thedition,ISBN-13:978-0-321-49362-0,ISBN-10:0-321-49362-1,PearsonEducation,Boston,MA,2008

[27] Skeel,Robert,RoundoffErrorCripplesPatriotMissile,SIAMNews,Volume25,Number4,July1992,page11,http://www.siam.org/siamnews/general/patriot.htm

[28] Seacord,R.,TheCERTCSecureCodingStandard.Boston,MA:Addison-Westley,2008.

[29] Subramanian,S.,Tsai,W.-T.,&Rayadurgam,S.(1998).DesignConstraintViolationDetectioninSafety-CriticalSystems.The3rdIEEEInternationalSymposiumonHigh-AssuranceSystemsEngineering,109-116.

60 ©ISO/IEC2022–Allrightsreserved

Index

abort,35,51,53,54accesstype,18Accesstype,11Accessvalue,11Access-to-object,11Access-to-subprogram,11Allocator,11AMV–Type-breakingReinterpretationofData,42

Aspectspecification,11Atomic,11,15,51,54attribute'Valid,41

Attribute,11'Access,39'Address,39,40,57'Alignment,18'Component_Size,18'Exponent,25'First,38,52'Image,36'Last,38,52'Length,38'Range,38'Size,18'Unchecked_Access,21,39,40,49'Valid,47‘Access,28,40‘Callable,54,55‘Terminated,54,55‘Valid,23’Valid,33

Bitordering,11,12BJL–NamespaceIssues,32BoundedError,11BQF–UnspecifiedBehaviour,50BRS–ObscureLanguageFeatures,49 Casechoices,12Caseexpression,12

Casestatement,11,25,26,37CCB–EnumeratorIssues,25CGA–Concurrency–Activation,53CGM–ProtocolLockErrors,55CGS–Concurrency–PrematureTermination,54

CGT–Concurrency–Directedtermination,53CGX–ConcurrentDataAccess,54CJM–StringTermination,27CLL–SwitchStatementsandStaticAnalysis,36

Compilationunit,12Configurationpragma,12,19Controlledtype,12CSJ–PassingParametersandReturnValues,39

DCM–DanglingReferencestoStackFrames,39

Deadstore,12Defaultexpression,12Discretetype,12Discriminant,12,51DJS–Inter-languageCalling,47 Endianness,12EnumerationRepresentationClause,12Enumerationtype,12,16EOJ–DemarcationofControlFlow,37Erroneousexecution,13EWD–StructuredProgramming,38EWF–UndefinedBehaviour,51Exception,13,16,17,18,20,23,26,27,33,38,41,46,47,48,49,52,53,55,56Constraint_Error,16,17,28,29,36,52Program_Error,16,18,50Storage_Error,16,41Tasking_Error,16,53

ExceptionInformation,52Expandedname,13Explicitconversions,17,23

©ISO/IEC2022–Allrightsreserved 61

FAB–Implementation-DefinedBehaviour,52FIF–ArithmeticWrap-aroundError,29Fixed-pointtypes,13FLC–NumericConversionErrors,26 GDL–Recursion,41Genericformalsubprogram,13 HCB–BufferBoundaryViolation(BufferOverflow),27

HFC–PointerTypeConversions,28Hiding,13,17,57hiddenfromallvisibility,17hiddenfromdirectvisibility,17

HJW–UnanticipatedExceptionsfromLibraryRoutines,48

Homograph,13 Idempotentbehaviour,13Identifier,13Identifierlength,30IHN–TypeSystem,23Implementationdefined,13,17Implicitconversions,17,23Internationalcharactersets,30invalidrepresentation,51Invalidrepresentation,13 JCW–OperatorPrecedence/OrderofEvaluation,34

Junkinitialization,33 KOA–LikelyIncorrectExpression,35 Languageconcepts,24,26,27,28,29,36,37,41,42,43,45,47,55,56

LanguageVulnerabilitiesArgumentPassingtoLibraryFunctions[TRJ],44,45,46

ArithmeticWrap-aroundError[FIF],29BitRepresentation[STR],24BufferBoundaryViolation(BufferOverflow)[HCB],27

ChoiceofClearNames[NAI],30Concurrency–Activation[CGA],53Concurrency–Directedtermination[CGT],53Concurrency–PrematureTermination[CGS],54ConcurrentDataAccess[CGX],54

DanglingReferencetoHeap[XYK],29DanglingReferencestoStackFrames[DCM],39DeadandDeactivatedCode[XYQ],36Deadstore[WXQ],22,31DemarcationofControlFlow[EOJ],37DeprecatedLanguageFeatures[MEM],53Dynamically-linkedCodeandSelf-modifyingCode[NYY],47

EnumeratorIssues[CCB],25ExtraIntrinsics[LRM],46Floating-pointArithmetic[PLF],24IdentifierNameReuse[YOW],32IgnoredErrorStatusandUnhandledExceptions[OYB],41

Implementation-DefinedBehaviour[FAB],52Inheritance[RIP],44InitializationofVariables[LAV],32Inter-languageCalling[DJS],47LibrarySignature[NSQ],47LikelyIncorrectExpression[KOA],35LoopControlVariables[TEX],37MemoryLeak[XYL],43NamespaceIssues[BJL],32NumericConversionErrors[FLC],26ObscureLanguageFeatures[BRS],49Off-by-oneError[XZH],37OperatorPrecedence/OrderofEvaluation[JCW],34PassingParametersandReturnValues[CSJ],39PointerArithmetic[RVG],28PointerTypeConversions[HFC],28ProtocolLockErrors[CGM],55ProvisionofInherentlyUnsafeOperations[SKL],49Recursion[GDL],41Relianceonexternalformatstrings[SHL],56Side-effectsandOrderofEvaluation[SAM],34StringTermination[CJM],27StructuredProgramming[EWD],38SubprogramSignatureMismatch[OTR],40SuppressionofLanguage-definedRun-timeChecking[MXB],49

SwitchStatementsandStaticAnalysis[CLL],36TemplatesandGenerics[SYM],43TypeSystem[IHN],23Type-breakingReinterpretationofData[AMV],42UnanticipatedExceptionsfromLibraryRoutines[HJW],48

UncheckedArrayIndexing[XYZ],27UndefinedBehaviour[EWF],51UnspecifiedBehaviour[BQF],50UnusedVariable[YZS],31

62 ©ISO/IEC2022–Allrightsreserved

UsingShiftOperationsforMultiplicationandDivision[PIK],29

LanguageVulnerabilityUncheckedArrayCopying[XYW],27

LAV–InitializationofVariables,32LRM–ExtraIntrinsics,46 MEM–DeprecatedLanguageFeatures,53Mixedcasing,30Modulartype,14MXB–SuppressionofLanguage-definedRun-timeChecking,49

NAI–ChoiceofClearNames,30NSQ–LibrarySignature,47NYY–Dynamically-linkedCodeandSelf-modifyingCode,47

Obsolescentfeature,14OperationalandRepresentationAttributes,14,18

OTR–SubprogramSignatureMismatch,40Overridingindicators,14OYB–IgnoredErrorStatusandUnhandledExceptions,41

Partition,14PIK–UsingShiftOperationsforMultiplicationandDivision,29

PLF–Floating-pointArithmetic,24Pointer,14,32PolymorphicVariable,17Postconditions,46,47Pragma,14,49Configurationpragma,12pragma Atomic,18,54pragmaAtomic_Components,18,54pragmaConvention,18,47,48pragma Default_Storage_Pool,20pragmaDetect_Blocking,18pragmaDiscard_Names,18pragmaExport,18,47,48pragmaImport,19,42,47,48pragmaNormalize_Scalars,19,33pragma Pack,19pragmaRestrictions,19,20,49,50,53,57pragmaSuppress,19,21,27,49,51pragma Unchecked Union,19pragmaVolatile,19,54

pragma Volatile_Components,19,54Preconditions,46,47Programverification,46 Rangecheck,14Recordrepresentationclause,14RIP–Inheritance,44RVG–PointerArithmetic,28 SAM–Side-effectsandOrderofEvaluation,34Scalartype,14selectingexpression,14SeparateCompilation,19SHL–Relianceonexternalformatstrings,56Singular/pluralforms,30SKL–ProvisionofInherentlyUnsafeOperations,49

staticexpression,14StoragePlaceAttribute,15Storagepool,11,15,20,43Storagesubpool,15,20,43STR–BitRepresentation,24Subtypedeclaration,15SYM–TemplatesandGenerics,43Symbolsandconventions,10 Task,15,55Termsanddefinitions,10TEX–LoopControlVariables,37TRJ–ArgumentPassingtoLibraryFunctions,44,45,46

Typeconversion,14,17Typeinvariants,46,47 Uncheckedconversions,17,23Unchecked_Conversion,17,21,23,42,49,51

Underscoresandperiods,30UnsafeProgramming,20,24,25,26,27,28,29,36,37,41,43,45,47,49,55

Unusedvariable,15 Volatile,15,54 WXQ–Deadstore,22,31 XYK–DanglingReferencetoHeap,29XYL–MemoryLeak,43

©ISO/IEC2022–Allrightsreserved 63

XYQ–DeadandDeactivatedCode,36XYW–UncheckedArrayCopying,27XYZ–UncheckedArrayIndexing,27XZH–Off-by-oneError,37

YOW–IdentifierNameReuse,32YZS–UnusedVariable,31

Recommended