Download as pdf or txt
Download as pdf or txt
You are on page 1of 222

SRI RAMAKRISHNA ENGINEERING COLLEGE

[Educational Service : SNR Sons Charitable Trust]


[Autonomous Institution, Reaccredited by NAAC with ‘A+’ Grade]
[Approved by AICTE and Permanently Affiliated to Anna University, Chennai]
[ISO 9001:2015 Certified and all eligible programmes Accredited by NBA]
VATTAMALAIPALAYAM, N.G.G.O. COLONY POST, COIMBATORE – 641 022.

B.E. ELECTRONICS & COMMUNICATION


ENGINEERING

20EC211 – EMBEDDED SYSTEMS AND


INTERNET OF THINGS
Semester : 05 Year : III
Academic Year : 2023-2024
VISION OF THE COLLEGE

 To develop into a leading world class Technological University consisting

of Schools of Excellence in various disciplines with a co-existent Centre


for Engineering Solutions Development for world-wide clientele.

20EC211- Embedded Systems & IoT RAJASEKAR T, AP/ECE 2


MISSION OF THE COLLEGE

 To provide all necessary inputs to the students for them to grow into

knowledge engineers and scientists attaining.


 Excellence in domain knowledge- practice and theory.

 Excellence in co-curricular and Extra curricular talents.

 Excellence in character and personality.

20EC211- Embedded Systems & IoT RAJASEKAR T, AP/ECE 3


VISION AND MISSION OF THE
DEPARTMENT
Vision
• To develop Electronics and Communication Engineers by keeping pace
with changing technologies, professionalism, creativity research and
employability.
Mission
• To provide quality an contemporary education through effective
teaching- learning process that equips the students with adequate
knowledge in Electronics and Communication Engineering for a
successful career.
• To inculcate the students in problem solving and lifelong learning skills
that will enable them to pursue higher studies and career in research.
• To produce engineers with effective communication skills, the abilities to
lead a team adhering to ethical values and inclination serve the society.

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 4
& IoT
Programme Educational
Objectives(PEOs) of the Programme
• The Program Educational Objective (PEOs) of ECE is established through
consultative process. The PEOs of Electronics and Communication
Engineering will demonstrate the following qualities which would be
attained by the graduates after few years of graduation.
• PEO 1 Excel in professional career to provide engineering solution by
demonstrating technical competence and by acquiring knowledge in
electronics and communication engineering.
• PEO 2 Identify, analyze and formulate problems to offer appropriate
design solutions that are technically superior, economically feasible,
environmentally compatible, professionally ethical and socially
acceptable.
• PEO 3 Achieve progress in professional and research career through
communication skills, team work and knowledge up gradation through
higher education.
20EC211- Embedded Systems
RAJASEKAR T, AP/ECE 5
& IoT
Programme Outcomes (POs)
• PO1. Engineering knowledge: Apply the knowledge of mathematics,
science, engineering fundamentals, and an engineering specialization to
the solution of complex engineering problems.
• PO2. Problem analysis: Identify, formulate, review research
literature, and analyze complex engineering problems reaching
substantiated conclusions using first principles of mathematics, natural
sciences, and engineering sciences.
• PO3. Design/development of solutions: Design solutions for complex
engineering problems and design system components or processes that
meet the specified needs with appropriate consideration for the public
health and safety, and the cultural, societal, and environmental
considerations.

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 6
& IoT
Programme Outcomes (POs)
• PO4. Conduct investigations of complex problems: Use research-
based knowledge and research methods including design of experiments,
analysis and interpretation of data, and synthesis of the information to
provide valid conclusions.
• PO5. Modern tool usage: Create, select, and apply appropriate
techniques, resources, and modern engineering and IT tools including
prediction and modeling to complex engineering activities with an
understanding of the limitations.
• PO6. The engineer and society: Apply reasoning informed by the
contextual knowledge to assess societal, health, safety, legal and cultural
issues and the consequent responsibilities relevant to the professional
engineering practice.

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 7
& IoT
Programme Outcomes (POs)
• PO7. Environment and sustainability: Understand the impact of the
professional engineering solutions in societal and environmental
contexts, and demonstrate the knowledge of, and need for sustainable
development.
• PO8. Ethics: Apply ethical principles and commit to professional
ethics and responsibilities and norms of the engineering practice.
• PO9. Individual and team work: Function effectively as an individual,
and as a member or leader in diverse teams, and in multidisciplinary
settings.
• PO10. Communication: Communicate effectively on complex
engineering activities with the engineering community and with society
at large, such as, being able to comprehend and write effective reports
and design documentation, make effective presentations, and give and
receive clear instructions.
20EC211- Embedded Systems
RAJASEKAR T, AP/ECE 8
& IoT
Programme Outcomes (POs)
• PO11. Project management and finance: Demonstrate knowledge and
understanding of the engineering and management principles and apply
these to one’s own work, as a member and leader in a team, to manage
projects and in multidisciplinary environments.
• PO12. Life-long learning: Recognize the need for, and have the
preparation and ability to engage in independent and life-long learning in
the broadest context of technological change.

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 9
& IoT
Course Outcomes:
• CO1: Explain the hardware architecture of embedded systems
and building and debugging tools for embedded software. PO1
• CO2: Summarize the strategies to test embedded memories and
MISRA secure coding standards. PO1, PO12
• CO3: Interpret the concepts and architecture of Embedded
Linux. PO1, PO3, PO12
• CO4: Explain real time embedded systems using the concepts of
RTOS. PO1, PO3, PO12
• CO5: Describe the concepts of Internet of Things and cloud
computing. PO1, PO12
• CO6: Develop an IoT system for real time applications. PO1,
PO10, PO11, PO12
20EC211- Embedded Systems
RAJASEKAR T, AP/ECE 10
& IoT
UNIT I
• ARCHITECTURE AND PROGRAMMING OF EMBEDDED
SYSTEMS
• R2-Overview of Embedded systems - Definitions and
Constraints- Design challenge - Embedded processor
technology –T1 - Embedded Program - Role of Infinite loop -
Compiling, Linking and locating -downloading and debugging
- Emulators and simulators processor - External peripherals -
Memory testing - Programming of Flash Memory-
• R3 - Guidelines for the use of the C language in critical
systems based on secure coding standard MISRA.

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 11
& IoT
UNIT II
• EMBEDDED LINUX
• T2 - Introduction - Advantages- Embedded Linux
Distributions - Architecture of Embedded Linux - Linux kernel
Architecture - User space - Linux start-up sequence -GNU
cross platform Tool chain - Device Driver: Introduction and
Types-Tracing and Profiling tools.

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 12
& IoT
UNIT III
• REAL TIME SYSTEMS
• Foreground/Background Systems -- Context Switching - Non-
Pre-emptive Kernel, Pre-emptive Kernel - Scheduler -
Scheduling Re-entrancy - Priority Inversion - Assigning Task
Priorities - Priority Inheritance - Mutual Exclusion -
Semaphores - Deadlock - Synchronization - Event Flags - Inter
Task Communications - Message Mailboxes - Message
Queues - Interrupts - Clock Tick - Memory Requirements.

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 13
& IoT
UNIT IV
• INTERNET OF THINGS
• T3 - Introduction to IOT, Physical Design of IOT, Logical
Design of IOT, IOT Enabling Technologies-IOT and M2M--
Essential Characteristics of Cloud Computing - Service
Models - Deployment Models.
• Case Study: Air Quality Monitoring System and Data Logger-
Landslide Detection and Disaster Management- Smart
Motion Detector.

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 14
& IoT
TEXT BOOKS
1. Michael Barr, "Programming Embedded Systems in C and C++", Oreilly, 2003.
2. Raghavan P., Amol Lad, Sriram Neelakandan, "Embedded Linux System Design and
Development", Tailor & Francis Group, 2006.
3. Vijay Madisetti, Arshdeep Bahga, "Internet of Things (A Hands-on Approach), Universities
Press, 2015
REFERENCES
1. Jean J. Labrosse, "μC/OS-III, The Real-Time Kernel", Micrium Press, 2009.
2. Frank Vahid and Tony Givargis, "Embedded System Design: A Unified Hardware/
Software Introduction", John Wiley, 2006.
3. MISRA C, "Guidelines for the use of the C language in critical systems", MIRA Limited,
Warwickshire, UK, 2004
WEB REFERENCES
1. https://micrium.atlassian.net/wiki/spaces/osiidoc/overview
2. https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.500-322.pdf
20EC211- Embedded Systems
RAJASEKAR T, AP/ECE 15
& IoT
Overview of Embedded Systems

