tkt-3500 microcontroller systems · tkt-3500 microcontroller systems lec 10 – arithmetics, stack,...

69
Erno Salminen - Nov. 2008 TKT TKT - - 3500 3500 Microcontroller Microcontroller systems systems Lec 10 Lec 10 Arithmetics, stack, g Arithmetics, stack, g eneral eneral guidelines (aka. smart guidelines (aka. smart - - ass stuff) ass stuff) Erno Salminen Erno Salminen Department of Computer Systems Department of Computer Systems Tampere University of Technology Tampere University of Technology Fall 2008 Fall 2008

Upload: dodiep

Post on 17-May-2018

225 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

Erno Salminen - Nov. 2008

TKTTKT--3500 3500 Microcontroller Microcontroller systemssystemsLec 10 Lec 10 –– Arithmetics, stack, gArithmetics, stack, general eneral guidelines (aka. smartguidelines (aka. smart--ass stuff)ass stuff)

Erno SalminenErno Salminen

Department of Computer SystemsDepartment of Computer SystemsTampere University of TechnologyTampere University of Technology

Fall 2008Fall 2008

Page 2: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#2/69 Erno Salminen - Nov. 2008

ContentsContents

Extended precision arithmeticsFunction pointersCommon guidelines

Project success in generalSW coding

Page 3: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#3/69 Erno Salminen - Nov. 2008

SourcesSourcesRobert Reese, Microprocessors: From Assembly to C with the PIC18Fxx2, Charles River Media, 2005Coley consulting, Why projects fail, http://www.coleyconsulting.co.uk/failure.htmR.N. Charette, Why software fails [software failure],Spectrum, IEEE, Vol. 42, Iss. 9, Sept. 2005, pp. 42 - 49.

N. Holmes, The Data Doughnut and the Software Hole, Computer, Vol. 39, Iss. 6, June 2006, pp. 100 - 99.

B. Boehm, V.R. Basili, Software defection reduction Top 10 list, Computer, Vol. 34, Iss. 1, Jan. 2001, pp. 135 - 137.

Forrest Shull et al., WhatWe Have Learned About Fighting Defects, METRICS, 2002

H. Sutter, A. Alexandrescu, C++ Coding Standards: 101 Rules, Guidelines, and Best Practices (C++ In-Depth Series), Addison-Wesley Professional, Nov. 2004.WikipediaThanks also to Heikki Orsila, Mauri Kuorilehto, Teemu Laukkarinen

Page 4: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#4/69 Erno Salminen - Nov. 2008

Arithmetic OperationsArithmetic Operations

Some large integer or floating point operations are not necessarily supported on embedded systemsGiven a binary operation (operation with two operands), type conversion can be neededAssume x + y is computed and x is a larger integer type than y

1. Integer promotionIf y is shorter than int, it is first converted to int or unsigned int

2. Arithmetic conversiony is converted until its type matches: int→ long→ unsigned long→long long→ unsigned long longOr, unsigned int→ long→ unsigned long→ long long→unsigned long long

Page 5: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#5/69 Erno Salminen - Nov. 2008

Arithmetic Operations in PIC18Arithmetic Operations in PIC18

By default, MCC18 compiler uses the value range equal to the largest range of operandsThis may have ”interesting” consequencesExampleunsigned char a = 0x80;unsigned char b = 0x80;unsigned int i = a + b; // i==0x00// not 0x100 as in ISO because operands are only 8-bits wide

With switch –Oi MCC18 used ISO standard definition (operands are at least int or larger)

Page 6: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#6/69 Erno Salminen - Nov. 2008

Extended precisionExtended precision

PIC18 is referred as ”8-bit microcontroller”because registres, data paths, and ALU operands are 8-bits wideOperations are performed 1 byte at a time

value assignmentaddition, subractionbitwise OR, bitwise AND, shift

Multibyte variables are slower to handleint operations take approx. twice as long as with charwith long variable it takes four time as long etc.

