Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 25 Embedded systems programming Bjarne Stroustrup www.stroustrup.com/Programming.

Similar presentations


Presentation on theme: "Chapter 25 Embedded systems programming Bjarne Stroustrup www.stroustrup.com/Programming."— Presentation transcript:

1 Chapter 25 Embedded systems programming Bjarne Stroustrup www.stroustrup.com/Programming

2 Abstract This lecture provides a brief overview of what distinguishes embedded systems programming from ordinary programming. It then touches upon facilities that become prominent or problems when working close to the hardware such as free store use, bit manipulation, and coding standards. Remember: not all computers are little grey boxes hiding under desks in offices. This lecture provides a brief overview of what distinguishes embedded systems programming from ordinary programming. It then touches upon facilities that become prominent or problems when working close to the hardware such as free store use, bit manipulation, and coding standards. Remember: not all computers are little grey boxes hiding under desks in offices. 2Stroustrup/Programming

3 Overview Embedded systems Embedded systems Whats special/different Whats special/different predictability predictability Resource management Resource management memory memory Access to hardware Access to hardware Absolute addresses Absolute addresses Bits – unsigned Bits – unsigned Coding standards Coding standards 3Stroustrup/Programming

4 Embedded systems Hard real time Hard real time Response must occur before the deadline Response must occur before the deadline Soft real time Soft real time Response should occur before the deadline most of the time Response should occur before the deadline most of the time Often there are plenty of resources to handle the common cases Often there are plenty of resources to handle the common cases But crises happen and must be handled But crises happen and must be handled Predictability is key Predictability is key Correctness is even more important than usual Correctness is even more important than usual correctness is not an abstract concept correctness is not an abstract concept but I assumed that the hardware worked correctly is no excuse but I assumed that the hardware worked correctly is no excuse Over a long time and over a large range of conditions, it simply doesnt Over a long time and over a large range of conditions, it simply doesnt 4Stroustrup/Programming

5 Embedded systems Computers used as part of a larger system Computers used as part of a larger system That usually doesnt look like a computer That usually controls physical devices Often reliability is critical Often reliability is critical Critical as in if the system fails someone might die Often resources (memory, processor capacity) are limited Often resources (memory, processor capacity) are limited Often real-time response is essential Often real-time response is essential 5Stroustrup/Programming

6 Embedded systems What are we talking about? What are we talking about? Assembly line quality monitors Assembly line quality monitors Bar code readers Bar code readers Bread machines Bread machines Cameras Cameras Car assembly robots Car assembly robots Cell phones Cell phones Centrifuge controllers Centrifuge controllers CD players CD players Disk drive controllers Disk drive controllers Smart card processors Smart card processors 6 Fuel injector controls Fuel injector controls Medical equipment monitors Medical equipment monitors PDAs PDAs Printer controllers Printer controllers Sound systems Sound systems Rice cookers Rice cookers Telephone switches Telephone switches Water pump controllers Water pump controllers Welding machines Welding machines Windmills Windmills Wrist watches Wrist watches … Stroustrup/Programming

7 Do You Need to Know This Stuff ? Computer Engineers – You will build and oversee the building of these systems Computer Engineers – You will build and oversee the building of these systems All close to he hardware code resembles this All close to he hardware code resembles this The concern for correctness and predictability of embedded systems code is simply a more critical form of what we want for all code The concern for correctness and predictability of embedded systems code is simply a more critical form of what we want for all code Electrical Engineers – You will build and oversee the building of these systems. Electrical Engineers – You will build and oversee the building of these systems. You have to work with the computer guys You have to work with the computer guys You have to be able to talk to them You have to be able to talk to them You may have to teach them You may have to teach them You may have to take over for them You may have to take over for them Computer scientists – youll know to do this or only work on web applications (and the like) Computer scientists – youll know to do this or only work on web applications (and the like) 7Stroustrup/Programming