• Definition:
– Embedded systems are specialized computer systems
designed to perform specific tasks or functions within larger
systems or devices.
– They are often dedicated to a particular function and have
constraints on size, power consumption, and performance.
– Processor+ Special hardware+ Embedded software
– Special hardware-Application specific
– Firmware-Executed in the processor

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 16
& IoT
Embedded systems Vs General
computing
General Computing
Embedded Systems
Designed for specific General-purpose computing for
Purpose
tasks or functions various applications
Often required for timely
Real-time Real-time operation may not be a
and deterministic
Operation primary concern
responses
Compact and often Can vary in size, from desktops to
Size
small in size server clusters

Power Optimized for low Power consumption can vary


Consumption power consumption depending on the system

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 17
& IoT
Contd.,
Resource Limited resources (processing More abundant resources
Constraints power, memory, energy) available for use

Integrated within larger systems Stand-alone or networked


Integration
or devices computing systems
Can use higher-level
Software Requires low-level programming
programming languages and
Development and optimization
frameworks

Smartphones, automotive
Personal computers, servers,
Examples systems, medical devices,
laptops, workstations
industrial control systems

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 18
& IoT
Characteristics of Embedded
Systems
• Real-time operation:
– Embedded systems often need to respond to events or
stimuli within specific time constraints.
– They are designed to provide timely and deterministic
responses.
• Resource-constrained:
– Embedded systems have limited resources, such as
processing power, memory, and energy.
– Optimization is crucial to meet the requirements within
these constraints.

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 19
& IoT
Contd.,
• Specific functionality:
– Embedded systems are built for specific tasks or
functions, such as controlling machinery, monitoring
systems, or processing data.
• Integration:
– Embedded systems are typically integrated into larger
systems or devices, working in conjunction with other
hardware and software components.

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 20
& IoT
Contd.,
• Examples of Embedded Systems:
– Smartphones, tablets, and wearables
– Automotive systems (engine control, infotainment)
– Home appliances (refrigerators, washing machines)
– Medical devices (pacemakers, insulin pumps)
– Industrial control systems
– Aerospace and defense systems

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 21
& IoT
Design challenge – optimizing design
metrics
• A design metric is a measurable feature of a system’s
implementation.
• Unit cost: the monetary cost of manufacturing each copy of
the system, excluding NRE cost.
• NRE cost (Non-Recurring Engineering cost): The monetary
cost of designing the system.
• Size: the physical space required by the system, often
measured in bytes for software, and gates or transistors for
hardware.

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 22
& IoT
Contd..
• Performance: the execution time or throughput of the
system.
• Power: the amount of power consumed by the system,
which determines the lifetime of a battery, or the cooling
requirements of the IC, since more power means more heat.
• Flexibility: the ability to change the functionality of the
system without incurring heavy NRE cost. Software is
typically considered very flexible.
• Time-to-market: The amount of time required to design and
manufacture the system to the point the system can be sold
to customers.

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 23
& IoT
Contd..
• Time-to-prototype: The amount of time to build a working
version of the system, but can be used to verify the system’s
usefulness and correctness and to refine the system's
functionality.
• Correctness: Can check the functionality throughout the
process of designing the system.

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 24
& IoT
Contd..
• Safety: the probability that the system will not cause harm.
• Choice of Hardware - (Performance deadline &Manufacturing
cost)
• Deadlines-Speed-clock plus memory
• Power Consumption: Slow down non critical parts
• Upgradability: Software Up gradation
• Reliability: Safety critical systems
• Complex Testing: Run real machine, timing of data is req.)
• Limited Observability and Controllability (no keyboard & screens,
force values on buses)
• Restricted Development environment(debug programs run on
PC)
20EC211- Embedded Systems
RAJASEKAR T, AP/ECE 25
& IoT
Types of Embedded Systems

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 26
& IoT
Contd.
• Real-time systems are those which give a quick response to
critical situations.
• Used in military, medical and industrial applications.
• Better hardware is used in these systems to avoid failure in
performance.
• Real time embedded systems are classified into two types
such as soft and hard real time systems.

20EC211- Embedded Systems & IoT RAJASEKAR T, AP/ECE 27


Contd.
• Stand alone embedded systems do not require a host
system like a computer, it works by itself.

• It takes the input from the input ports either analog or digital
and processes, calculates and converts the data and gives
the resulting data through the connected device-Which
either controls, drives and displays the connected devices.

• Examples: mp3 players, digital cameras, video game


consoles, microwave ovens and temperature measurement
systems.

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 28
& IoT
Contd.
• Networked embedded systems are those systems which are
connected to the network It can be either a local area
network (LAN) or a wide area network (WAN).
• Example for the LAN networked embedded system is a home
security system wherein all sensors are connected and run
on the protocol TCP/IP
• Mobile embedded systems are used in portable embedded
devices like cell phones, mobiles, digital cameras, mp3
players and personal digital assistants, etc. Mobile
embedded systems are limited in resources including
memory.

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 29
& IoT
Contd.
• Small-scale embedded systems consist of 8-16
bit microcontroller(E.g.PIC microcontroller ).
• Little hardware and software complexity
• Programming tools: Editor, Assembler and Cross Assembler
• The need to limit power dissipation when system is running
continuously.
• Medium scale embedded systems use 16 or 32 bit
microcontroller, RISCs or DSPs.
• Both hardware and software complexity.
• Programming tools: RTOS, Source code Engineering Tool,
Simulator, Debugger and Integrated Development
Environment (IDE).
20EC211- Embedded Systems
RAJASEKAR T, AP/ECE 30
& IoT
Contd.
• Sophisticated embedded systems have enormous hardware
and software complexities, that may need ASIPs, IPs, PLAs,
scalable or configurable processors.
• Used for cutting-edge applications that need hardware and
software Co-design and components which have to
assemble in the final system.
• Programming Tools: A compiler or retargetable compiler
(designed to be relatively easy to modify to generate code
for different µp) might have to be developed for this.

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 31
& IoT
Components of Embedded
Systems
Hardware Components:
Microcontrollers:
– Central processing unit (CPU) integrated with memory,
peripherals, and interfaces.
– Provides processing power and controls the system's
operation.
Sensors and Actuators:
– Sensors gather data from the environment (temperature,
pressure, motion, etc.).
– Actuators perform actions based on the system's output
(motor control, display, etc.).
20EC211- Embedded Systems
RAJASEKAR T, AP/ECE 32
& IoT
Contd.,
Memory:
– ROM (Read-Only Memory): Stores firmware or
permanent data.
– RAM (Random Access Memory): Provides temporary
storage for program instructions and data.
Software Components:
Firmware:
– Software permanently stored in ROM, responsible for
booting the system and providing low-level control.

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 33
& IoT
Contd.,
Operating System (OS):
– Manages hardware resources, provides services, and enables
software development.
Application Software:
– Implements the specific functionality of the embedded system.
– Can include control algorithms, user interfaces, communication
protocols, etc.
Development Tools:
– Integrated Development Environments (IDEs) for writing, compiling,
and debugging code.
– Simulation tools for testing and validating embedded systems before
deployment.
20EC211- Embedded Systems
RAJASEKAR T, AP/ECE 34
& IoT
Contd.,
Challenges in Embedded System Development:

• Real-time constraints and timing issues.


• Power optimization and energy efficiency.
• Safety and security considerations.
• Hardware-software co-design and integration.
• Testing, debugging, and maintenance.

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 35
& IoT
Embedded System Components

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 36
& IoT
Embedded processor technology

• General-purpose processors – software


– The designer of a general-purpose processor builds a
device suitable for a variety of applications, to maximize
the number of devices sold.
– Design-metric benefits:
• Design time and NRE cost are low
• Flexibility is high
• Low Unit cost
• Fast Performance

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 37
& IoT
Single-purpose processors -- hardware

• A single-purpose processor is a digital circuit designed to


execute exactly one program.
• Eg., Digital camera.
• Design metrics benefits and drawbacks:
• Performance may be fast, size and power may be small
• Unit-cost may be low for large quantities, while design time
and NRE costs may be high, flexibility is low
• Unit cost may be high for small quantities, and performance
may not match general-purpose processors for some
applications.

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 38
& IoT
Application-specific processors

• ASIP - application-specific instruction-set processor.