Prefer small variables when possible

Page 7: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#7/69 Erno Salminen - Nov. 2008

little -endian

little -endian

Ext.prec.: assignmentExt.prec.: assignment

Page 8: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#8/69 Erno Salminen - Nov. 2008

Ext.prec.: logical and shiftExt.prec.: logical and shift

Order is irrelevant

RLCF =Rotate Left f through Carry

Note the order

Page 9: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#9/69 Erno Salminen - Nov. 2008

Ext.prec.: arithmcticExt.prec.: arithmctic

Add upper bytes and Carry

Page 10: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#10/69 Erno Salminen - Nov. 2008

Ext.prec.: conditionsExt.prec.: conditionsEquality test

Greater than test

Page 11: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#11/69 Erno Salminen - Nov. 2008

Signed/Unsigned comparisonSigned/Unsigned comparison

You cannot rely on bit representationYou must the know the semantics (type)

Page 12: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#12/69 Erno Salminen - Nov. 2008

FixedFixed--point arithmeticpoint arithmetic

Fixed-point numbers are used for real data types when floating-points are impractical

SW emulation of FPU is very sloooowAllow using the basic integer-ALUHigher precision than with integers

There are fixed number of digits after the radix point

decimal point, binary point...07815

,

,

,

16-bit examples

Q8.8

Q12.4

Q2.14

integer part’s rangefractional part’s precision

[0,255], [-128, +127]

[0,4095], [-2048, +2047]

[0,3], [-2,+1]

1/256

1/16

1/4096

Page 13: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#13/69 Erno Salminen - Nov. 2008

FixedFixed--point arithmeticpoint arithmetic

Radix (binary) point is not stored in memoryIts location is encoded into the program code

Designer keeps track where it is and possibly shifts the operands accordingly

Floating-point unit (FPU) handles radix point automaticallyNo native support in C

Some SW libraries offer basic functionsFormat Q0.n avoids multiplication overflows

Number range is [0,1) (excluding 1)

,

Q8.8 + Q12.4 = ?1

,

+

2 Shift and add

,+

,0..0

,

3 Shift result if needed

Page 14: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#14/69 Erno Salminen - Nov. 2008

Saturating arithmeticSaturating arithmetic

Unfortunately, Q0.n does not prevent overflow in addition or subractionSaturating arithmetic clips the values to minimum/maximum instead of overflow

addsat k, 0xf0, 0xee // k becomes 0xffE.g. in position control, saturation drives the motor to one extreme instead of bouncing it aroundE.g. in audio processing, saturation causes less distortion than overflow (wrap-around)E.g in image processing, ”blacker than black” is still black and not almost white

Useful but no native support in CSupported in asm in certain CPU/DSPs, though

Page 15: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

Erno Salminen - Nov. 2008

Subroutines and stackSubroutines and stack

Page 16: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#16/69 Erno Salminen - Nov. 2008

Page 17: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#17/69 Erno Salminen - Nov. 2008

StackStack

Stack is the memory area that keeps the context or place of function execution, registers, and local variablesMemory for locals is allocated from stackStack contains also the

input parameters, return values, stack pointer of calling functionreturn address etc.

Each function call has one stack frameEach execution entity (thread) has its own stack

Page 18: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#18/69 Erno Salminen - Nov. 2008

Page 19: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#19/69 Erno Salminen - Nov. 2008

Page 20: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#20/69 Erno Salminen - Nov. 2008

Page 21: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#21/69 Erno Salminen - Nov. 2008

On Stack Use On Stack Use

Be careful with stack, its size is often very limited in embedded systems

Limits the size of variables and the depth of function nesting

For example32 bytes, 256 bytes, 4 KiBs, …, 4 MiBs (*)

And even in workstations it is often limited to few megabytes

(*) = To avoid confusion with the SI standard, International Electrotechnical Commission standard 60027-2 specifies