8 Predictability C++ operations execute in constant, measurable time C++ operations execute in constant, measurable time E.g., you can simply measure the time for an add operation or a virtual function call and thatll be the cost of every such add operation and every virtual function call (pipelining, caching, implicit concurrency makes this somewhat trickier on some modern processors) E.g., you can simply measure the time for an add operation or a virtual function call and thatll be the cost of every such add operation and every virtual function call (pipelining, caching, implicit concurrency makes this somewhat trickier on some modern processors) With the exception of: With the exception of: Free store allocation (new) Free store allocation (new) Exception throw Exception throw So throw and new are typically banned in hard real-time applications So throw and new are typically banned in hard real-time applications Today, I wouldnt fly in a plane that used those Today, I wouldnt fly in a plane that used those In 5 years, well have solved the problem for throw In 5 years, well have solved the problem for throw Each individual throw is predictable Each individual throw is predictable Not just in C++ programs Not just in C++ programs Similar operations in other languages are similarly avoided Similar operations in other languages are similarly avoided 8Stroustrup/Programming

9 Ideals/aims Given the constraints Given the constraints Keep the highest level of abstraction Keep the highest level of abstraction Dont write glorified assembler code Dont write glorified assembler code Represent your ideas directly in code Represent your ideas directly in code As always, try to write the clearest, cleanest, most maintainable code As always, try to write the clearest, cleanest, most maintainable code Dont optimize until you have to Dont optimize until you have to People far too often optimize prematurely People far too often optimize prematurely John Bentley's rules for optimization John Bentley's rules for optimization First law: Dont do it First law: Dont do it Second law (for experts only): Dont do it yet Second law (for experts only): Dont do it yet 9Stroustrup/Programming

10 Embedded systems programming You (usually) have to be much more aware of the resources consumed in embedded systems programming than you have to in ordinary programs You (usually) have to be much more aware of the resources consumed in embedded systems programming than you have to in ordinary programs Time Time Space Space Communication channels Communication channels Files Files ROM (Read-Only Memory) ROM (Read-Only Memory) Flash memory Flash memory … You must take the time to learn about the way your language features are implemented for a particular platform You must take the time to learn about the way your language features are implemented for a particular platform Hardware Hardware Operating system Operating system Libraries Libraries 10Stroustrup/Programming

11 Embedded systems programming A lot of this kind of programming is A lot of this kind of programming is Looking at specialized features of an RTOS (Real Time Operating System) Looking at specialized features of an RTOS (Real Time Operating System) Using a Non-hosted environment (thats one way of saying a language right on top of hardware without an operating system) Using a Non-hosted environment (thats one way of saying a language right on top of hardware without an operating system) Involving (sometimes complex) device driver architectures Involving (sometimes complex) device driver architectures Dealing directly with hardware device interfaces Dealing directly with hardware device interfaces … We wont go into details here We wont go into details here Thats what specific courses and manuals are for Thats what specific courses and manuals are for 11Stroustrup/Programming