• Eg., Digital-signal processing, telecommunications,
embedded control

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 39
& IoT
20EC211- Embedded Systems
RAJASEKAR T, AP/ECE 40
& IoT
Embedded Program
/**********************************************************************
* Function: main()
* Description: Blink the green LED once a second.
* Notes: This outer loop is hardware-independent. However it depends on two hardware-
dependent functions.
* Returns: This routine contains an infinite loop.
*********************************************************************/
void
main(void)
{ while (1)
{
toggleLed(LED_GREEN); /* Change the state of the LED. */
delay(500); /* Pause for 500 milliseconds. */
}
} /* main() */

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 41
& IoT
toggleLed
• In the case of the Arcom board has two LEDs: one red and one
green.
• The state of each LED is controlled by a bit in a register called the
Port 2 I/O Latch Register (P2LTCH, for short).
• The eight bits in the P2LTCH register is associated with the voltage
on one of the I/O pins.
• For example, bit 6 controls the voltage going to the green LED:
• #define LED_GREEN 0x40 /* The green LED is controlled by bit 6.
*/
• By modifying this bit, it is possible to change the voltage on the
external pin and, thus, the state of the green LED.
20EC211- Embedded Systems
RAJASEKAR T, AP/ECE 42
& IoT
toggleLed

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 43
& IoT
#define P2LTCH 0xFF5E /* The offset of the P2LTCH register. */
/*********************************************************
* Function: toggleLed()
* Description: Toggle the state of one or both LEDs.
* Notes: This function is specific to Arcom's Target188EB board.
* Returns: None defined.
************************************************************/
Void toggleLed(unsigned char ledMask)
{
asm {
mov dx, P2LTCH /* Load the address of the register. */
in al, dx /* Read the contents of the register. */
mov ah, ledMask /* Move the ledMask into a register. */
xor al, ah /* Toggle the requested bits. */
out dx, al /* Write the new register contents. */
};
} /* toggleLed() */
20EC211- Embedded Systems
RAJASEKAR T, AP/ECE 44
& IoT
delay
• To implement a half-second (500 ms) delay between LED
toggles.
• This is done by busy-waiting within the delay routine.
• This routine accepts the length of the requested delay, in
milliseconds, as its only parameter.
• It then multiplies that number by the constant
CYCLES_PER_MS to obtain the total number of while-loop
iterations required to delay for the requested time period.

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 45
& IoT
delay
/**********************************************************
* Function: delay()
* Description: Busy-wait for the requested number of milliseconds.
* Notes: The number of decrement-and-test cycles per millisecond was determined
through trial and error. This value is dependent upon the processor type and speed.
* Returns: None defined.
***********************************************************/
Void delay(unsigned int nMilliseconds)
{
#define CYCLES_PER_MS 260 /* Number of decrement-and-test cycles. */
unsigned long nCycles = nMilliseconds * CYCLES_PER_MS;
while (nCycles--);
} /* delay() */

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 46
& IoT
Role of Infinite Loop
• Definition:
• An infinite loop is a programming construct that
continuously executes a sequence of instructions without an
exit condition.
• It repeats indefinitely until an external event or action breaks
the loop.

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 47
& IoT
Importance of Infinite Loops
• Continuous Execution:
– Embedded systems often require constant monitoring,
sensing, or controlling of devices or processes.
– An infinite loop ensures that the system remains active
and responsive at all times.
• Real-Time Operation:
– Many embedded systems need to respond to events or
stimuli in real-time.
– An infinite loop allows the system to continuously check
for and react to these events without delay.

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 48
& IoT
• Task Scheduling:

• Embedded systems often involve multiple tasks or processes