kibibyte (KiB) == 1024 bytes, mebibyte (MiB) == 1024^2 bytes

Page 22: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#22/69 Erno Salminen - Nov. 2008

On Stack Use (2)On Stack Use (2)

In the worst case, there isn’t any noticeable warning on stack overflow until it is too late As local variables are allocated on the stack

Sum of local variables and stack contexts quickly underflowAvoid arrays as local variablesAvoid recursion

Calculate the worst case stack size by hand!

Page 23: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#23/69 Erno Salminen - Nov. 2008

Function callsFunction calls

Pass large parameter variables by-reference to the function, i.e. as a pointer

e.g. 32-bit should not passed in stack as it is in quite small in 8-bit machinepointer takes only 8-32 bits

Add specifier const to the pointer, if function is not meant to modify the variable,

This is correct way although MCC18 ignores the specifier

Page 24: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#24/69 Erno Salminen - Nov. 2008

MacrosMacros

Macros are created with preprocessor directive #define

1. Simple constants2. Bastardization of funtions

Simple textual find-replace happens before compilation, larger code sizePrefer real functions as they simplify debuggingUseful function-like macro#define dbg_level 2

#define dbg_print (message) \

{if (dbg_level >0){ cout << message; }}

If dbg_level==0Function would execute comparison everytime when calledMacro creates no extra code but function does

Page 25: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#25/69 Erno Salminen - Nov. 2008

Macros and inMacros and in--line functionsline functionsIn-line expansion: compiler inserts the complete body of the function in every context where that function is used

Avoid call overhead, increase code sizeHowever, in-line functions are better than macros

debugging is easier as error messages for macros refer to expanded code line and not the one the user wrotetype checking and argument list checkingcan return values from other expression than the last

Bjarne Stroustrup, the designer of C++emphasizes that macros should be avoided wherever possibleadvocates extensive use of inline functions

C++, C99, and GNU C each have support for inline functions, although 1989 ANSI C does not

Page 26: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

Erno Salminen - Nov. 2008

Function pointersFunction pointers

Page 27: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#27/69 Erno Salminen - Nov. 2008

Function pointersFunction pointers

Function pointers allow making run-time changes to code’s behaviorWhen dereferenced, a function pointer invokes a function, passing it zero or more arguments just like a normal functionAll functions called with the same function pointer, must have the same parameters and return-type!An array of function pointers can be indexed, no need for switch-case structureE.g. used for implementing menu system

Generic menu moduleShown texts in one arrayPointers to associated functions in another array

Page 28: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#28/69 Erno Salminen - Nov. 2008

Function pointers (2)Function pointers (2)Assigning a function pointer

int foo (int a, char b); // function’s prototypeint (*fptr)(int a, char b) = &foo; // or just =foo

Function pointers are often used in driver interfaces in operating system

in POSIX’s thread interface alsoAlso in real-time operating system (RTOS) to implement callback structure

A callback is executable code that is passed as an argument to other code. It allows a lower-level software layer to call a subroutine (or function) defined in a higher-level layer

Page 29: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#29/69 Erno Salminen - Nov. 2008

Function pointer exampleFunction pointer exampleTUTWSN SW library has a debug print facility via callback

Debug module accepts a function that prints one charThat function may be changed at runtime

Passing a function (pointer) to debug module:void DebugPrint_setOutput(void (*putc_func)(unsigned char chr));Calling the print function via debug module:

void DebugPrint_printf (rom char const* fmt, ...);

Usage inside DebugPrint happens as if the pointer was a regular function:

...; putc_func('H'); ...

Page 30: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#30/69 Erno Salminen - Nov. 2008

Function pointer example: usageFunction pointer example: usage

1. TUTWSN: Create a function that writes one character to serial port

void Serial_putc(unsigned char){...}

2. Set the above function as print function of the debug module

dbg module stores to pointer to itselsDebugPrint_setOutput(Serial_putc);