12 How to live without new Whats the problem Whats the problem C++ code refers directly to memory C++ code refers directly to memory Once allocated, an object cannot be moved (or can it?) Once allocated, an object cannot be moved (or can it?) Allocation delays Allocation delays The effort needed to find a new free chunk of memory of a given size depends on what has already been allocated The effort needed to find a new free chunk of memory of a given size depends on what has already been allocated Fragmentation Fragmentation If you have a hole (free space) of size N and you allocate an object of size M where M { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://images.slideplayer.com/1/677695/slides/slide_12.jpg", "name": "How to live without new Whats the problem Whats the problem C++ code refers directly to memory C++ code refers directly to memory Once allocated, an object cannot be moved (or can it?) Once allocated, an object cannot be moved (or can it?) Allocation delays Allocation delays The effort needed to find a new free chunk of memory of a given size depends on what has already been allocated The effort needed to find a new free chunk of memory of a given size depends on what has already been allocated Fragmentation Fragmentation If you have a hole (free space) of size N and you allocate an object of size M where M

13 How to live without new Solution: pre-allocate Solution: pre-allocate Global objects Global objects Allocated at startup time Allocated at startup time Sets aside a fixed amount of memory Sets aside a fixed amount of memory Stacks Stacks Grow and shrink only at the top Grow and shrink only at the top No fragmentation No fragmentation Constant time operations Constant time operations Pools of fixed sized objects Pools of fixed sized objects We can allocate and deallocate We can allocate and deallocate No fragmentation No fragmentation Constant time operations Constant time operations 13 Pool: Stack: Top of stack Stroustrup/Programming

14 How to live without new No new (of course) No new (of course) And no malloc() (memory allocation during runtime) either (for those of you who speak C) And no malloc() (memory allocation during runtime) either (for those of you who speak C) No standard library containers (they use free store indirectly) No standard library containers (they use free store indirectly) Instead Instead Define (or borrow) fixed-sized Pools Define (or borrow) fixed-sized Pools Define (or borrow) fixed-sized Stacks Define (or borrow) fixed-sized Stacks Do not regress to using arrays and lots of pointers Do not regress to using arrays and lots of pointers 14Stroustrup/Programming

15 Pool example // Note: element type known at compile time // allocation times are completely predictable (and short) // the user has to pre-calculate the maximum number of elements needed template class Pool { public: Pool();// make pool of N Ts – construct pools only during startup T* get();// get a T from the pool; return 0 if no free Ts void free(T*);// return a T given out by get() to the pool private: // keep track of T[N] array (e.g., a list of free objects) }; Pool sb_pool; Pool indicator_pool; 15Stroustrup/Programming

16 Stack example // Note: allocation times completely predictable (and short) // the user has to pre-calculate the maximum number of elements needed template class Stack { public: Stack();// make an N byte stack – construct stacks only during startup void* get(int N); // allocate n bytes from the stack; return 0 if no free space void free(void* p); // return the last block returned by get() to the stack private: // keep track of an array of N bytes (e.g. a top of stack pointer) }; Stack my_free_store;// 50K worth of storage to be used as a stack void* pv1 = my_free_store.get(1024); int* pi = static_cast (pv1);// you have to convert memory to objects void* pv2 = my_free_store.get(50); Pump_driver* pdriver = static_cast (pv2); 16Stroustrup/Programming

17 Templates Excellent for embedded systems work Excellent for embedded systems work No runtime overhead for inline operations No runtime overhead for inline operations Sometimes performance matters Sometimes performance matters No memory used for unused operations No memory used for unused operations In embedded systems memory is often critical (limited) In embedded systems memory is often critical (limited) 17Stroustrup/Programming

18 How to live with failing hardware Failing how? Failing how? In general, we cannot know In general, we cannot know In practice, we can assume that some kinds of errors are more common than others In practice, we can assume that some kinds of errors are more common than others But sometimes a memory bit just decides to change But sometimes a memory bit just decides to change Why? Why? Power surges/failure Power surges/failure The connector vibrated out of its socket The connector vibrated out of its socket Falling debris Falling debris Falling computer Falling computer X-rays X-rays … Transient errors are the worst Transient errors are the worst E.g., only when the temperature exceeds 100° F. and the cabinet door is closed E.g., only when the temperature exceeds 100° F. and the cabinet door is closed Errors that occur away from the lab are the worst Errors that occur away from the lab are the worst E.g., on Mars E.g., on Mars 18Stroustrup/Programming

19 How to live with failing hardware Replicate Replicate In emergency, use a spare In emergency, use a spare Self-check Self-check Know when the program (or hardware) is misbehaving Know when the program (or hardware) is misbehaving Have a quick way out of misbehaving code Have a quick way out of misbehaving code Make systems modular Make systems modular Have some other module, computer, part of the system responsible for serious errors Have some other module, computer, part of the system responsible for serious errors In the end, maybe a person i.e., manual override In the end, maybe a person i.e., manual override Remember HAL ? Remember HAL ? Monitor (sub)systems Monitor (sub)systems In case they cant/dont notice problems themselves In case they cant/dont notice problems themselves 19Stroustrup/Programming

20 Absolute addresses Physical resources (e.g., control registers for external devices) and their most basic software controls typically exist at specific addresses in a low-level system Physical resources (e.g., control registers for external devices) and their most basic software controls typically exist at specific addresses in a low-level system We have to enter such addresses into our programs and give a type to such data We have to enter such addresses into our programs and give a type to such data For example For example Device_driver* p = reinterpret_cast (0xffb8); Serial_port_base *COM1 = reinterpret_cast (0x3f8); 20Stroustrup/Programming

21 Bit manipulation: Unsigned integers How do you represent a set of bits in C++? How do you represent a set of bits in C++? unsigned char uc;// 8 bits unsigned char uc;// 8 bits unsigned short us;// typically 16 bits unsigned short us;// typically 16 bits unsigned int ui;// typically 16 bits or 32 bits // (check before using) // many embedded systems have 16-bit ints unsigned int ui;// typically 16 bits or 32 bits // (check before using) // many embedded systems have 16-bit ints unsigned long int ul;// typically 32 bits or 64 bits unsigned long int ul;// typically 32 bits or 64 bits std::vector vb(93);// 93 bits std::vector vb(93);// 93 bits Use only if you really need more than 32 bits Use only if you really need more than 32 bits std::bitset bs(314);// 314 bits std::bitset bs(314);// 314 bits Use only if you really need more than 32 bits Use only if you really need more than 32 bits Typically efficient for multiples of sizeof(int) Typically efficient for multiples of sizeof(int) 21Stroustrup/Programming

22 Bit manipulation & and & and | inclusive or | inclusive or ^ exclusive or ^ exclusive or <> right shift >> right shift ~ ones complement ~ ones complement 22 01001011 0xaa 00011110 0x0f 00001010 0x0a a: a&b: b: 00011000 0x03b>>2: 11100001 0xf0~b: 01011111 0xafa|b: 01010101 0xa5a^b: 10100100 0x54a<<1: Stroustrup/Programming

23 Bit manipulation Bitwise operations Bitwise operations & (and) | (or) ^ (exclusive or – xor) << (left shift) >> (right shift) ~ (one's complement) Basically, what the hardware provides right: For example For example void f(unsigned short val)// assume 16-bit, 2-byte short integer { unsigned char right = val & 0xff ; // rightmost (least significant) byte unsigned char left = (val>>8) & 0xff ; // leftmost (most significant) byte bool negative = val & 0x8000 ; // sign bit (if 2s complement) // … } 23 110010101100110 Sign bit 11111111 0xff: 8 bits == 1 byte 0 10010 val 011 falsetrue Stroustrup/Programming

24 Bit manipulation Or | Or | Set a bit Set a bit And & And & Is a bit set? Select (mask) some bits Is a bit set? Select (mask) some bits For example: For example: enum Flags { bit4=1<<4, bit3=1<<3, bit2=1<<2, bit1=1<<1, bit0=1 }; unsigned char x = bit3 | bit1;// x becomes 8+2 x |= bit2;// x becomes 8+4+2 if (x&bit3) {// is bit3 set? (yes, it is) // … } unsigned char y = x &(bit4|bit2);// y becomes 4 Flags z = Flags(bit2|bit0); // the cast is necessary because the compiler // doesnt know that 5 is in the Flags range // doesnt know that 5 is in the Flags range 24 11111111 0xff: 01111 val 000 Stroustrup/Programming

25 Bit manipulation Exclusive or (xor) ^ Exclusive or (xor) ^ a^b means (a|b) & !(a&b) either a or b but not both a^b means (a|b) & !(a&b) either a or b but not both unsigned char a = 0xaa; unsigned char b = 0x0f; unsigned char c = a^b; Immensely important in graphics and cryptography Immensely important in graphics and cryptography 25 01001011 0xaa 00011110 0x0f 01010101 0xa5 a: a^b: b: Stroustrup/Programming

26 Unsigned integers You can do ordinary arithmetic on unsigned integers You can do ordinary arithmetic on unsigned integers Avoid that when you can Avoid that when you can Try never to use unsigned just to get another bit of precision Try never to use unsigned just to get another bit of precision If you need one extra bit, soon, youll need another If you need one extra bit, soon, youll need another Dont mix signed and unsigned in an expression Dont mix signed and unsigned in an expression You cant completely avoid unsigned arithmetic You cant completely avoid unsigned arithmetic Indexing into standard library containers uses unsigned (in my opinion, thats a design error) Indexing into standard library containers uses unsigned (in my opinion, thats a design error) vector v; // … for (int i = 0; i { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://images.slideplayer.com/1/677695/slides/slide_26.jpg", "name": "Unsigned integers You can do ordinary arithmetic on unsigned integers You can do ordinary arithmetic on unsigned integers Avoid that when you can Avoid that when you can Try never to use unsigned just to get another bit of precision Try never to use unsigned just to get another bit of precision If you need one extra bit, soon, youll need another If you need one extra bit, soon, youll need another Dont mix signed and unsigned in an expression Dont mix signed and unsigned in an expression You cant completely avoid unsigned arithmetic You cant completely avoid unsigned arithmetic Indexing into standard library containers uses unsigned (in my opinion, thats a design error) Indexing into standard library containers uses unsigned (in my opinion, thats a design error) vector v; // … for (int i = 0; i

27 Complexity One source of errors is complicated problems One source of errors is complicated problems Inherent complexity Inherent complexity Another source of errors is poorly-written code Another source of errors is poorly-written code Incidental complexity Incidental complexity Reasons for unnecessarily complicated code Reasons for unnecessarily complicated code Overly clever programmers Overly clever programmers Who use features they dont understand Who use features they dont understand Undereducated programmers Undereducated programmers Who dont use the most appropriate features Who dont use the most appropriate features Large variations in programming style Large variations in programming style 27Stroustrup/Programming

28 Coding standards A coding standard is a set of rules for what code should look like A coding standard is a set of rules for what code should look like Typically specifying naming and indentation rules Typically specifying naming and indentation rules E.g., use Stroustrup layout E.g., use Stroustrup layout Typically specifying a subset of a language Typically specifying a subset of a language E.g., dont use new or throw to avoid predictability problems E.g., dont use new or throw to avoid predictability problems Typically specifying rules for commenting Typically specifying rules for commenting Every function must have a comment explaining what it does Every function must have a comment explaining what it does Often requiring the use of certain libraries Often requiring the use of certain libraries E.g., use rather than to avoid safety problems E.g., use rather than to avoid safety problems Organizations often try to manage complexity through coding standards Organizations often try to manage complexity through coding standards Often they fail and create more complexity than they manage Often they fail and create more complexity than they manage 28Stroustrup/Programming

29 Coding standards A good coding standard is better than no standard A good coding standard is better than no standard I wouldnt start a major (multi-person, multi-year) industrial project without one I wouldnt start a major (multi-person, multi-year) industrial project without one A poor coding standard can be worse than no standard A poor coding standard can be worse than no standard C++ coding standards that restrict programming to something like the C subset do harm C++ coding standards that restrict programming to something like the C subset do harm They are not uncommon They are not uncommon All coding standards are disliked by programmers All coding standards are disliked by programmers Even the good ones Even the good ones All programmers want to write their code exactly their own way All programmers want to write their code exactly their own way A good coding standard is prescriptive as well as restrictive A good coding standard is prescriptive as well as restrictive Here is a good way of doing things as well as Here is a good way of doing things as well as Never do this Never do this A good coding standard gives rationales for its rules A good coding standard gives rationales for its rules And examples And examples 29Stroustrup/Programming

30 Coding standards Common aims Common aims Reliability Reliability Portability Portability Maintainability Maintainability Testability Testability Reusability Reusability Extensibility Extensibility Readability Readability 30Stroustrup/Programming

31 Some sample rules No function shall have more than 200 lines (30 would be even better) No function shall have more than 200 lines (30 would be even better) that is, 200 non-comment source lines that is, 200 non-comment source lines Each new statement starts on a new line Each new statement starts on a new line E.g., int a = 7; x = a+7; f(x,9);// violation! E.g., int a = 7; x = a+7; f(x,9);// violation! No macros shall be used except for source control No macros shall be used except for source control using #ifdef and #ifndef using #ifdef and #ifndef Identifiers should be given descriptive names Identifiers should be given descriptive names May contain common abbreviations and acronyms May contain common abbreviations and acronyms When used conventionally, x, y, i, j, etc., are descriptive When used conventionally, x, y, i, j, etc., are descriptive Use the number_of_elements style rather than the numberOfElements style Use the number_of_elements style rather than the numberOfElements style Type names and constants start with a capital letter Type names and constants start with a capital letter E.g., Device_driver and Buffer_pool E.g., Device_driver and Buffer_pool Identifiers shall not differ only by case Identifiers shall not differ only by case E.g., Head and head// violation! E.g., Head and head// violation! 31Stroustrup/Programming

32 Some more sample rules Identifiers in an inner scope should not be identical to identifiers in an outer scope Identifiers in an inner scope should not be identical to identifiers in an outer scope E.g., int var = 9; { int var = 7; ++var; }// violation: var hides var E.g., int var = 9; { int var = 7; ++var; }// violation: var hides var Declarations shall be declared in the smallest possible scope Declarations shall be declared in the smallest possible scope Variables shall be initialized Variables shall be initialized E.g., int var;// violation: var is not initialized E.g., int var;// violation: var is not initialized Casts should be used only when essential Casts should be used only when essential Code should not depend on precedence rules below the level of arithmetic expressions Code should not depend on precedence rules below the level of arithmetic expressions E.g., x = a*b+c;// ok if( a { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://images.slideplayer.com/1/677695/slides/slide_32.jpg", "name": "Some more sample rules Identifiers in an inner scope should not be identical to identifiers in an outer scope Identifiers in an inner scope should not be identical to identifiers in an outer scope E.g., int var = 9; { int var = 7; ++var; }// violation: var hides var E.g., int var = 9; { int var = 7; ++var; }// violation: var hides var Declarations shall be declared in the smallest possible scope Declarations shall be declared in the smallest possible scope Variables shall be initialized Variables shall be initialized E.g., int var;// violation: var is not initialized E.g., int var;// violation: var is not initialized Casts should be used only when essential Casts should be used only when essential Code should not depend on precedence rules below the level of arithmetic expressions Code should not depend on precedence rules below the level of arithmetic expressions E.g., x = a*b+c;// ok if( a

33 An example of bit manipulation The Tiny Encryption Algorithm (TEA) The Tiny Encryption Algorithm (TEA) Originally by David Wheeler Originally by David Wheeler http://143.53.36.235:8080/tea.htm http://143.53.36.235:8080/tea.htm Dont look too hard at the code (unless you happen to need a good simple encryption algorithm for an application); its simply to give you the flavor of some bit manipulation code Dont look too hard at the code (unless you happen to need a good simple encryption algorithm for an application); its simply to give you the flavor of some bit manipulation code It takes one word (4 bytes at a time) It takes one word (4 bytes at a time) E.g., 4 characters from a string or an image file E.g., 4 characters from a string or an image file It assumes 4-byte long integers It assumes 4-byte long integers Explanation is at the link (and in the book) Explanation is at the link (and in the book) Without the explanation this is just an example of how bit manipulation code can look. This code is not meant to be self-explanatory. Without the explanation this is just an example of how bit manipulation code can look. This code is not meant to be self-explanatory. 33Stroustrup/Programming

34 TEA void encipher( const unsigned long *const v, unsigned long *const w, const unsigned long * const k) { unsigned long y = v[0]; unsigned long z = v[1]; unsigned long sum = 0; unsigned long delta = 0x9E3779B9; unsigned long n = 32; while(n-->0) { y += (z > 5) + z ^ sum + k[sum&3]; sum += delta; z += (y > 5) + y ^ sum + k[sum>>11 & 3]; }w[0]=y;w[1]=z;} 34Stroustrup/Programming

35 TEA void decipher( const unsigned long *const v, unsigned long *const w, const unsigned long * const k) { unsigned long y = v[0]; unsigned long z = v[1]; unsigned long sum = 0xC6EF3720; unsigned long delta = 0x9E3779B9; unsigned long n = 32; // sum = delta<<5; in general, sum = delta * n while(n-->0) { z -= (y > 5) + y ^ sum + k[sum>>11 & 3]; sum -= delta; y -= (z > 5) + z ^ sum + k[sum&3]; }w[0]=y;w[1]=z;} 35Stroustrup/Programming


Download ppt "Chapter 25 Embedded systems programming Bjarne Stroustrup www.stroustrup.com/Programming."

Similar presentations


Ads by Google