running concurrently.
• An infinite loop can serve as the central control mechanism
for managing task scheduling and execution.

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 49
& IoT
Contd.,
• Example of Infinite Loop - Temperature Monitoring
System
• Benefits of Infinite Loop in this Example:
– The infinite loop ensures that the monitoring and control
process remains active and responsive.
– Real-time adjustments can be made without delay,
maintaining the desired temperature range.
– The loop continuously runs, enabling the system to
monitor and respond to changes efficiently.

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 50
& IoT
Embedded Software Development Process

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 51
& IoT
Contd.,

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 52
& IoT
Compiling
• The job of a compiler is mainly to translate programs written
in some human-readable language into an equivalent set of
opcodes for a particular processor. -cross-compiler
• GNU C compiler-AVR, Intel x86, MIPS, PowerPC, ARM, and
SPARC.
• object file-specially formatted binary file that contains the
set of instructions and data-large, flexible data structure.

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 53
& IoT
Contd.
• Common Object File Format (COFF) or Executable and
Linkable Format (ELF)
• Most object files begin with a header that describes the
sections that follow.
• In gcc all of the code blocks are collected into a section
called text
• initialized global variables (and their initial values) into a
section called data
• uninitialized global variables into a section called bss

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 54
& IoT
Linker
• Some of the internal variable and function references-
unresolved.
• Combine these object files and, in the process, to resolve all
of the unresolved symbols
• All of the code from all of the input object files will be in
the text section of the new file, and all of the initialized and
uninitialized variables will reside in the
new data and bss sections

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 55
& IoT
Contd.
• Compiled startup code-need to be linked(libgloss)
• a small block of assembly language code that prepares the
way for the execution of software written in a high-level
language
• Disable all interrupts.
• Copy any initialized data from ROM to RAM.
• Zero the uninitialized data area.
• Allocate space for and initialize the stack.
• Initialize the processor’s stack pointer.
• Call main.

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 56
& IoT
Locating
• The tool that performs the conversion from relocatable
program to executable binary image is called a locator.
• Information about the memory on the target board-input
• Assign physical memory addresses to each of the code and
data sections
• In the case of the GNU tools, this feature is built into the
linker (ld) -memory information can be passed to it in the
form of a linker script(http://www.gnu.org.).

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 57
& IoT
Emulators
• An in-circuit emulator (ICE) allows you to examine the state
of the processor on which that program is running.
• ICE actually takes the place of—or emulates—the processor
on your target board.
• It is itself an embedded system, with its own copy of the
target processor, RAM, ROM, and its own embedded
software.
• As a result, in-circuit emulators are usually pretty
expensive— often more expensive than the target
hardware.

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 58
& IoT
ROM Emulators
• A ROM emulator is a device that emulates a read-only
memory device.
• Like an ICE, it is an embedded system that connects to the
target and communicates with the host.
• However, this time the target connection is via a ROM
socket.
• To the embedded processor, it looks like any other read-only
memory device.

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 59
& IoT
Simulators
• A simulator is a completely host-based program that
simulates the functionality and instruction set of the target

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 60
& IoT
Emulator Vs Simulator
Emulator Simulator
Emulates the behavior of the Simulates the behavior of the
Definition
target system target system
Replicate the hardware and Mimic the behavior and
Purpose software environment of the characteristics of the target
target system system
Can be faster or slower than the
Execution Slower compared to the
actual hardware, depending on
Speed actual hardware
the simulation model

Highly accurate May have limitations and


Accuracy representation of the target approximation due to simulation
system models and algorithms

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 61
& IoT
Contd.,
Can interact with the actual Limited or no interaction with
Hardware hardware, allowing for the actual hardware, often used
Interaction testing and debugging of for higher-level testing and
low-level code validation
Generally more complex to
Easier to set up and configure, as
Complexity set up and configure due to
it focuses on software behavior
hardware emulation

Often used during software Utilized throughout the


Development
development and testing development lifecycle, including
Stage
stages design, development, and testing
Real-World Emulates real-world Simulates real-world scenarios
Testing scenarios and interactions and interactions
MATLAB/Simulink, NS-3, Simics,
Examples Android Emulator, QEMU
20EC211- Embedded Systems
RAJASEKAR T, AP/ECE
VirtualBox 62
& IoT
External Peripherals
• These are the hardware devices that reside outside the
processor chip and communicate with it by way of interrupts
and I/O or memory-mapped registers.
• LCD or keyboard controllers, A/D converters, network
interface chips, or custom ASICs (Application-Specific
Generated Circuits).
• Device Driver - a collection of software routines that control
the operation of the peripheral and isolate the application
software from the details of that particular hardware device.

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 63
& IoT
Memory
• Types of Memory:

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 64
& IoT
Memory Device Characteristics

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 65
& IoT
Memory Testing
• The purpose of a memory test is to confirm that each storage
location in a memory device is working.
• Common Memory Problems:
– circuit board problems
– Problems with the wiring between the processor and memory device.
– Missing memory chips
– Improperly inserted memory chips

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 66
& IoT
Memory Testing
• Electrical wiring problems:
• An electrical wiring problem could be caused by an error in
design or production of the board or as the result of damage
received after manufacture.
• Each of the wires that connect the memory device to the
processor is one of three types: an address line, a data line,
or a control line.
• The address and data lines are used to select the memory
location and to transfer the data, respectively.
• The control lines tell thread or write e memory device
whether the processor wants to the location.

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 67
& IoT
Memory Testing
• Possible wiring problems

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 68
& IoT
Contd.,
• Missing memory chips:
– Unfortunately, because of the capacitive nature of unconnected electrical
wires, some memory tests will not detect this problem.
• Improperly inserted chips:
– If a memory chip is present but improperly inserted in its socket, the
system will usually behave as though there is a wiring problem or a missing
chip.
– Some of the pins on the memory chip will either not be connected to the
socket at all or will be connected at the wrong place.
– These pins will be part of the data bus, address bus, or control wiring.
– So to test for wiring problems and missing chips, any improperly inserted
chips will be detected automatically.

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 69
& IoT
Data bus test
– to test that is to write all possible data values and verify that the memory
device stores each one successfully.
– A faster method is to test the bus one bit at a time. The data bus passes
the test if each data bit can be set to 0 and 1, independently of the other
data bits.
– Consecutive Data Values for the Walking 1’s Test
• 00000001
• 00000010
• 00000100
• 00001000
• 00010000
• 00100000
• 01000000
• 10000000

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 70
& IoT
Function: memTestDataBus()
memTestDataBus(volatile datum * address)
{ datum pattern; /* Perform a walking 1's test at the given address.*/
for (pattern = 1; pattern != 0; pattern <<= 1)
{ /* Write the test pattern*/
*address = pattern; /* Read it back (immediately is okay for this test)*/
if (*address != pattern)
{
return (pattern);
}
}
return (0);
} /* memTestDataBus() */

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 71
& IoT
Address bus test
• Address bus problems lead to overlapping memory
locations.
• To confirm that no two memory locations overlap, you
should first write some initial data value at each power-of-
two offset within the device.
• Then write a new value—an inverted copy of the initial
value is a good choice—to the first test offset, and verify that
the initial data value is still stored at every other power-of
two offset.
• If you find a location (other than the one just written) that
contains the new data value, you have found a problem with
the current address bit.
20EC211- Embedded Systems
RAJASEKAR T, AP/ECE 72
& IoT
Function: memTestAddressBus()
memTestAddressBus(volatile datum * baseAddress, unsigned long nBytes)
{
unsigned long addressMask = (nBytes - 1);
unsigned long offset;
unsigned long testOffset;
datum pattern = (datum) 0xAAAAAAAA;
datum antipattern = (datun) 0x55555555;
/*
* Write the default pattern at each of the power-of-two offsets..
*/
for (offset = sizeof(datum); (offset & addressMask) != 0; offset <<= 1)
{aseAddress[offset] = pattern;
}
20EC211- Embedded Systems
RAJASEKAR T, AP/ECE 73
& IoT
Contd.,
/*
* Check for address bits stuck high.
*/
testOffset = 0;
baseAddress[testOffset] = antipattern;
for (offset = sizeof(datum); (offset & addressMask) != 0; offset <<= 1)
{
if (baseAddress[offset] != pattern)
{
return ((datum *) &baseAddress[offset]);
}
}
baseAddress[testOffset] = pattern;
20EC211- Embedded Systems
RAJASEKAR T, AP/ECE 74
& IoT
Contd.,
/* Check for address bits stuck low or shorted*/
for (testOffset = sizeof(datum); (testOffset & addressMask) != 0;
testOffset <<= 1)
{
baseAddress[testOffset] = antipattern;
for (offset = sizeof(datum); (offset & addressMask) != 0;
offset <<= 1)
{ if ((baseAddress[offset] != pattern) && (offset != testOffset))
{ return ((datum *) &baseAddress[testOffset]);
}}
baseAddress[testOffset] = pattern;
}
return (NULL);
} /* memTestAddressBus() */
20EC211- Embedded Systems
RAJASEKAR T, AP/ECE 75
& IoT
Device test
• Data Values for an Increment Test

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 76
& IoT
Function: memTestDevice()
memTestDevice(volatile datum * baseAddress, unsigned long nBytes)
{
unsigned long offset;
unsigned long nWords = nBytes / sizeof(datum);
datum pattern;
datum antipattern;
/*
* Fill memory with a known pattern.
*/
for (pattern = 1, offset = 0; offset < nWords; pattern++, offset++)
{
baseAddress[offset] = pattern;
}
20EC211- Embedded Systems
RAJASEKAR T, AP/ECE 77
& IoT
Contd.,
/*
* Check each location and invert it for the second pass.
*/
for (pattern = 1, offset = 0; offset < nWords; pattern++, offset++)
{
if (baseAddress[offset] != pattern)
{
return ((datum *) &baseAddress[offset]);
}
antipattern = ~pattern;
baseAddress[offset] = antipattern;
}

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 78
& IoT
Contd.,
/* Check each location for the inverted pattern and zero it*/
for (pattern = 1, offset = 0; offset < nWords; pattern++, offset++)
{
antipattern = ~pattern;
if (baseAddress[offset] != antipattern)
{
return ((datum *) &baseAddress[offset]);
}
baseAddress[offset] = 0;
}
return (NULL);
} /* memTestDevice() */

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 79
& IoT
Putting it all together
• Test 64kb of SRAM:
• Memory test routines returns a nonzero (or non-NULL)
value, immediately turn on the red LED to visually indicate
the error.
• Three tests have completed successfully, we will turn on the
green LED

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 80
& IoT
20EC211- Embedded Systems
RAJASEKAR T, AP/ECE 81
& IoT
Programming of Flash Memory
• Reading from Flash memory is fast and easy, as it should be.
In fact, reading data from a Flash is not all that different from
reading from any other memory device.
• The processor simply provides the address, and the memory
device returns the data stored at that location

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 82
& IoT
Contd.,
• Writing data to a Flash is harder.
• Three factors make writes difficult.
• First, each memory location must be erased before it can be
rewritten.
• If the old data is not erased, the result of the write operation
will be some logical combination of the old and new values.
• The second factor is in flash memory only one sector, or
block, of the device can be erased at a time; it is impossible
to erase a single byte.
• The size of an individual sector varies by device, but it is
usually on the order of several thousand bytes.
20EC211- Embedded Systems
RAJASEKAR T, AP/ECE 83
& IoT
Contd.,
• Finally, the process of erasing the old data and writing the
new varies from one manufacturer to another and is usually
rather complicated.
• These device programming interfaces are so awkward that it
is usually best to add a layer of software to make the Flash
memory easier to use called the Flash driver.

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 84
& IoT
Flash Drivers
• The purpose of the Flash driver is to hide the details of a
specific chip from the rest of the software.
• This driver should present a simple application programming
interface (API) consisting of the erase and write operations.
• Parts of the application software that need to modify data
stored in Flash memory simply call the driver to handle the
details.
• This driver contains just two functions: flashErase and
flashWrite.

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 85
& IoT
MISRA-C and CERT coding
standards
Introduction
• MISRA- The Motor Industry Software Reliability Association
• Every rule is classified as being either “required” or
“advisory”
• Required rules: These are mandatory requirements placed
on the programmer
• Advisory rules: These are requirements placed on the
programmer that should normally be followed

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 87
& IoT
Presentation of rules
• Rule <number> (<category>): <requirement text>
<number> Every rule has a unique number. This number
consists of a rule group prefix and a group member suffix.
<category> is one of “required” or “advisory”,
<requirement text> The rule itself.
• <source ref> This indicates the primary source(s) where a
rule originates from one or more published sources these are
indicated in square brackets after the rule.
Rule 1.1 (req) [IEC 61508 Part 3]

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 88
& IoT
typedef’d types
• char_t plain 8 bit character
• uint8_t unsigned 8 bit integer
• uint16_t unsigned 16 bit integer
• uint32_t unsigned 32 bit integer
• int8_t signed 8 bit integer
• int16_t signed 16 bit integer
• int32_t signed 32 bit integer
• float32_t 32 bit floating-point
• float64_t 64 bit floating-point
20EC211- Embedded Systems
RAJASEKAR T, AP/ECE 89
& IoT
Environment

Rule 1.1 (req) All code shall conform to ISO/IEC 9899:1990


“Programming languages — C”, amended and corrected by
ISO/IEC 9899/COR1:1995, ISO/IEC 9899/ AMD1:1995, and
ISO/IEC 9899/COR2:1996

Rule 1.2 (req) No reliance shall be placed on undefined or


unspecified behavior.

Rule 1.3 (req) Multiple compilers and/or languages shall only be


used if there is a common defined interface standard for
object code to which the languages/compilers/ assemblers
conform.
e.g. ELF (Extensible Linking Format) format - Executable and Linkable
Format

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 90
& IoT
Contd.
Rule 1.4 (req) The compiler/linker shall be checked to
ensure that 31 character significance and case
sensitivity are supported for external identifiers.
ANSI allows six significant characters in an
external identifier's name and 31 for names of
internal (within a function) identifiers

Rule 1.5 (adv) Floating-point implementations should


comply with a defined floating-point standard.
(ANSI/IEEE Std 754)

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 91
& IoT
Language extensions
• Rule 2.1 (req) Assembly language shall be encapsulated and
isolated in (a) assembler functions, (b) C functions or (c) macros.

• Rule 2.2 (req) Source code shall only use /* … */ style comments.

• Rule 2.3 (req) The character sequence /* shall not be used within a
comment.
The double-slash comments (//) expire at the end of the
line. Slash-star (/*) comments are in effect until a closing
comment mark (*/)