3. Print debug message to serial portDebugPrint_printf("HelloWorld");

Page 31: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

Erno Salminen - Nov. 2008

Common wisdom and Common wisdom and general guidelinesgeneral guidelines

Page 32: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

General guidelines

Charrette, Why software failsBoehm and Basili, SW Defect reduction Top-10 Selection from Sutter and Alexandrescu, C++ Coding Standards - Almost 101 rulesOther notes and recommendations

Page 33: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

Erno Salminen - Nov. 2008

Common WisdomCommon Wisdom

"C makes it easy to shoot yourself in the foot. C++ makes it harder, but when you do, it blows away your whole leg.“ --- Bjarne Stroustrup, creator of C++Everyone knows that debugging is twice as hard as writing a program in the first place. So if you're as clever as you can be when you write it, how will you ever debug it? --- Brian KernighanControlling complexity is the essence of computer programming. --- Brian Kernighan

Page 34: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#34/69 Erno Salminen - Nov. 2008

Why software failsWhy software fails

Reasons for failures fall into 3 categories1. Project management –related2. Context–related3. Implementation-related

Note that only category 3 is technical matterMost could be avoided with common sense and more or less human-scienceAlthough, the cited surveys discuss SW projects, the discussion may be generalized to HW and HW/SW projects as well

[R.N. Charette, Why software fails [software failure],Spectrum, IEEE, Vol. 42, Iss. 9, Sept. 2005, pp. 42 - 49. ]

[N. Holmes, The Data Doughnut and the Software Hole, Computer, Vol. 39, Iss. 6, June 2006, pp. 100 - 99.]

Page 35: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#35/69 Erno Salminen - Nov. 2008

Why software fails: Management 1Why software fails: Management 1

1. Unrealistic or unarticulated project goalsGet the end users involvedTry to infiltrate technical people when requirements are captured

Both from customer’s and developer’s sideThere is no free lunch: ”If you choose A, you cannot have B” – R. Colwell

Do you want a good car or a cheap car?Most simple thing, often forgotten

“Is it feasible?”http://www.youtube.com/watch?v=1GSV2kVkO1w

Page 36: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#36/69 Erno Salminen - Nov. 2008

Why software fails: Management 1bWhy software fails: Management 1b

1. Unrealistic or unarticulated project goals”Oh, I forgot to mention that our Gizmo must cost less than 1€...”Motivate your workers to aim for the common goal

Reward them for successAim for quantifiable goals

Goals that are unambiguosly met or notE.g. This projects cuts expenses by 8%. Expenses are calculated as...

Page 37: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#37/69 Erno Salminen - Nov. 2008

Why software fails: Management 2Why software fails: Management 2

2. Badly defined systems requirements

Fig: [J.P. Bowen, M.G. Hinchey, Ten Commandments of Formal Methods ...Ten Years Later, Computer, Vol. 39, Iss. 1, Jan. 2006, pp. 40 – 48]

Critical step in the projectEven if product meets the specification, it may not meet customer’s wishesReview and validate requirements thoroughly

get acceptance on black-and-white

Speak up if the requirements do not make any sense

Page 38: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#38/69 Erno Salminen - Nov. 2008

Why software fails: Management 2bWhy software fails: Management 2b2. Badly defined systems requirements

Or late changes to requirementsThe sooner the better; the less the bettere.g. Pentium bug: optimize area just before tape-out

However, changes are inevitableApply disciplined change procedurePostpone most, accept the critical changes

Poor requirement document creates ambiguity for the design - which way to choose?contradictory goals – which one is right?

Remember that most customers are inexperienced in requirement captureDocument also the self-evident things

”evident to one’s self and to nobidy else” - A. Bierce

Page 39: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#39/69

Why software fails: Management 3Why software fails: Management 3

3. Poor project management”All important decisions are made at least 2 organization steps above the level where the consequences are understood”Do not overestimate your (team’s) capabilitiesMost people are productive when they can concentrate on one thing at a timePrioritize

