A General Framework for Formalizing Object-Oriented Modeling Techniques
description
Transcript of A General Framework for Formalizing Object-Oriented Modeling Techniques
1
A General Framework for Formalizing Object-Oriented Modeling
TechniquesBetty H. C. Cheng
Software Engineering and Network Systems Laboratory
Department of Computer Science and Engineering
Michigan State University
East Lansing, Michigan 48824
www.cse.msu.edu/~chengb
2
Acknowledgements
Joint work with the following people: Robert Bourdeau Laura Campbell William McUmber Enoch Wang Ryan Stephenson
Sponsored in part by: National Science Foundation Grants:
(CCR-9633391, CCR-9901017, EIA-0000433) DARPA Grant (EDCS Program): F30602-96-1-0298 Motorola Eaton Corporation Siemens Automotive Detroit Diesel Corporation
3
Bridge the Gap Between Informal and Formal Methods
Object-Oriented “Blueprints” Formal Representations
Informal specifications,• graphical models,• easy for humans to formulate, •may be inconsistent and incomplete.
Ap
ply F
orm
aliza
tion
Fram
ew
ork
Objective:• formal specifications• executable code• that can be verified for correctness and completeness
Benefits:•Automated Analysis
•Consistency, completeness•Rapid Prototyping•Behavior Simulation
• Design Transformations•Test Case generation
5
Overview
Introduction Background/Related Work Formalization Framework Validation:
Tool Support Case Study
Conclusions and Future Investigations
6
Motivation
Embedded systems are difficult to develop Object-Oriented Design can be powerful for
embedded systems Diagrammatic notations facilitate abstraction
UML is de facto standard Object-Oriented Commonly used More intuitive
But diagrams lack formality precisely predicting behavior is difficult
7
Objectives and Results
Overarching goals: Broaden base of developers who can use rigorous software
engineering techniques Provide palatable path to more rigorous SE techniques Leverage existing expertise and technology
Enable use of intuitive diagrammatic notations (UML) for embedded system design
Provide path from UML to existing formal languages Existing user base Support Tools
Enable automated analyses of model Simulation Model checking
8
Additional Results
Provide precise semantics for diagrams Establish consistency of mapping rules Allow choice of formalization language
9
Background: Embedded Systems
Code difficult to design and analyze Time-dependent difficult to instrument often highly concurrent
High level of robustness required control real-world, physical processes
10
Background: UML
“General-purpose” visual modeling language de facto Standard
(At least) nine different diagrams
Diagrams described by metamodels: A graphical model that describes syntax of model
Therefore, nine different metamodels
11
UML Class Diagram
Class A
Class A1 Class A2 Class A3
Class B
Class X
Contains components
Contains aggregationsof Class B
“type of”indicator
Named association
Talks-to1 0..1
multiplicities
12
UML Metamodel
Metamodel defines UML syntax using
class diagram notation.
Semantics not defined by metamodel
Note: Any language or diagram syntax can
be defined with a metamodel
13
Example MetaModel
Program
SimpleStatement
CompoundStatement
Block0..*
14
Metamodel - Diagram - System Relationship
MetamodelMetamodelUML
DiagramInstance
UML DiagramInstance
Constrainssyntax
Constrainssyntax SystemSystemSpecifies
aspect of
Specifiesaspect of
Uses class diagramnotation to describediagram componentrelationships
Specific diagram showssome aspect of the systembeing constructed
15
Background: VHDL
IEEE standard language Intended for abstract description of hardware Uses multiple, concurrent, communicating
processes Communication through “signals”
Syntax is Ada-like, procedural in nature Models can be “executed” in simulation.
17
Background: Promela (SPIN)
Promela is language for SPIN model checker Simulation and model checking of concurrent systems
SPIN: commonly used in telecommunication domain
Developed by Bell Labs (now Lucent) Protocol verification
Guarded Command Language + CSP + C Collection of processes, channels, and variables
18
Background: Promela Example
typdef A_type {int x;int y;bool unused;mtype vals;}chan queue=[3] of {mtype};A_type A;mtype={on, off, none};
init {atomic {A.x = 1; A.y = 2}run abc()}
proctype abc() {int I;do:: A.x > 1 -> A.y = A.y + 1; A.x = A.x + 1;od;queue!on;if:: queue?vals:: A.y > 4 -> goto skip1fi}
“structure” typedef
Channel declaration
Basic proctype
do-od loop
if-fi block
Proctype instantiation
“initial” procedure
declarations
Instantiation of “A_type”
Executed as one stmt
Channelwrite
Channelread
GuardedstatementProctype declaration
19
Homomorphisms
Preserve operations, hence structureand semantics
)()()( bhahbah
This operation in this systemwith these objects (a & b)
Does the “same thing” as this operationin this system
With the mapped objects
20
Metamodel mapping
UMLmetamodel
UMLmetamodel
Formal languagemetamodel
Formal languagemetamodel
UMLdiagram
UMLdiagram
Describes instance
Formal descriptionof system
Formal descriptionof system
Describes instance
Homomorphism
Mapping Rules
Producesmapping
21
Unified Class/Dynamic Metamodel
ModelModel
ClassClass RelationshipsRelationships
InstanceVariables
InstanceVariables AggregationAggregation GeneralizationGeneralization
AssociationAssociation
BehaviorBehavior
State VertexState Vertex
TransitionTransition
Rest of dynamic model
Class relatedDynamic related
22
Dynamic Model Portion of Unified Metamodel
BehaviorBehavior
State VertexState VertexTransitionTransition
GuardGuard
PseudostatePseudostate StateState
CompositeStateCompositeState SimpleStateSimpleState
ActionSequenceActionSequence
EventEvent
SignalEventSignalEvent TimeEventTimeEvent ChangeEventChangeEvent
StartStart
FinalFinal
JoinJoin
HistoryHistory
0..1
0..1 0..1
0..1
0..1
0..1
0..1
0..111
1..*
To Class
23
Example Metamodel Mapping
h:
h:
h:
h:
h:
AA BB
CC
R
hasComp(A,C)
Source
B’B’ A’A’
C’C’
D’D’
hasPart(A’,C’)
R’
Target
29
Promela Class Diagram Mapping Rules
Classes (objects) map to proctypes.
Relationships map to channels.
Instance variables map to global typdef structures.
30
Promela Dynamic Model Mapping Rules
Simple states map to blocks of Promela statements.
Transitions map to goto and run() Composite states map to proctypes Events map to channel writes/receives Pseudo-states map to blocks of various Promela
statements
31
SPIN Analyses
Random simulation Exhaustive search of states
State transition system checked by temporal logic assertions Often provides counter-examples (path to problem state) “Easier” than theorem proving
Better than simulation when precise timing not required
32
Summary of Mappings
VHDL Promela
Ent/Arch proctype
Port signature channels
procedure Labeled blockof statements
Ent/Archproctype
Write to signalChannelassignment
Class
Relationship
State
CompositeState
Event
Structure
33
Tool Support
MINERVA HydraAnalysis
Tool*HIL
Analysis results
Diagramreports
Analysis reports
Spec*UML
35
Architecture of Minerva
UML
Diagram in DoME format
Diagram reports
Analysis reports
Visualizationcommands
HIL
Analysis results (raw)
Analysis results (processed)
UML diagrameditors Plug-ins
Text processingscripts
38
Smart Cruise Requirements
Safety zone
Desired trail distance
Coast zone Closing zone
About 400 ft - acquires target vehicle. Closing speed low enough to control.
Starts coasting to match speed
Safe zoneMaintain proper trail distance - speeds match
Closing speed too high.
Issues warnings to avoid this condition
This is what we want
39
Class - Context Diagram
Control
Car
Radar
Target acquisitiontarget lossdistance
Car speedthrottle control Car speed
Warnings
Target
Distance
System boundary
Throttle Control
Brakes
“set”
brakes
40
Smart Cruise Class Model
Control Radar
Car
Car speed
Car speedthrottle control
•Target acquisition•target loss•distance to target
41
High Level Radar Dynamic Model
Get car speed
Check distance
Off
Wait forack
[target <= 400]^target-acquired
[target > 400]
Ack-from-control
Turn-off
Car-speed
Turn-on
42
car1
car1car4
car3
Get-speed[real=set]^speed
Get-speed[realset]/{adjust real speed}^speedSet-speed
Get-speed^speed
Unset speed
updatex updatespd
dogetspd dounset
Supply speed to radar
Supply speed to control
Set cruise speed
Car Dynamic Model
Unset cruise speed
43
High Level Control Dynamic Model
Get speedand
distance
Wait for “set”Wait for target
Warningor Alarm
Check bounds
Closing on target
Maintain Trail
position
settarget
[closing][trailing]
Ackfrom car
[exceed bounds]
44
SPIN Analyses Performed
Random simulation State reachability State reachability with assertions Progress loop analysis (cycle checks) Model checking with temporal claim Model checking with temporal claim and non-
deterministic execution paths.
45
Use of Simulation
Check that model runs (does not deadlock) Model appears to achieve basic requirements Model not erratic (simulation is random) Exercise common paths Explore extremes for initial proper behavior Basically, high level debugging strategy
46
State Reachability Analysis
Reachability is exhaustive (unlike simulation)
For common scenarios, ensure state set correct and exception states not entered
For exception scenarios, ensure exception states entered
47
State Reachability for Normal Scenario
Get speedand
distance
Wait for “set”Wait for target
Warningor Alarm
Check bounds
Closing on target
Maintain Trail
position
settarget
[closing][trailing]
Only unreachedstate, as expected
Ackfrom car
control dynamic
model
(Establish target trail)= reached
[exceed bounds]
48
SPIN Progress Loop Analysis
Ensures no cycles of only unmarked states.
Reports cycles unless state(s) are marked. If nothing marked, reports cycles If known cycles are marked, reports
unexpected cycles
49
Progress Cycle Analysis of Model
Liveness check: Ensure state cycle “follow target” established Differs from reachability by ensuring cycle exists, not
just state visit.
Safety check: Ensure no unexpected cycles encountered
50
Progress Loop Checks
Get speedand
distance
Wait for “set”Wait for target
Warningor Alarm
shut off systemCheck bounds
Closing on target
Maintain Trail
position
settarget
[closing][trailing]
1. Blue states reported as cycle when unmarked
2. After marked, no other cycles appeared(complement of first check)
None ofthese reported
Ackfrom car
51
Model Checking Tests
Car achieves trail position, and stays there. Three checks:
Once in idle, model never comes back when target sent, ack replied Remove ack to demonstrate check works
Brake application leads to return to idle state. Revealed missed an event on transition
52
Hand Written Never Claim
/* Verifies that at low enough closure speeds, the car comes up behind the target and stays there forever. If the trail loop is exited, we return to state idle */1: never2: {/* wait until state idle is entered */3: do4: :: skip5: :: control[controlpid]@idle -> break6: od;/* now wait until state idle is exited */7: do8: :: skip9: :: !(control[controlpid]@idle) -> break10: od;/* and if we come back to state idle, it's an error */11: do12: :: control[controlpid]@idle -> break13: od}
A never claim specifying that state idle is only entered once, at the start of execution.
53
Analysis Output From Hand-Written Never Claim
warning: for p.o. reduction to be valid the never claim must be stutter-closed(never claims generated from LTL formulae are stutter-closed)(Spin Version 3.3.1 -- 11 July 1999) + Partial Order Reduction
Full statespace search for: never-claim + assertion violations + (if within scope of claim) acceptance cycles + (fairness disabled) invalid endstates - (disabled by never-claim)
State-vector 504 byte, depth reached 3114, errors: 0 6314 states, stored 2919 states, matched 9233 transitions (= stored+matched) 3445 atomic stepshash conflicts: 72 (resolved)(max size 2^18 states)
4.565 memory usage (Mbyte)
No mention of failing claim or “acceptance cycles”.Implies claim succeeded.
54
SPIN Generated Never Claim for “p leads-to q”
never { /* !([](p -> <>q)) *//* >>0,0<< */T0_init:
if:: (! ((q)) && (p)) -> goto accept_S4:: (1) -> goto T0_initfi;
accept_S4:if:: (! ((q))) -> goto T0_S4fi;
T0_S4:if:: (! ((q))) -> goto accept_S4fi;
accept_all:skip
}
Always(p implies eventually q)
p leads-to qwhich is the same
as:
p leads-to qfrequently used
assertion forliveness
55
Ensure target Never Missed
Control Radar
Target acquired
acknowledgement
Using: always(p implies eventually q)
This check succeededNever, not [always(p implies eventually q)]
SPIN version for claim
56
Demonstrate Check Works
Control Radar
Target acquired
acknowledgement
This check failed (as expected)
Remove this message to forceclaim to fail
57
warning: for p.o. reduction to be valid the never claim must be stutter-closed(never claims generated from LTL formulae are stutter-closed)pan: acceptance cycle (at depth 298)pan: wrote sc.v9.pr.trail(Spin Version 3.3.1 -- 11 July 1999)Warning: Search not completed + Partial Order Reduction
Full statespace search for: never-claim + assertion violations + (if within scope of claim) acceptance cycles + (fairness disabled) invalid endstates - (disabled by never-claim)
State-vector 500 byte, depth reached 299, errors: 1 134 states, stored (135 visited) 1 states, matched 136 transitions (= visited+matched) 32 atomic stepshash conflicts: 0 (resolved)(max size 2^18 states)
Check Demonstration: target leads-to ack failing never claim output
Acceptance cycle in never claim. Implies claim has failed.
Never claim is p leads-to q.p is target,
q is acknowledgement.
58
Non-deterministic Paths(checking brake signal behavior)
r3[tmode & x>400]^control.lost
[tmode & x<=400]^control.dist(x)
[tmode & x<=400]^control.brakes
Non-deterministic choicebetween these two transitions.Either is possible after x<=400
New transition added for verification.Send brakes at random times.
Matching guards
59
Never Claim to Test Brakes
Let p be defined as “brake signal in control’s queue ”
Let q be defined as “in state idle in object control”
Use never claim generated for p leads-to q
control_q??[brakes]Promela predicate
Promela predicate control[controlpid]@idle
60
First Test of Brake Signal Behavior
<<<<<START OF CYCLE>>>>>616: proc 0 (NEVER) line 471 "never"616: proc - (:never:) line 471 "sc.v9.pr" (state 11) [(!((control[controlpid]._p==idle)))] control_V.a = 15 control_V.xcoast = 3333 control_V.setspd = 1100 control_V.v = 200 control_V.tmin = 2 control_V.x1 = 3700 control_V.vc = 1100 control_V.x2 = 3500 control_V.vt = 900 control_V.z1 = 1620 control_V.z2 = 1800 control_V.xhit = 1333 control_V.tinc = 1 control_V.closing = 0 queue 2 (control_q): [carspeed][ackcar] radar_V.x = 3500 radar_V.tmode = 0
This signal is blocking --
This one and stoppingtransition to idle
result: deadlock
Claim failed with acceptance loop.This is a trace of the loop.
61
Correcting Brake Behavior
caroff
calcgetspd
To state idleackcar
Dist(x1)losttargetbrakescarspeed(vc)
brakes
Analysis shows modelstopped in this state.
Had to add this eventto pick up ackcar
Normal trail loop
Brake application path
(control_q=[carspeed][ackacr])
62
Related Work
Object-Orientation and Embedded Systems
Formalization of UML
Formalization of OO Modeling Techniques
63
Embedded System Methodologies
Ad Hoc (frequently used in industry) Structured methods - RTSA
[Ward & Mellor, Hatley & Pirbhai] RTSA models semi-formal, uses top-down
Hybrid OO -- RTOOSA [Ellis] Still structured, semi-formal - little object use
OO, non-UML (ROOM) [Selic, Gullekson] Formal, but unusual OO model
OO, UML based [Douglass] Semi-formal. No behavior verification
64
Formalization of UML
Precise UML (pUML) based UML on Z [Evans, Clarks, Bruel, France, Lano]
Attempts to provide direct manipulations of diagrams But no dynamic behavior mapping No way to verify behavior or properties, other than
potential theorem prover
65
Other OO Formalizations
OCL shown to have problems [Mandel & Cengarle]
Fusion well-defined process, but informal semantics [Coleman, et al]
TROLL formally defined, but no checkers or simulation capability
[Jungclaus, Saake, Hartman, Sernadas]
Formalized OMT with rules but no generic mapping framework [(Wang & Cheng), (Bourdeau & Cheng)]
Rules specific to LOTOS
66
Overview of Contributions
General framework for providing semantics.
Unified UML Class/Dynamic metamodel.
Mapping to VHDL and Promela.
Means to perform simulation and model checking
from semi-formal diagrams.
Systematic process for developing OO graphical
models for embedded systems.
67
Where does this all fit in Big Picture?
68
MERIDIAN: An Integrated Toolkit for Developing Interactive Distributed Applications
Increasing interest fueled by:•The World-Wide Web.•Middleware technology (e.g., CORBA, DCOM, JavaBeans).•New network services and protocols.
Examples: On-board driver/pilot navigation
systems. Computer-supported collaborative
work environments. Distributed interactive simulation.
69
Meridian Research goals Improve quality of IDAs.
Better IDAs (reliable, maintainable, extensible). Better development (faster, cheaper).
Advance state of automated software-engineering (ASE) practice.
Incorporate ASE techniques into mainstream development. Apply various formal methods in a new domain.
Identify end-to-end automation techniques that take advantage of multiple phases of development.
70
Meridian Practical goals
To have techniques adopted in practice: Must complement existing design methods and notations. Otherwise, acceptance must overcome stiff economic hurdles.
Implications: Designers should not reformulate designs in a formal notation. Designers should not have to view the output of a formal analysis
tool.
We chose (UML) for representing IDA designs.
71
Meridian Vision
Model Editing
SpecificationAnalysis
DesignProcessing
Testing/Simulation
IDA Models IDA Constraints IDA Interface Requirements
IDA ReuseRepository
IDA ExternalParameters
SpecificationsRefinedSpecifications
Code
FeedbackUser
Req
uire
men
ts
Test Cases
72
Summary of Contributions
General framework for constructing mappings of diagrams to formal target languages
Framework enables use of rigorous techniques to establish completeness, consistency, and correctness of mapping rules.
A set of rules for generating VHDL and Promela specifications from UML
Enable behavior simulation and analysis on informal
diagrams via their formal specifications
Systematic process for developing OO graphical models
for embedded systems
73
Current and Future Research
Consider other UML Diagrams: Use Case: provide high-level user goals Interaction Diagrams (Sequence and Collaboration):
model behavior of specific scenarios
Add temporal and real-time constraints Explore modified UML semantics
Adapt semantics to application?
74
Current/Future Research
Mapping to SMV Different temporal logic (CTL) Different analysis capabilities (e.g., fairness)
Explore the use of specification patterns to guide analysis capabilities
Domain-specific refinement of UML diagrams Move closer towards implementation Use of Design Patterns and Frameworks
75
Discussion…
76
END OF REGULARSLIDES
The rest are backup
78
Control dynamic model template
Get speedand
distance
Wait for “set”Wait for target
Warningor Alarm
Check bounds
Closing on target
Maintain Trail
position
settarget
[closing][trailing]
Ackfrom car
79
Future Work:Extended Metamodel
ModelModel
ClassClass RelationshipsRelationshipsBehaviorBehavior
Use Cases
SequenceDiagrams
Scenarios
Can easily add Use Casesto unified metamodel, and extend mapping to includeUse Cases.
80
Example Static VHDL
use std.textio.all;use work.easyio.all;use work.pk_A.allentity obj_A is port(r1: inout integer);end entity;architecture abstract of obj_A is shared variable var A : integer;begin l1: entity obj_C(abstract) port map(r1=>r1);end architecture;
use std.textio.all;use work.easyio.all;use work.pk_D.allentity obj_D is port(r1: inout integer);end entity;architecture abstract of obj_D isbeginend architecture;
Skeleton structure for object A Skeleton structure for object D
Primary association
Inherited association
Instantiation resulting fromaggregation in class model
81
Tunable SemanticsTo Fit Application Domain
Semantic Property
Message passingbetween objects
Transition inter-leaving
Eventless, guarded transitions(e.g.) [a & b]^object.evt
•Queued - any order•Queued FIFO•Non-Queued
•Queued - any order•Queued FIFO•Non-Queued
•Must Complete•Interleaved
•Must Complete•Interleaved
Mapping Options
•Waits on guard, like “WHEN”•Hangs if guard false
•Waits on guard, like “WHEN”•Hangs if guard false
82
Example entity for state D
use std.textio.all;use work.easyio.all;use work.pk_top.all;entity cs_d is port(state: inout rs_st; t1: inout boolean; t2: inout boolean; t3: inout boolean; t4: inout boolean; t5: inout boolean; t6: inout boolean; t7: inout boolean; ins_cp1: in st; ins_cp2: in st; instate: out st);end entity;
architecture abstract of cs_d isbegin-- body of composite state follows...
Port signature external informationto composite state.
State ‘bus’ to select state
Passes state status of cp1 and cp2
Send our state value out
All relevant event variables
83
Example process for state D2
S_d2: processbegin wait until state=st’(d2); say(“In state d2”); loop wait until t3 or t4 or t1; if t3 and g1 then state <= st’(d1), null after 1 fs; exit; elsif t4 then state <= st’(join1), null after 1 fs; exit; elsif t1 then state <= st’(e), null after 1 fs; exit; end if; end loop;end process
Guard entry into state
Wait for transition events
Transition initiations
Purpose of loop is to wait for guard
84
Example Dynamic Model
A
D1
C
B
D2
E
H
F
T1
T2
T3T4
CP1
CP2
T3[G1]
T5
T4T3
T1 T2
D
85
Example object “top”
architecture abstract of obj_top is signal state : rs_st; signal ss_cp1 : rs_st; signal ss_cp2 : rs_st; signal ins_cp1 : st; signal ins_cp2 : st; signal ins_d: st;begin l2: entity cs_cp1(abstract) port map(state=>ss_cp1, t1=>t1, t2=>t2, t3=>t3, t4=>t4, t5=>t5, t6=>t6, t7=>t7, instate=>ins_cp1, ins_cp2=>ins_cp2, ins_d=>ins_d); ss_cp1 <= st’(cp1), null after 1 fs when state=st’(cp1) or state=st’(cp2); 13: entity cs_cp2(abstract) port map(state=>ss_cp2, t1=>t1, t2=>t2, t3=>t3, t4=>t4, t5=>t5, t6=>t6, t7=>t7, ins_cp1=>ins_cp1, instate=>ins=>ins_cp2, ins_d=>ins_d);ss_cp2<= st’(cp2), null after 1 fs when state=st’(cp1) or state=st’(cp2);
Instantiation of composite state cp1from the object top level
Start concurrent state
86
Sample Class Model
A
DC
BVar A:integer
R1
Maps to
87
Validation: Furnace Example
88
UML Dynamic Metamodel
89
The Problem
Computer programs have become too large and complex to be encompassed within the human mind. Therefore:
The job of a developmentmethod is to show people howto discipline their work so 500mediocre programmers canjoin together to produce aprogram that meets its specifications.
The job of a developmentmethod is to make it soprograms can fit within our mindsby using more powerful, flexible ideas.
OR
Adapted from Simply Schemeby Harvey and Wright
90
VHDL Dynamic Metamodel
91
Furnace Dynamic Model
92
Mapping to Kripke Structure
''')( uRmuRmh
)(')()( uhRmhuRmh
) fixeda (for then let muRmuggmh ''')(,)(
Pt
))(( ugPt
Cases Use withoutmodel unified thebe Letm
Cases Use be Letu
Then,
And,
(model and drivingscenarios are separable)
So,
If
(these are Kripke structures)
Is a temporal predicate testing a property,
Then, Is the validity of the property, and u is modular.
93
Application of Extended Model
Clearly shows Use Cases and model are separable
Can generate function g with respect to u also:
Might provide insight into exact nature (and requirements) for h
))(( guh
94
Design Process Data Flow
Develop UseCases
Develop ContextModel
Develop UseCase Scenarios
Develop ClassModel
DevelopResponsibility
List
Scenarios
Write dynamic model
scenarios
class model
System Component DelineationModel CheckingRequirements
contextdelineation
Develop SequenceCharts Write Dynamic
Model
class modelresponsibility list
95
Design Process Data Flow
Scenarios
Model CheckingSimulation
Write DynamicModel
UML Model
Formal Language Specs
Hydra
DevelopResponsibility
List
responsibilities
Class model
Develop SequenceCharts
Develop ClassModel
Develop UseCase Scenarios
96
Ambiguous Semantics 1
A BE F
[G]
Is F transition ever taken? How?
97
Ambiguous Semantics 2
A BE [G]
What happens when G is false after event E?
Are we stuck here?
98
Ambiguous Semantics 3
A B
E
DC
F
G
H
J
K
What does this mean?
How many threads are running in here?
99
Ambiguous Semantics 4
A B
E
DC
F
G
H
J
K
Does this component get started?