• Rule 2.4 (adv) Sections of code should not be “commented out”.

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 92
& IoT
Inline assembly code in C
void main() {
int a = 3, b = 3, c;
asm {
mov ax,a
mov bx,a
add ax,bx
mov c,ax
}
printf("%d",c);
}
#define NOP asm(" NOP")
20EC211- Embedded Systems
RAJASEKAR T, AP/ECE 93
& IoT
Character sets
• Rule 4.1 (req) Only those escape sequences that are defined in the ISO C
standard shall be used.
• All “hexadecimal-escape-sequences” are prohibited.
• The “octal-escape-sequences” other than \0 are also prohibited
• Rule 4.2 (req) Trigraphs shall not be used.
Trigraphs are denoted by a sequence of 2 question marks followed by a
specified third character
(e.g. ??- represents a “~” (tilde) character and ??) represents a “]”).
They can cause accidental confusion with other uses of two question marks.
For example the string
"(Date should be in the form ??-??-??)"
would not behave as expected, actually being interpreted by the compiler as
"(Date should be in the form ~~]"
20EC211- Embedded Systems
RAJASEKAR T, AP/ECE 94
& IoT
Identifiers
• Rule 5.1 (required):Identifiers (internal and external)
shall not rely on the significance of more than 31
characters.(internal identifiers to be distinct in the first 31
characters to guarantee code portability)
• Rule 5.2 (required):Identifiers in an inner scope shall
not use the same name as an identifier in an outer
scope, and therefore hide that identifier.
int16_t i;
{
int16_t i;
i = 3;
} 20EC211- Embedded Systems RAJASEKAR T, AP/ECE 95
& IoT
Contd.
Rule 5.3 (required):A typedef name shall be a unique
identifier
{
typedef unsigned char uint8_t;
}
{
unsigned char uint8_t; /* Not compliant - reuse of
uint8_t */
}

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 96
& IoT
Contd.
Rule 5.4 (required):A tag name shall be a unique
identifier.

struct stag { uint16_t a; uint16_t b; };


void foo(void)
{
struct stag { uint16_t a; }; /* Not compliant - tag stag
redefined */
}

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 97
& IoT
Contd.
Rule 5.5 (advisory):No object or function identifier with static
storage duration should be reused
• Regardless of scope, no identifier with static storage
duration should be re-used across any source files in the
system.
• This includes objects or functions with external linkage and
any objects or functions with the static storage class
specifier.
• One example of this confusion is having an identifier name
with internal linkage in one file and the same identifier name
with external linkage in another file.

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 98
& IoT
Contd.
Rule 5.7 (advisory):No identifier name should be reused
struct air_speed
{
uint16_t speed; /* knots */
} * x;

struct gnd_speed
{
uint16_t speed; /* mph */
/* Not Compliant - speed is in different units */
} * y;

x->speed = y->speed;

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 99
& IoT
Types
• Rule 6.1 (required):The plain char type shall be used
only for the storage and use of character values.

• Rule 6.2 (required):signed and unsigned char type shall


be used only for the storage and use of numeric values.

• Rule 6.3 (advisory):typedefs that indicate size and


signedness should be used in place of the basic
numerical types
 typedef char char_t;
 typedef signed char int8_t;

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 100
& IoT
Contd.
• Rule 6.4 (required):Bit fields shall only be defined to
be of type unsigned int or signed int
E.g. unsigned int d: 5;

• Rule 6.5 (required):Bit fields of signed type shall be


at least 2 bits long.

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 101
& IoT
Constants
• Rule 7.1 (required):Octal constants (other than
zero) and octal escape sequences shall not be used.
code[1] = 109; /* equivalent to decimal 109 */
code[2] = 100; /* equivalent to decimal 100 */
code[3] = 052; /* equivalent to decimal 42 */
code[4] = 071; /* equivalent to decimal 57 */

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 102
& IoT
Declarations and definitions
• Rule 8.1 (required):Functions shall have prototype
declarations and the prototype shall be visible at
both the function definition and call.

• Rule 8.2 (required): Whenever an object or function


is declared or defined, its type shall be explicitly
stated.
• static int16_t foo(void);

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 103
& IoT
Contd.
• Rule 8.3 (required): For each function parameter
the type given in the declaration and definition shall
be identical, and the return types shall also be
identical.

• Rule 8.11 (required): The static storage class


specifier shall be used in definitions and
declarations of objects and functions that have
internal linkage.

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 104
& IoT
example
#include<stdio.h>
/* function prototype, also called function
declaration*/
float square ( float x );
float square ( float x ) /* function definition*/
{
float p ;
p=x*x;
return ( p ) ;
}
20EC211- Embedded Systems
RAJASEKAR T, AP/ECE 105
& IoT
Contd.
int main( )
{
float m, n ;
printf ( "\nEnter some number for finding square \n");
scanf ( "%f", &m ) ;
/* function call*/
n = square ( m ) ;
printf ( "\nSquare of the given number %f is %f",m,n );
}

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 106
& IoT
Contd.
• Rule 8.12 (required): When an array is declared
with external linkage, its size shall be stated
explicitly or defined implicitly by initialisation.
 int array2[ ] = { 0, 10, 15 };
 extern int array2[ ];
 int array1[ 10 ];

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 107
& IoT
Initialization
• Rule 9.1 (required): All automatic variables shall have
been assigned a value before being used.
• Rule 9.2 (required): Braces shall be used to indicate
and match the structure in the non-zero initialization of
arrays and structures.
• int16_t y[3][2] = { { 1, 2 }, { 3, 4 }, { 5, 6 } };
• int16_t y[3][2] = { 1, 2, 3, 4, 5, 6 };non-complaint

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 108
& IoT
Expressions
• Rule 12.1 (advisory): Limited dependence
should be placed on C’s operator precedence
rules in expressions.
• x = a + b; /* acceptable */
• x = (a + b); /* () not required
• Do not add too many parentheses so as to clutter
the code and make it unreadable

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 109
& IoT
Contd.
• Rule 12.3 (required): The sizeof operator shall not
be used on expressions that contain side effects.
 int32_t i;
 int32_t j;
 j = sizeof(i = 1234);

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 110
& IoT
Contd.
• Rule 12.4 (required): The right-hand operand of a
logical && or || operator shall not contain side effects.
 if ( ishigh && ( x == i++ ) )
• if ( ishigh && ( x == f(x) ) ) /* Only acceptable if f(x) is
known to have no side effects */

• Rule 12.7 (required): Bitwise operators shall not be


applied to operands whose underlying type is signed.
• (~, <<, <<=, >>, >>=, &, &=, ^, ^=, | and |=) not
meaningful for signed integers

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 111
& IoT
Contd.
• Rule 12.13 (advisory): The increment (++) and
decrement (--) operators should not be mixed with
other operators in an expression.
u8a = ++u8b + u8c--;
• The following sequence is clearer and
therefore safer:
++u8b;
u8a = u8b + u8c;
u8c--;

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 112
& IoT
Control statement expressions
• Rule 13.1 (required): Assignment operators shall
not be used in expressions that yield a Boolean
value.
x = y;
if ( x != 0 ) /* complaint*/
{
foo();
}

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 113
& IoT
Contd.
if ( ( x = y ) != 0 ) /* Boolean by context */
{
foo();
}

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 114
& IoT
Contd.
• Rule 13.3 (required): Floating-point expressions
shall not be tested for equality or inequality.
 float32_t x, y;
 /* some calculations in here */
 if ( x == y ) /* not compliant */