1.These features are absolutely necessary2.These might be incorporated if schedule

allows

Page 40: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#40/69

Why software fails: Management 3Why software fails: Management 3

3. Poor project managementInformation hiding seldom pays off

Give reasons to decicionsTell what exactly was promised to the customer

Long projects are also more lateSplit to small projects instead of ”sqeezing”

Settle few milestones that have to be metConvert the huge last week’s panic into several but smaller mid-week panics

Do not update your organizational structure every month

Page 41: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#41/69 Erno Salminen - Nov. 2008

Why software fails: Management 4Why software fails: Management 4

4. Inaccurate estimates of needed resourcesEverything takes longer than you think

Especially verification (e.g. 40-80% of project’s time)Comments regarding the exercise work, anyone?

Remember mythical man-monthMany tasks won’t finish sooner with more workersOften they are more late (managing overhead grows)Compare digging a well and trench

Account the other duties of the laboradministrative tasks, other projects, vacations...

One ”super-designer” may account 5-10 regular engineers

Page 42: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#42/69 Erno Salminen - Nov. 2008

Why software fails: Management 5Why software fails: Management 5--66

5. Poor reporting of the project’s statusStatus reports are boring, I know, but essentialNo reason to make things look nice – be realistic and honest

6. Unmanaged risksMother nature is a bitch and Murphy was an optimist.Prepare for the delays

part delivery, manufacturing, vacations, bugs, higher priority tasks, damaged equipment...

Question: How does a large software project get to be one year late?

Answer: One day at a time!

Page 43: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#43/69 Erno Salminen - Nov. 2008

Why software fails: Context 7Why software fails: Context 7--99

7. Poor communication among customers, developers, and usersRight hand does not what the left one is doingMake sure that each meeting has writtenconclusion which everone agrees

Make sure that everyone has access to those memosAccept and welcome the debateRemember to ask ”stupid” questions

8. Commercial pressuresE.g. rush to the marketE.g. feature explosion for marketing purposes

9. Stakeholder politics

Page 44: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#44/69 Erno Salminen - Nov. 2008

Why software fails: Implementation 10Why software fails: Implementation 10

10. Use of immature technologyOr technology unfamiliar to the developers or vendors

”Make sure that simple things work...”Project’s success should not hinge on the adequate performance of new technologyA project can be based on an emerging technology

thoughtful assessment that such a technology has extraordinary potential differential value achieved by being an early adopter

Even in these cases, first carry out pilot projects that provide experience with the technology

limit the scope of its implementation to minimize potential damage

Page 45: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#45/69 Erno Salminen - Nov. 2008

Why software fails: Implementation 11Why software fails: Implementation 11

11. Sloppy development practices, e.g.Poor documentationInconsistent namingNo version controlNo review processIgnoring the compiler warningsNot checking return valuesNot using assertions25% of admin time spent going down blind alleys due to bad msgs [Candea]”I hope someone else will check it””I’ll code this first and test after that”

Page 46: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#46/69 Erno Salminen - Nov. 2008

Why software fails: Implementation 12Why software fails: Implementation 12

12. Inability to handle the project’s complexityDivide-and-conquer, separation (orthogonalization) of concers

Separate computation and communicationSeparate function and architecture

Reuse everything you canModel-based design, model-driven engineering

Obtain early estimates and boundsEstablish the critical choices earlyAutomate the implementation via synthesis

Techniques for this challenge are addressed in TKT-2431 SoC Design

Page 47: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#47/69 Erno Salminen - Nov. 2008

Why software fails: Implementation 12bWhy software fails: Implementation 12b

12. Inability to handle the project’s complexity“The most important aspect of any design is how it is partitioned. The second most important aspect of any design is its interfaces.” – M. Keating

Minimize coupling between modulesDst and source parameters always in the same orderSimilar naming conventionUse consistent units

If some function users meters as units, no function should use millimeters

Try to make functionality obviousNames should not be too long but they should also be to-the-pointTry to make misuse hard (e.g. add checks and asserts to the code)

Page 48: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#48/69 Erno Salminen - Nov. 2008

Further reading on project managementFurther reading on project management

Robert P. Colwell, The Pentium Chronicles: The People, Passion, and Politics Behind Intel's Landmark Chips, Wiley-IEEE Computer Society, 2005Author is former chief IA32 architect for Pentium II, III, and 4 microprocessorsBrilliant stuff

Page 49: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#49/69 Erno Salminen - Nov. 2008

SW defect reduction Top 10: 1SW defect reduction Top 10: 1

1. Finding and fixing a software problem after delivery is often 100 times more expensive than finding and fixing it during the requirements and design phase

Top-10 rules: [B. Boehm, V.R. Basili, Software defection reduction Top 10 list, Computer, Vol. 34, Iss. 1, Jan. 2001, pp. 135 - 137 .]

Figure: [B.W. Boehm, Software Engineering, IEEE Trans. Computers, 1976]

log scale

thorough requirements analysis and design,early verification and validationon up-front prototyping and simulation

Page 50: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#50/69 Erno Salminen - Nov. 2008

SW defect reduction Top 10: 2SW defect reduction Top 10: 2

2. Current software projects spend about 40 to 50 percent of their effort on avoidable reworkRework means fixing difficulties that could have been discovered earlier and fixed less expensively or avoided altogether. Originate from

1. Hastily specified requirements2. Nominal-case design and development

Emergent design process for user-interactive systems

Requirements emerge from prototyping and other multistakeholder shared learning activitiesNot like reductionist process that sets requirements in advance, then reduces them to practice via design and coding

Page 51: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#51/69 Erno Salminen - Nov. 2008

SW defect reduction Top 10: 3SW defect reduction Top 10: 3--55

3. About 80 percent of avoidable rework comes from 20 percent of the defects

4. About 80 percent of the defects come from 20 percent of the modules, and about half the modules are defect free.

5. About 90 percent of the downtime comes from, at most, 10 percent of the defectsBugs do not live alone

Check deeply module where the bug was foundSeek similar bugs from elsewhere (man grep)

Identify the characteristics of error-prone modulescomplexity, level of data coupling, changes to reused code

Emphasize testing of high-risk scenarios

Page 52: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#52/69 Erno Salminen - Nov. 2008

SW defect reduction Top 10: 6SW defect reduction Top 10: 6--77

6. Peer reviews catch 60 percent of the defects7. Perspective-based reviews catch 35 percent

more defects than nondirected reviewsDesigner explains his/her work to the colleagues

1. specification – remove ambiguities, inconsistensies2. code – clarify code, add checks

Very effective even if listeners do not understand everything!

Designer has to formulate the intent more thoroughly when presenting itNot just one or two times when the designer detects the bug himself

Limited to small designs at a time

Page 53: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#53/69 Erno Salminen - Nov. 2008

SW defect reduction Top 10: 8SW defect reduction Top 10: 8

8. Disciplined personal practices can reduce defect introduction rates by up to 75 percentCreate checklistsAutomate (we are dealing with ATK after all)

Compilation, synthesis, Test benches, regression testingConformance to coding style

Accept no warnings More examples about recommended pratices coming in sequel

Page 54: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#54/69 Erno Salminen - Nov. 2008

SW defect reduction Top 10: 9SW defect reduction Top 10: 9--1010

9. All other things being equal, it costs 50 percent more per source instruction to develop high-dependability software products than to develop low-dependability software products

However, the investment is more than worth it if the project involves significant operations and maintenance costsTypical life-cycle cost distribution of 30 percent development and 70 percent maintenance

10. About 40 to 50 percent of user programs contain nontrivial defects