• Rule 13.4 (required): The controlling
expression of a for statement shall not
contain any objects of floating
type.(Rounding and truncation errors)
20EC211- Embedded Systems
RAJASEKAR T, AP/ECE 115
& IoT
Contd.
• Rule 13.6 (required): Numeric variables being
used within a for loop for iteration counting
shall not be modified in the body of the loop.
flag = 1;
for ( i = 0; (i < 5) && (flag == 1); i++ )
{
flag = 0; /* Compliant - allows early termination of
loop */
i = i + 3; /* Not compliant - altering the loop
counter */
}
20EC211- Embedded Systems
RAJASEKAR T, AP/ECE 116
& IoT
Control flow
• Rule 14.1 (required): There shall be no unreachable code. A
portion of code is unreachable if there is no control flow path from the relevant entry
point to that
• code.
switch (event)
{
case E_wakeup:
do_wakeup();
break; /* unconditional control transfer */
do_more(); /* Not compliant - unreachable code */
/* ... */
default:
/* ... */
break;
}

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 117
& IoT
Contd.
Rule 14.4 (required): The goto statement shall not be
used.
Rule 14.5 (required): The continue statement shall not
be used.
Rule 14.6 (required): For any iteration statement
there shall be at most one break statement used for
loop termination.

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 118
& IoT
Contd.
• Rule 14.9 (required): An if (expression) construct
shall be followed by a compound statement. The
else keyword shall be followed by either a
compound statement, or another if statement.

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 119
& IoT
Contd.
if ( test1 )
{
x = 1; /* Even a single statement must be in braces */
}
else if ( test2 )
{
x = 0; /* Single statement must be in braces */
}
else
x = 3; /* This was (incorrectly) not enclosed in braces */
y = 2;

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 120
& IoT
Contd.
• Rule 14.10 (required): All if … else if constructs shall
be terminated with an else clause.
if ( x < 0 )
{
log_error(3);
x = 0;
} /* else not needed */

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 121
& IoT
• This rule applies whenever an if statement is
followed by one or more else if statements;
the final else if shall be followed by an else
statement.
• In the case of a simple if statement then the
else statement need not be included.

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 122
& IoT
Contd.
if ( x < 0 )
{
log_error(3);
x = 0;
}
else if ( y < 0 )
{
x = 3;
}
else {
x=1;
}

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 123
& IoT
Switch statement
• Rule 15.5 (required): Every switch statement shall
have at least one case clause.
• Rule 15.4 (required): A switch expression shall not
represent a value that is effectively Boolean
switch (x == 0) /* not compliant - effectively Boolean */
{
• Rule 15.3 (required): The final clause of a switch
statement shall be the default clause.

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 124
& IoT
Functions
• Rule 16.1 (required): Functions shall not be defined
with a variable number of arguments
• Rule 16.2 (required): Functions shall not call
themselves, either directly or indirectly.
• Rule 16.3 (required): Identifiers shall be given for all
of the parameters in a function prototype
declaration

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 125
& IoT
Contd.
• Rule 16.5 (required): Functions with no parameters
shall be declared and defined with the parameter
list void.
void myfunc ( void );

• Rule 16.6 (required): The number of arguments


passed to a function shall match the number of
parameters.

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 126
& IoT
Contd.
• Rule 16.8 (required): All exit paths from a function
with non-void return type shall have an explicit
return statement with an expression.

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 127
& IoT
Pointers and arrays
• Rule 17.1 (required): Pointer arithmetic shall only
be applied to pointers that address an array or array
element.
• Rule 17.2 (required): Pointer subtraction shall only
be applied to pointers that address elements of the
same array.

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 128
& IoT
Contd.
• Rule 17.4 (required): Array indexing shall be
the only allowed form of pointer arithmetic.
void my_fn(uint8_t * p1, uint8_t p2[])
{
uint8_t index = 0U;
uint8_t * p3;
index ++;
index = index + 5U;
p3[index] = 0U;
20EC211- Embedded Systems
RAJASEKAR T, AP/ECE 129
& IoT
Structures and unions
• Rule 18.2 (required): An object shall not be
assigned to an overlapping object.
• Rule 18.3 (required) An area of memory shall not be
reused for unrelated purposes.
• Rule 18.4 (required): Unions shall not be used.

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 130
& IoT
Preprocessing directives
• Rule 19.1 (advisory): #include statements in a file
should only be preceded by other preprocessor
directives or comments.
• Rule 19.2 (advisory): Non-standard characters
should not occur in header file names in #include
directives.(', \, ", or /*)
• Rule 19.3 (required): The #include directive shall be
followed by either a <filename> or "filename"
sequence.

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 131
& IoT
Contd.
• Rule 19.5 (required): Macros shall not be #define’d
or #undef’d within a block.

• Rule 19.6 (required): #undef shall not be used.

• Rule 19.7 (advisory): A function should be used in


preference to a function-like macro.

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 132
& IoT
Standard libraries
• Rule 20.1 (required): Reserved identifiers, macros
and functions in the standard library, shall not be
defined, redefined or undefined.

• Rule 20.2 (required): The names of standard library


macros, objects and functions shall not be reused.
• functions provide a safer mechanism

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 133
& IoT
Contd.
• Rule 20.4 (required): Dynamic heap memory
allocation shall not be used.

• Rule 20.5 (required): The error indicator errno shall


not be used.

• Rule 20.10 (required): The library functions atof,


atoi and atol from library <stdlib.h> shall not be
used.

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 134
& IoT
Contd.
• Rule 20.11 (required): The library functions abort,
exit, getenv and system from library <stdlib.h> shall
not be used.

• Rule 20.12 (required): The time handling functions


of library <time.h> shall not be used. Includes time,
strftime(need to know exact implementation of the
compiler)

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 135
& IoT
CERT C Coding Standard

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 136
& IoT
CERT C Programming Language Secure
Coding Standard
• The goal of these rules and recommendations is
to develop safe, reliable, and secure systems
• Each rule and recommendation is given a unique
identifier within a standard-eg.PRE04-A
• A three letter mneumonic representing the
section of the standard
• A two digit numeric value in the range of 00-99

• The letter "A" or "C" to indicate whether the


coding practice is an advisory recommendation
or a compulsory rule
20EC211- Embedded Systems
RAJASEKAR T, AP/ECE 137
& IoT
Risk Assessment
• Each rule and recommendation in a secure
coding standard has an assigned priority.

• Priorities are assigned using a metric based


on Failure Mode, Effects, and Criticality
Analysis (FMECA)

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 138
& IoT
Contd.
• Severity - how serious are the consequences
of the rule being ignored
 1 = low (denial-of-service attack, abnormal
termination)
 2 = medium (data integrity violation, unintentional
information disclosure)
 3 = high (run arbitrary code)

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 139
& IoT
Contd.
• Likelihood - how likely is it that a flaw
introduced by ignoring the rule could lead to
an exploitable vulnerability ( a weakness
exploited by an attacker)
 1 = unlikely
 2 = probable
 3 = likely

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 140
& IoT
Contd.
• Remediation cost – how expensive is it to
comply with the rule
 1 = high (manual detection and correction)
 2 = medium (automatic detection / manual
correction)
 3 = low (automatic detection and correction)

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 141
& IoT
Contd.
• The three values are then multiplied together
for each rule.
• This product provides a measure that can be
used in prioritizing the application of the
rules.
• These products range from 1 to 27(1, 2, 3, 4,
6, 8, 9, 12, 18, and 27) .

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 142
& IoT
Priorities and Levels
High severity,
likely, L1 P12-P27
inexpensive to
repair flaws
L2 P6-P9

L3 P1-P4

Med severity, Low severity,


probable, med unlikely,
cost to repair expensive to
flaws repair flaws

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 143
& IoT
Contd.
• Each rule consists of a title, a description, and
noncompliant code examples and compliant solutions.
• The title is a concise description of the rule.
• The description specifies the normative requirements
of the rule.
• The noncompliant code examples are examples of
code that would constitute a violation of the rule.
• The accompanying compliant solutions demonstrate
equivalent code that does not violate the rule or any
other rules in this coding standard.

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 144
& IoT
Preprocessor (PRE)
• PRE31-C :- Avoid side effects in arguments to unsafe
macros .
• Never invoke an unsafe macro with arguments
containing an assignment, increment, decrement,
volatile access, input/output, or other expressions
with side effects.

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 145
& IoT
Noncompliant Code:
Validate that n is within the desired range
#define ABS(x) (((x) < 0) ? -(x) : (x))
void func(int n)
{
int m = ABS(++n);
}
m = (((++n) < 0) ? -(++n) : (++n));

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 146
& IoT
Compliant Solution
#define ABS(x) (((x) < 0) ? -(x) : (x))
void func(int n)
{
++n;
int m = ABS(n);
}

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 147
& IoT
Risk Assessment
• PRE31-C Low Unlikely Low P3 L3

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 148
& IoT
Contd.
• PRE32-C. Do not use preprocessor directives
in invocations of function-like macros

• The arguments to a macro must not include


preprocessor directives, such as #define,
#ifdef, and #include function like macros
• This rule also applies to the use of
preprocessor directives in arguments to a
function.
20EC211- Embedded Systems
RAJASEKAR T, AP/ECE 149
& IoT
Noncompliant Code Example
• Validate the source string; calculate size,.
#include <string.h>
void func(const char *src)
{
char *dest;
memcpy(dest, src,
#ifdef
PLATFORM1 12
#else
24
#endif );
);
20EC211- Embedded Systems
RAJASEKAR T, AP/ECE 150
& IoT
Compliant code
#include <string.h>
void func(const char *src)
{
char *dest;
#ifdef
PLATFORM1
memcpy(dest, src, 12);
#else
memcpy(dest, src, 24);
#endif
}
20EC211- Embedded Systems
RAJASEKAR T, AP/ECE 151
& IoT
Risk Assessment
• PRE32-C Low Unlikely Medium P2
L3

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 152
& IoT
Declarations and Initialization (DCL)
• DCL30-C. Declare objects with appropriate storage
durations
• Every object has a storage duration that determines
its lifetime. Do not attempt to access an object
outside of its lifetime
• Every object has a storage duration that determines
its lifetime: static and automatic

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 153
& IoT
Noncompliant Code Example (Differing
Storage Durations)
#include <stdio.h>
const char *p;
void dont_do_this(void)
{
const char str1[] = "This will change";
p = str1;
}
void innocuous(void)
{
printf("%s\n", p);
}

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 154
& IoT
Contd.
int main(void)
{
dont_do_this();
innocuous();
return 0;
}

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 155
& IoT
Compliant Solution (Same Storage
Durations)
void this_is_OK(void)
{
const char str1[] = "Everything OK";
const char *p = str1;
}

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 156
& IoT
Compliant Solution (Differing Storage
Durations)
const char *p;
void is_this_OK(void)
{
const char str1[] = "Everything OK?";
p = str1;
p = NULL;
}
p can be set to NULL before str1 is destroyed
20EC211- Embedded Systems
RAJASEKAR T, AP/ECE 157
& IoT
Noncompliant Code Example
char *init_array(void)
{
char array[10];
return array;
}
Some compilers generate a diagnostic message when a pointer to an
object with automatic storage duration is returned from a
function.

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 158
& IoT
Compliant Solution (Return Values)
#include <stddef.h>
void init_array(char *array, size_t len)
{
return;
}
int main(void)
{
char array[10];
init_array(array, sizeof(array) / sizeof(array[0]));
return 0;
}

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 159
& IoT
Contd.
• DCL30-C High Probable High P6 L2

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 160
& IoT
Contd.
• DCL31-C. Declare identifiers before using them
Noncompliant Code Example (Implicit int)
• C no longer allows the absence of type specifiers in
a declaration e.g extern foo;
Compliant Solution (Implicit int)
• extern int foo;

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 161
& IoT
Contd.
• Noncompliant Code Example (Implicit Function
Declaration)
• Implicit declaration of functions is not allowed;
every function must be explicitly declared before it
can be called

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 162
& IoT
Noncompliant code example
#include <stddef.h>
int main(void)
{
for (size_t i = 0; i < 100; ++i)
{
char *ptr = (char *)malloc(0x10000000);
*ptr = 'a';
}
return 0;
}

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 163
& IoT
Compliant Solution (Implicit Function
Declaration)
#include <stdlib.h>
int main(void)
{
for (size_t i = 0; i < 100; ++i)
{
char *ptr = (char *)malloc(0x10000000);
*ptr = 'a';
}
return 0;
}

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 164
& IoT
Noncompliant Code Example (Implicit
Return Type)
#include <limits.h>
#include <stdio.h>
foo(void)
{
return UINT_MAX;
}
int main(void)
{
long long int c = foo();
printf("%lld\n", c);
return 0;
}
Do not declare a function with an implicit return type UINT_MAX is
incorrectly converted to −1
20EC211- Embedded Systems
RAJASEKAR T, AP/ECE 165
& IoT
Compliant Solution (Implicit Return
Type)
#include <limits.h>
#include <stdio.h>
unsigned int foo(void)
{
return UINT_MAX;
}
int main(void)
{
long long int c = foo();
printf("%lld\n", c);
return 0;
}
20EC211-
& IoT
Embedded Systems
RAJASEKAR T, AP/ECE 166
Contd.
• DCL31-C Low Unlikely Low P3 L3

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 167
& IoT
DCL37-C. Do not declare or define a
reserved identifier
• All identifiers that begin with an underscore
and either an uppercase letter or another un-
derscore are always reserved for any use

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 168
& IoT
Noncompliant Code Example (Header
Guard)
#ifndef _MY_HEADER_H_
#define _MY_HEADER_H_
#endif

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 169
& IoT
Compliant Solution (Header Guard)

#ifndef MY_HEADER_H
#define MY_HEADER_H
#endif

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 170
& IoT
Noncompliant Code Example
#include <stddef.h>
static const size_t _max_limit = 1024;
size_t _limit = 100;
unsigned int getValue(unsigned int count)
{
return count < _limit ? count : _limit;
}

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 171
& IoT
Compliant Solution
#include <stddef.h>
static const size_t max_limit = 1024;
size_t limit = 100;
unsigned int getValue(unsigned int count)
{
return count < limit ? count : limit;
}

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 172
& IoT
DCL39-C. Avoid information leakage when
passing a structure across a trust boundary
• When a value is stored in an object of structure or
union type, including in a member object, the bytes
of the object representation that correspond to any
padding bytes take unspecified values.

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 173
& IoT
Noncompliant Code Example
Copies data from struct test to user space.
#include <string.h>
struct test
{
int a;
char b;
int c;
};
extern int copy_to_user(void *dest, void *src,
size_t size);

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 174
& IoT
Contd.
void do_stuff(void *usr_buf)
{
struct test arg = {.a = 1, .b = 2, .c = 3};
copy_to_user(usr_buf, &arg, sizeof(arg));
}
struct uart
{
unsigned baud : 3;
unsigned parity : 2;
unsigned unused : 2;
unsigned interrupt_enable : 1;
};

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 175
& IoT
Compliant Solution
#include <stddef.h>
#include <string.h>
struct test
{
int a;
char b;
int c;
};
20EC211- Embedded Systems
RAJASEKAR T, AP/ECE 176
& IoT
Contd.
extern int copy_to_user(void *dest, void *src,
size_t size);
void do_stuff(void *usr_buf)
{
struct test arg = {.a = 1, .b = 2, .c = 3};
unsigned char buf[sizeof(arg)];
size_t offset = 0;

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 177
& IoT
Contd.
memcpy(buf + offset, &arg.a, sizeof(arg.a));
offset += sizeof(arg.a);
memcpy(buf + offset, &arg.b, sizeof(arg.b));
offset += sizeof(arg.b);
memcpy(buf + offset, &arg.c, sizeof(arg.c));
offset += sizeof(arg.c);
copy_to_user(usr_buf, buf, offset
}
20EC211- Embedded Systems
RAJASEKAR T, AP/ECE 178
& IoT
Compliant Solution (Structure
Packing—GCC)
#include <stddef.h>
struct test
{ int a;
char b;
int c;
} __attribute__((__packed__));

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 179
& IoT
Contd.
extern int copy_to_user(void *dest, void *src,
size_t size);
void do_stuff(void *usr_buf)
{
struct test arg = {.a = 1, .b = 2, .c = 3};
copy_to_user(usr_buf, &arg, sizeof(arg));
}

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 180
& IoT
DCL40-C. Do not create incompatible
declarations of the same function or
object
/* In a.c */
extern int i;
int f(void)
{
return ++I;
}
/* In b.c */
short i;
Two or more incompatible declarations of the same
function or object must not appear in the same
program because they result in undefined behavior.

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 181
& IoT
Compliant Solution (Incompatible
Object Declarations)
/* In a.c */
extern int i;
int f(void)
{ return ++i;
}
/* In b.c */
int i;

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 182
& IoT
Noncompliant Code Example
(Incompatible Array Declarations)
/* In a.c */
extern int *a;
int f(unsigned int i, int x)
{
int tmp = a[i]; /* read access */
a[i] = x; /* write access */
return tmp;
}
/* In b.c */
int a[] = { 1, 2, 3, 4 };
variable a is declared to have a pointer type in file a.c but
defined to have an array type in file b.c.

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 183
& IoT
Compliant Solution (Incompatible
Array Declarations)
/* In a.c */
extern int a[];
int f(unsigned int i, int x)
{
int tmp = a[i];
a[i] = x;
return tmp;
}
int a[] = { 1, 2, 3, 4 }; /* In b.c */

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 184
& IoT
Noncompliant Code Example
(Incompatible Function Declarations)
/* In a.c */
extern int f(int a);
int g(int a)
{
return f(a); }
/* In b.c */
long f(long a)
{
return a * 2;
}
the function f() is declared in file a.c with one prototype but
defined in file b.c with another.

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 185
& IoT
Compliant Solution (Incompatible
Function Declarations)
/* In a.c */
extern int f(int a);
int g(int a)
{
return f(a);
}/* In b.c */
int f(int a)
{
return a * 2;
}

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 186
& IoT
DCL41-C. Do not declare variables inside a
switch statement before the first case label

• If a programmer declares variables, initializes


them before the first case statement, and
then tries to use them inside any of the case
statements, those variables will have scope
inside the switch block but will not be
initialized and will consequently contain
indeterminate values.

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 187
& IoT
Noncompliant Code Example
#include <stdio.h>
extern void f(int i);
void func(int expr)
{
switch (expr)
{
int i = 4;
f(i);
case 0:
i = 17;

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 188
& IoT
contd.
• /* Falls through into default code */ default:
printf("%d\n".•, i); } }

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 189
& IoT
Compliant Solution
#include <stdio.h>
extern void f(int i);
int func(int expr)
{ /** Move the code outside the switch block;
now the statements * will get executed. */
int i = 4;
f(i);

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 190
& IoT
Contd.

switch (expr)
{ case 0: i = 17;
/* Falls through into default code */
default: printf(".oe%d\n".•
, i);
}
return 0;
}

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 191
& IoT
Expressions (EXP)
EXP30-C. Do not depend on the order of evaluation
for side effects
Noncompliant Code Example
#include <stdio.h>
void func(int i, int *b)
{
int a = i + b[++i];
printf("%d, %d", a, i);
}
20EC211- Embedded Systems
RAJASEKAR T, AP/ECE 192
& IoT
Compliant Solution
#include <stdio.h>
void func(int i, int *b)
{
int a;
++i;
a = i + b[i];
printf("%d, %d", a, i);
}
20EC211- Embedded Systems
RAJASEKAR T, AP/ECE 193
& IoT
Call functions with the correct
number and type of arguments
• Do not call a function with the wrong number
or type of arguments

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 194
& IoT
Noncompliant Code Example
#include <tgmath.h>
void func(void)
{ double complex c = 2.0 + 4.0 * I;
double complex result = log2(c);
}
Calling any of the following type-generic
functions with complex values is undefined
be-havior.
20EC211- Embedded Systems
RAJASEKAR T, AP/ECE 195
& IoT
Compliant Solution (Complex
Number)
#include <tgmath.h>
void func(void)
{ double complex c = 2.0 + 4.0 * I;
double complex result = log(c)/log(2);
}

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 196
& IoT
EXP44-C Do not rely on side effects in
operands to sizeof
Noncompliant Code Example (sizeof)
#include <stdio.h>
void func(void)
{
int a = 14;
int b = sizeof(a++);
printf("%d, %d\n", a, b);
}
the operand is not evaluated

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 197
& IoT
Compliant Solution (sizeof)
#include <stdio.h>
void func(void)
{
int a = 14;
int b = sizeof(a);
++a;
printf("%d, %d\n", a, b); }

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 198
& IoT
EXP45-C. Do not perform assignments
in selection statements
Noncompliant Code Example
if (a = b) {.. }
Compliant Solution (Unintentional
Assignment)
if (a == b)
..
}
if ((a = b) != 0) { /* ... */ }
20EC211- Embedded Systems
RAJASEKAR T, AP/ECE 199
& IoT
Contd.
• do { /* ... */ } while (foo(), x = y); -NC
• do { /* ... */ } while (x = y, p == q); -C

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 200
& IoT
EXP46-C. Do not use a bitwise
operator with a Boolean-like operand
• Noncompliant Code Example
• if (!(getuid() & geteuid() == 0)) { /* ... */ }
• Compliant Solution
• if (!(getuid() && geteuid() == 0)) { /* ... */ }
• Mixing bitwise and relational operators in the
same full expression can be a sign of a logic
error in the expression where a logical
operator is usually the intended operator
20EC211- Embedded Systems
RAJASEKAR T, AP/ECE 201
& IoT
Integers(INT)
• INT30-C. Ensure that unsigned integer
operations do not wrap
• Noncompliant Code Example
• void func(unsigned int ui_a, unsigned int
ui_b) { unsigned int usum = ui_a + ui_b; /* ...
*/ }

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 202
& IoT
Compliant Solution (Precondition Test)

#include <limits.h>
void func(unsigned int ui_a, unsigned int ui_b) {
unsigned int usum;
if (UINT_MAX - ui_a < ui_b) { /* Handle error */
}
else
{ usum = ui_a + ui_b; }/* ... */ }

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 203
& IoT
Noncompliant Code Example
(Unsigned to Signed)
#include <limits.h>
void func(void)
{ unsigned long int u_a = ULONG_MAX;
signed char sc;
sc = (signed char)u_a;
• /* Cast eliminates warning */ /* ... */ }
• Type range errors, including loss of data
(truncation) and loss of sign (sign errors), can
occur when converting from a value of an
unsigned integer type to a value of a signed
integer type
20EC211- Embedded Systems
RAJASEKAR T, AP/ECE 204
& IoT
Compliant Solution (Unsigned to
Signed)
#include <limits.h>
void func(void)
{ unsigned long int u_a = ULONG_MAX;
signed char sc;
if (u_a <= SCHAR_MAX)
{ sc = (signed char)u_a; /* Cast eliminates warning */
}
else { /* Handle error */
}
}

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 205
& IoT
INT32-C. Ensure that operations on signed
integers do not result in overflow
Noncompliant Code Example
void func(signed int si_a, signed int si_b)
{
signed int sum = si_a + si_b; /* ... */
}

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 206
& IoT
Compliant Solution
#include <limits.h>
void f(signed int si_a, signed int si_b)
{ signed int sum;
if (((si_b > 0) && (si_a > (INT_MAX - si_b))) ||
((si_b < 0) && (si_a < (INT_MIN - si_b))))
{ /* Handle error */ }
else
{
sum = si_a + si_b;
}/* ... */ }
20EC211- Embedded Systems
RAJASEKAR T, AP/ECE 207
& IoT
Contd.
• INT34-C. Do not shift an expression by a negative
number of bits or by greater than or equal to the
number of bits that exist in the operand
• INT33-C. Ensure that division and remainder
operations do not result in divide-by-zero errors
• INT35-C. Use correct integer precisions. The
precision of an integer type is the number of bits
it uses to represent values, excluding any sign
and padding bits.
20EC211- Embedded Systems
RAJASEKAR T, AP/ECE 208
& IoT
Floating Point (FLP)
FLP30-C. Do not use floating-point variables as
loop counters
Noncompliant Code Example
void func(void)
{
for (
float x = 0.1f; x <= 1.0f; x += 0.1f)
{ /* Loop may iterate 9 or 10 times */
}
}

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 209
& IoT
Compliant Solution
#include <stddef.h>
void func(void)
{
for (size_t count = 1; count <= 10; ++count)
{ float x = count / 10.0f;
/* Loop iterates exactly 10 times */

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 210
& IoT
Array (ARR)
• ARR30-C. Do not form or use out-of-bounds
pointers or array subscripts

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 211
& IoT
Noncompliant Code Example
(Apparently Accessible Out-of-Range
Index)
#include <stddef.h>
#define COLS 5
#define ROWS 7
static int matrix[ROWS][COLS];
void init_matrix(int x)
{
for (size_t i = 0; i < COLS; i++) {
for (size_t j = 0; j < ROWS; j++)
{ matrix[i][j] = x; }
}
}

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 212
& IoT
Contd.
• the function iterates over the elements in
column-major order, and when the value of j
reaches the value COLS during the first
iteration of the outer loop, the function
attempts to access element matrix[0][5].

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 213
& IoT
Compliant Solution
#include <stddef.h>
#define COLS 5
#define ROWS 7
static int matrix[ROWS][COLS];
void init_matrix(int x)
{
for (size_t i = 0; i < ROWS; i++)
{ for (size_t j = 0; j < COLS; j++)
{ matrix[i][j] = x;
}
}
}

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 214
& IoT
Characters and Strings (STR)
• STR30-C. Do not attempt to modify string
literals
• Noncompliant Code Example
• char *p = "string literal"; p[0] = ‘S';

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 215
& IoT
CONTD.
• Compliant Solution
• char a[] = "string literal"; a[0] = ‘S';
• This code creates a copy of the string literal in
the space allocated to the character array a.
The string stored in a can be modified safely.

• STR31-C. Guarantee that storage for strings


has sufficient space for character data and
the null terminator
20EC211- Embedded Systems
RAJASEKAR T, AP/ECE 216
& IoT
NC
STR32-C. Do not pass a non-null-terminated
character sequence to a library function that
expects a string
#include <stdio.h>
void func(void)
{
char c_str[3] = "abc";
printf("%s\n", c_str);
}

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 217
& IoT
C
#include <stdio.h>
void func(void)
{ char c_str[] = "abc";
printf("%s\n", c_str);
}

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 218
& IoT
Memory Management (MEM)
• MEM30-C. Do not access freed memory
• MEM31-C. Free dynamically allocated
memory when no longer needed

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 219
& IoT
NC
#include <stdlib.h> enum
{ BUFFER_SIZE = 32 };
int f(void)
{
char *text_buffer = (char *)malloc(BUFFER_SIZE);
if (text_buffer == NULL)
{ return -1;
}return 0;
}

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 220
& IoT
C
#include <stdlib.h> enum
{ BUFFER_SIZE = 32 };
int f(void)
{
char *text_buffer = (char *)malloc(BUFFER_SIZE);
if (text_buffer == NULL)
{
return -1;
}
free(text_buffer);
return 0; }

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 221
& IoT
THANK YOU

20EC211- Embedded Systems


RAJASEKAR T, AP/ECE 222
& IoT

You might also like