There are more and more programmers with little expertise to avoid or detect high-risk defects but tremendous power to create themTool vendors should provide ”seat belts and air bags”

Page 55: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#55/69 Erno Salminen - Nov. 2008

Almost 101 Rules, Guidelines, and Best Almost 101 Rules, Guidelines, and Best practices: practices: Organizational and policy issuesOrganizational and policy issues

0. Don’t sweat the small stuffCreate coding standard that someone can actually followDon’t over-specify formatting, e.g. indentation, location of braces, header formatAutomatic check must produce zero warningsExample: Linux kernel coding style

http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6.git;a=blob_plain;f=Documentation/CodingStyle;hb=HEAD

1. Compile cleanly at high warning levels.2. Use automated build system.3. Use version control system.4. Invest in code reviews.

Numbered guidelines from the book, bullets both from lecturer and the book.

Page 56: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#56/69 Erno Salminen - Nov. 2008

Rules ... (2): Design styleRules ... (2): Design style

5. Give one entity one cohesive responsibility.6. Correctness, simplicity, and clarity come first.

Progams must be written for people to read, and only incidentally for machines to execute – H. Abelson, G.J. SussmanA clever algorithm is harder to understand and debug.Write only a single statement per line

int x,y; // not like thisif ((x = foo()) == NULL) { // not like thisint x;int y;x = foo();if (x == NULL) {

7. Know when and how to code for scalability.

Page 57: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#57/69 Erno Salminen - Nov. 2008

Rules ... (3): Design styleRules ... (3): Design style8. Don’t optimize prematurely.

A clever algorithm is harder to understand and debug1st rule: Don’t optimize2nd rule (for experts only): Don’t do it yet. Measure twice, optimize once.”Premature optimization is the root of all evil” – D. Knuth [quoting Hoare]When in doubt, use brute force (Kernighan and Ritchie, inventors of C)

9. Don’t pessimize prematurely.10. Minimize global and shared data.

Shared data causes contention, increases coupling which reduces maintainabilityWeakens unit testing

11. Hide information.Localizes changes; fewer places that corrupt the data

Page 58: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#58/69 Erno Salminen - Nov. 2008

Rules ... (4): Coding styleRules ... (4): Coding style

12. Know when and how to code for concurrency.

ThsareafedlyBe very careful with semaphores

14. Prefer compile- and link-time errors to run-time errors.

Static checks are independent of the program flow (input data) → stronger confidenceError messages with one LED are hard to understandUse assertions to catch run-time errors

15. Use const proactively.

Page 59: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#59/69 Erno Salminen - Nov. 2008

Rules ... (5): Coding styleRules ... (5): Coding style

16. Avoid macros.17. Avoid magic numbers.

Numerical valued inside the code that are not self-explanatory

int array_len = 42;... // thousand lines of code here...for (i=0; i < 35; i++)... // 35 = 42-7, of course!

The worst are those derived from other magical valuesDefine well-named constants instead

18. Declare variables as locally as possible.Pay attention to naming and comment the purpose

Page 60: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#60/69 Erno Salminen - Nov. 2008

Rules ... (6): Coding styleRules ... (6): Coding style

19. Always initialize variables.Compiler is not forced to perform any initializationIn best case, uninitialized variables crash your system. Often they just result in byzantine faults

20. Avoid long functions. Avoid deep nesting.Avoid more than 78 characters per lineWrite new functions when indentation level growsFunction should fit into few (≤3) screensNo more than 3 levels of indentation and Indent 4 or 8 spaces per indentation levelNo more than 5-10 local variables

23. Make header files self-sufficient.Header includes all other headers it needs. But no others.

Page 61: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#61/69 Erno Salminen - Nov. 2008

Rules ... (7): Rules ... (7): FunctionsFunctions

Eliminate common codeSame code sequence only once in the programReuse existing code, examples and templates

Many common errors were probably already fixed

25. Take parameters appropriately by value, (smart) pointer, or reference.

Distinguish between input, output, and input/output parametersAdd const to pointers that are input-only parameters

31. Don’t write code that depends on the order of evaluation of function arguments.res= Transmogrify (++a, a++); // aargh

Page 62: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#62/69 Erno Salminen - Nov. 2008

Rules ... (8): Rules ... (8): Errors handlingErrors handling

ALWAYS CHECK RETURN VALUESBugs and thinking errors are caught earlier in development with diligent return value checking

68. Assert liberally to document internal assumptions and invariants.

Comments are good but assertions are way betterThey check the basic assumption that should always holdAsserts save debugging effort, money, sanity, reputation”Always ON”, not just in test bench#include <assert.h>...

assert (i < 100);

Program terminates if condition does not hold

Page 63: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#63/69 Erno Salminen - Nov. 2008

Rules ... (9): Type safetyRules ... (9): Type safety

91. Rely on types, not on representations.94. Avoid casting away const.97. Don’t use unions to reinterpret representation.98. Don’t use varargs (ellipsis).

Rules taken from: H. Sutter, A. Alexandrescu, C++ Coding Standards: 101 Rules, Guidelines, and Best Practices (C++ In-Depth Series), Addison-Wesley Professional, Nov. 2004.

Page 64: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

Erno Salminen - Nov. 2008

MiscMisc

Page 65: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#65/69 Erno Salminen - Nov. 2008

Version controlVersion control

Use version control (Git, SVN, ...)Teaches one to take logically consistent steps in a projectHelps backup processEasy throw-away code prototypingKeeps track of your work (how many changes in a week?)Keeps track who did whatOne can go back to see any previous versionA must for all work

Page 66: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#66/69 Erno Salminen - Nov. 2008

ProgramProgram’’s controls control

Three basic choicesa) Simple control loop (sense – act – wait)

Use this when possibleb) Light-weigth, non-preemptive operating system (OS)c) Pre-emptive OS (possbily with real-time features)

Trade-off betweenfeatures – multi-threading, communication, sheculingcosts - time overhead and mamory usage

Try to obtain already tried control for any non-trivial application

See also Jim Turley, Embedded systems survey: Operating systems up for grabs, Embedded Systems Design, May 2005.

Page 67: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#67/69

ProgramProgram’’s control (2)s control (2)

Be careful with while and for loops:What is the initial condition?What is the end condition?What is the step?break often needss special care that after the loopDoes continue interfere with stepping? Was something left undone?

Purely computational parts of the program can be designed, developed and tested on a workstation

This often means better development toolsUse good debuggers, verifying compilers (Sparse), and memory error checkers (valgrind)Also style analyzers (lint tools)

Page 68: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#68/69

Double buffering

Allows concurrent computation and communicationAllocate two buffers and simultaneously

fill one with new dataprocess the data that already exists in the other buffer

Switch buffers when both operations completedBuffer filling with ISR and DMA (direct-memory access)Use interrupt service routine to notice that a buffer has been filled

CPUCPU MemoryMemory

data sourcedata sourcenew data

buf0

buf1processed data

Page 69: TKT-3500 Microcontroller systems · TKT-3500 Microcontroller systems Lec 10 – Arithmetics, stack, ... Floating-point unit ... zDebug module accepts a function that prints one

#69/69

Further readingFurther reading

History's Worst Software Bugs (Wired) http://www.wired.com/news/technology/bugs/0,2924,69355,00.html

Software Horror Stories (Nachum Deshowitz, Tel Aviv University)

http://www.cs.tau.ac.il/~nachumd/horror.htmlFailure Rate (collection of failure rate statistics from IT surveys)

http://www.it-cortex.com/Stat_Failure_Rate.htmThe DailyWTF

http://thedailywtf.com/More on management's role in IT project failures: the failure rate of IT projects is quite high (John Glaser)

http://www.allbusiness.com/technology/306312-1.html