SlideShare a Scribd company logo
Experiences Sharing on
Embedded System Development
Teddy Hsiung / 熊厚祥Teddy Hsiung / 熊厚祥
hhhsiung@gmail.com
Embedded System
• An embedded system is a computer system with
a dedicated function within a larger mechanical or
electrical system, often with real-time
computing constraints.
• It is embedded as part of a complete device often• It is embedded as part of a complete device often
including hardware and mechanical parts.
• Embedded systems control many devices in
common use today, 98 percents of all
microprocessors being manufactured are used in
embedded systems.
• Definition from Wiki.
Embedded System Restrictions
• Limited CPU Speed
• Limited Flash Size (code, constant data)
• Limited RAM Size (data, run-time stack)
• Limited Peripherals (GPIO Simulate?)
• Low Power Consumption• Low Power Consumption
• Low Per-Unit Cost
• Small In Size
• Rugged Operating Ranges?
• Response in Real-Time?
uC/OS-II on TI-DM270
Task Monitor via COM port
Memory Alignment Issue in memcpy()
void *memcpy(void *dest, void *src, size_t count);
memcpy( 4m , 4n , x );
4 Times
memcpy( 4m+1, 4n , x );
memcpy( 4m , 4n+1, x );
V.S.
4 Times
Faster!!!
Portable DVR Kits with CF Card
CF Card Access Performance Issue
wp = (FS_U16 *) word_buf;
for (i=0; i<CF_WORDS_PER_PHY_SECTOR; i++)
{
*wp++ = *BYTDATREG;
}
wp = (FS_U16 *) word_buf;
for (i=0; i<CF_DWORDS_PER_PHY_SECTOR; i++)
{
*wp++ = *BYTDATREG;
*wp++ = *BYTDATREG;
}
Double Access Performance!!!
Survellience 8/16CH DVR
Simulated I/F Access Timing Stability
TI-DM270 Techwell TW2824
Forgotten World Under Program
Running – Runtime Stack
• Why our function calls can return to it’s
original address?
• How the functions parameters passing?
• Where are our local variables stored/located?• Where are our local variables stored/located?
• Where is the program runtime stack located?
• How to decide stack size for each task/process?
• Recursive functions vs. runtime stack.
• Buffer overflow attack.
Machine status in “run-time stack”
void interrupt (*old_isr)(...);
void interrupt new_isr(…)
{
(*old_isr)();
}
@new_isr$qve proc far
push ax
push bx
push cx
push dx
push es
push ds
push si
push di
push bp
mov bp,DGROUP
mov ds,bp
n-6 mov bp,DGROUP
mov ds,bp
mov bp,sp
; {
; (*old_isr)();
pushf
call dword ptr DGROUP:_old_isr
; }
pop bp
pop di
pop si
pop ds
pop es
pop dx
pop cx
pop bx
pop ax
iret
@new_isr$qve endp
n-2
n
n+2
n+4
n+6
n+8
n+10
n+12
n+14
n+16
n+18
n+22
n+24
CPU flags
Return Address
.
.
.
ax
axbx
cx
dx
es
ds
si
di
bp sp, bp
Parameters in “run-time stack”
_DATA segment word public 'DATA'
_c label byte
db 97
_i label word
db 52,18
_j label word
db 120,86,0,0
_DATA ends
_TEXT segment byte public 'CODE'
;
; void main(void)
;
assume cs:_TEXT
_main proc near
char c='a';
int i=0x1234;
long j=0x5678;
int val;
int func(char, int, long);
void main(void)
{
val = func(c, i, j);
} _main proc near
push bp
mov bp,sp
;
; {
; val = func(c, i, j);
;
push word ptr DGROUP:_j+2
push word ptr DGROUP:_j
push word ptr DGROUP:_i
mov al,byte ptr DGROUP:_c
push ax
call near ptr _func
add sp,8
mov word ptr DGROUP:_val,ax
;
; }
;
pop bp
ret
_main endp
_TEXT ends
}
n-16
n-14
n-12
n-10
n-8
n-6
n-4
n-2
n
n+2
n+4
Return Address
.
.
.
low word of j
i
c
bp
high word of j
sp
bp
Local variables in “run-time stack”
_TEXT segment byte public 'CODE'
;
; int func(char cc,int ii,long jj)
;
assume cs:_TEXT
_func proc near
push bp
mov bp,sp
sub sp,4
;
; {
; int k=0, l=1;
;
mov word ptr [bp-2],0
mov word ptr [bp-4],1
char c='a';
int i=0x1234;
long j=0x5678;
int val;
int func(char cc, int ii, long jj)
{
int k=0, l=1;
return ii;
}
void main(void)
{
val = func(c, i, j);
}
ENTER Instruction
mov word ptr [bp-4],1
;
; return k;
;
mov ax,word ptr [bp+6]
jmp short @1@58
@1@58:
;
; }
;
mov sp,bp
pop bp
ret
_func endp
;
; void main(void)
;
assume cs:_TEXT
_main proc near
...
_main endp
_TEXT ends
}
n-4
n-2
n
n+2
n+4
n+6
n+8
n+10
n+12
n+14
n+16
Return Address
.
.
.
low word of j =jj
I =ii
c =cc
bp
high word of j =jj
Return Address
sp
bpbp
?? = l
?? = k
Control
Link
bp
LEAVE Instruction
Buffer/Stack Overflow in Local Array
void foo(const char* input)
{
char buf[10];
sprintf(buf, "Hello World, %s.n“, input);
}
int main(int argc, char* argv[]) { buf[3] buf[2] buf[1] buf[0]int main(int argc, char* argv[]) {
foo(argv[1]);
return 0;
}
buf[3] buf[2] buf[1] buf[0]
buf[7] buf[6] buf[5] buf[4]
……………….. buf[9] buf[8]
Buffer Overflow Prevention
• Use “snprintf()” instead of “sprintf()”:
 int snprintf(char *str, size_t size, const char * restrict format, ...)
 int sprintf( char * str, const char * format, ... )
 Refer “用 snprintf / asprintf 取代不安全的 sprintf”
• Use “strncpy()” instead of “strcpy()”:• Use “strncpy()” instead of “strcpy()”:
 char *strncpy(char *dest, const char * src, size_t num)
 char *strcpy(char *dest, const char *src)
Buffer Overflow Attack
#include <stdio.h>
#include <string.h>
int main(void)
{
char buff[15];
int pass = 0;
printf("n Enter the password : n");
gets(buff);
if(strcmp(buff, "thegeekstuff"))
$ ./bfrovrflw
Enter the password :
thegeekstuff
Correct Password
Run with correct password:
if(strcmp(buff, "thegeekstuff"))
{
printf ("n Wrong Password n");
}
else
{
printf ("n Correct Password n");
pass = 1;
}
if(pass)
{
/* Now Give root or admin rights to user*/
printf ("n Root privileges given to user n");
}
return 0;
}
Root privileges given to the user
$ ./bfrovrflw
Enter the password :
hhhhhhhhhhhhhhhhhhhh
Wrong Password
Root privileges given to the user
Run with buffer overflow attack:
/*
StackOverrun.c
This program shows an example of how a stack-based
buffer overrun can be used to execute arbitrary code. Its
objective is to find an input string that executes the function bar.
*/
#pragma check_stack(off)
#include <string.h>
#include <stdio.h>
void foo(const char* input)
Stack Overrun Example from
Howard and LeBlanc
{
char buf[10];
printf("My stack looks like:n%pn%pn%pn%pn%pn% pnn");
strcpy(buf, input);
printf("%sn", buf);
printf("Now the stack looks like:n%pn%pn%pn%pn%pn%pnn");
}
void bar(void)
{
printf("Augh! I've been hacked!n");
}
int main(int argc, char* argv[])
{
//Blatant cheating to make life easier on myself
printf("Address of foo = %pn", foo);
printf("Address of bar = %pn", bar);
if (argc != 2)
{
printf("Please supply a string as an
argument!n");
return -1;
}
foo(argv[1]);
return 0;
}
File Browse in Media Player Project
Video File Sorting in DVR
Video File Sorting in PSR
Sorting Algorithm Comparison
Randomly sorted array:
Sorting Algorithm Comparison
Sorted array:
Reverse sorted array:
Stack Overflow in Recursive QSort
OS_STK *QSortStkLmt;
void _CalcStkLmt(void) { QSortStkLmt = OSTCBCur->OSTCBStkBottom + QSORT_STK_CONSUPT; }
_CODE_ACCESS void _QSort(void *base, size_t nmemb, size_t size,
int (*compar)(const void *, const void *))
{
register char *basep = base; /* POINTER TO ARRAY OF ELEMENTS */
register unsigned i = 0; /* left scan index */
register unsigned j = nmemb - 1; /* right scan index */
register unsigned pivot = (nmemb / 2);
register char *pivp = basep + (pivot * size);
// prevent stack overflow.
//dprintf("Stack=%xnr", GetStkPtrReg());
if(GetStkPtrReg() <= (U32)QSortStkLmt) {if(GetStkPtrReg() <= (U32)QSortStkLmt) {
dprintf("nrQSortStkOv:%x, Lmt:%x:", GetStkPtrReg(), QSortStkLmt);
return;
}
if (nmemb <= 1) return;
while( i < j )
{
while( (*compar) (basep + (i * size), pivp) < 0 ) ++i;
while( (*compar) (basep + (j * size), pivp) > 0 ) --j;
if( i < j )
{
_SwapItem(basep + (i * size), basep + (j * size), size);
if ( pivot == i ) { pivot = j; pivp = basep + (pivot * size); }
else if( pivot == j ) { pivot = i; pivp = basep + (pivot * size); }
++i; --j;
}
else if ( i == j ) { ++i; --j; break; }
}
if( j > 0) _QSort(basep, j + 1, size, compar);
if( i < nmemb-1) _QSort(basep + (i * size), nmemb - i, size, compar);
}
Critical Section Issues
class Counter
{
private int value = 1; //counter starts at one
public Counter(int c) { //constructor initializes counterpublic Counter(int c) { //constructor initializes counter
value = c;
}
public int inc() { //increment value & return prior value
int temp = value; //start of danger zone
value = temp+1; //end of danger zone
return temp;
}
}
Critical Section Issues
• The problem occurs if two threads both read
the value field at the line marked “start of
danger zone”, and then both update that field
at the line marked “end of danger zone”.at the line marked “end of danger zone”.
int temp = value;
value = temp+1;
Critical Section Issues
Value 2 3 2int temp = value;
value = temp+1;
read 1
read 1
write 2
read 2
write 3
write 2
time
The secret of “volatile” keyword
• void dummy_loop(int cnt)
{
volatile int i;
for (i=0; i<cnt; i++) {}
}}
• volatile UINT32 *reg = 0x30000000;
*reg = 100;
*reg = 200;
*reg = 300;
• What’s the result after optimization?
Variable Allocation in C/C++
• Global variables:
int var;
static int var;
const int var = 100;const int var = 100;
• Local variables:
void func(void) {
int var;
static int var;
}
Logical Memory Components
Reduce of Program Flash Usage
• How to minimize the code size to fit into the
limited flash memory?
– What will be put into the flash memory after
program compiled/linked?program compiled/linked?
– Good algorithm reduced code size.
– Good coding skill reduced code size.
– Optimization during compiling.
=> Timing changed side effect => Usage of
“volatile”
Reduce of Data Memory Usage
• How to minimize the data size to fit into the
limited SRAM?
– Usually more precious/limited than flash memory.
– Where will our data located for different kind of– Where will our data located for different kind of
variables? (local vs. global vs. static vs. const)
– Constant tables put into flash instead of SRAM
– Compact data structure design
– Local variable vs. Global variable
Conclusion (1/2)
• Embedded system is a mix domain that cover
various technical fields:
– Computer Programming, Assembly Language
– Data Structure, Algorithm
– Operating System, Compiler– Operating System, Compiler
– Computer Organization & Architecture
– Digital System, Electrical Circuits
– Microprocessor Systems
– Digital Signal Processing
– Specific Industry Domain Knowledge.
Conclusion (2/2)
• Workaround ≠ Solution
• 工作年資 ≠ 經驗累積
• 成為嵌入式系統達人的必要條件:
–– 廣泛的專業知識
– 敏銳的觀察力
– 追根究底的精神.
– 面對問題的積極態度
Q & A
Thank You

More Related Content

What's hot

ISCA Final Presentaiton - Compilations
ISCA Final Presentaiton -  CompilationsISCA Final Presentaiton -  Compilations
ISCA Final Presentaiton - Compilations
HSA Foundation
 
Vc4c development of opencl compiler for videocore4
Vc4c  development of opencl compiler for videocore4Vc4c  development of opencl compiler for videocore4
Vc4c development of opencl compiler for videocore4
nomaddo
 
Sysprog 12
Sysprog 12Sysprog 12
Sysprog 12
Ahmed Mekkawy
 
Sysprog 12
Sysprog 12Sysprog 12
Sysprog 12
Ahmed Mekkawy
 
Vectorization on x86: all you need to know
Vectorization on x86: all you need to knowVectorization on x86: all you need to know
Vectorization on x86: all you need to know
Roberto Agostino Vitillo
 
Process management
Process managementProcess management
Process management
Utkarsh Kulshrestha
 
Meltdown & Spectre
Meltdown & Spectre Meltdown & Spectre
Meltdown & Spectre
Marco Cipriano
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
Viji B
 
Virtual Machine Constructions for Dummies
Virtual Machine Constructions for DummiesVirtual Machine Constructions for Dummies
Virtual Machine Constructions for Dummies
National Cheng Kung University
 
Meltdown & spectre
Meltdown & spectreMeltdown & spectre
Meltdown & spectre
Sergio Shevchenko
 
C - aptitude3
C - aptitude3C - aptitude3
C - aptitude3
Srikanth
 
Bridge TensorFlow to run on Intel nGraph backends (v0.5)
Bridge TensorFlow to run on Intel nGraph backends (v0.5)Bridge TensorFlow to run on Intel nGraph backends (v0.5)
Bridge TensorFlow to run on Intel nGraph backends (v0.5)
Mr. Vengineer
 
Tiramisu をちょっと、味見してみました。
Tiramisu をちょっと、味見してみました。Tiramisu をちょっと、味見してみました。
Tiramisu をちょっと、味見してみました。
Mr. Vengineer
 
TVM VTA (TSIM)
TVM VTA (TSIM) TVM VTA (TSIM)
TVM VTA (TSIM)
Mr. Vengineer
 
Python profiling
Python profilingPython profiling
Python profiling
dreampuf
 
WebAssembly向け多倍長演算の実装
WebAssembly向け多倍長演算の実装WebAssembly向け多倍長演算の実装
WebAssembly向け多倍長演算の実装
MITSUNARI Shigeo
 
Initiation concrète-à-la-virtualisation-devoxx-fr-2021
Initiation concrète-à-la-virtualisation-devoxx-fr-2021Initiation concrète-à-la-virtualisation-devoxx-fr-2021
Initiation concrète-à-la-virtualisation-devoxx-fr-2021
Pierre-Antoine Grégoire
 
深層学習フレームワークにおけるIntel CPU/富岳向け最適化法
深層学習フレームワークにおけるIntel CPU/富岳向け最適化法深層学習フレームワークにおけるIntel CPU/富岳向け最適化法
深層学習フレームワークにおけるIntel CPU/富岳向け最適化法
MITSUNARI Shigeo
 
TensorFlow XLA RPC
TensorFlow XLA RPCTensorFlow XLA RPC
TensorFlow XLA RPC
Mr. Vengineer
 

What's hot (19)

ISCA Final Presentaiton - Compilations
ISCA Final Presentaiton -  CompilationsISCA Final Presentaiton -  Compilations
ISCA Final Presentaiton - Compilations
 
Vc4c development of opencl compiler for videocore4
Vc4c  development of opencl compiler for videocore4Vc4c  development of opencl compiler for videocore4
Vc4c development of opencl compiler for videocore4
 
Sysprog 12
Sysprog 12Sysprog 12
Sysprog 12
 
Sysprog 12
Sysprog 12Sysprog 12
Sysprog 12
 
Vectorization on x86: all you need to know
Vectorization on x86: all you need to knowVectorization on x86: all you need to know
Vectorization on x86: all you need to know
 
Process management
Process managementProcess management
Process management
 
Meltdown & Spectre
Meltdown & Spectre Meltdown & Spectre
Meltdown & Spectre
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
Virtual Machine Constructions for Dummies
Virtual Machine Constructions for DummiesVirtual Machine Constructions for Dummies
Virtual Machine Constructions for Dummies
 
Meltdown & spectre
Meltdown & spectreMeltdown & spectre
Meltdown & spectre
 
C - aptitude3
C - aptitude3C - aptitude3
C - aptitude3
 
Bridge TensorFlow to run on Intel nGraph backends (v0.5)
Bridge TensorFlow to run on Intel nGraph backends (v0.5)Bridge TensorFlow to run on Intel nGraph backends (v0.5)
Bridge TensorFlow to run on Intel nGraph backends (v0.5)
 
Tiramisu をちょっと、味見してみました。
Tiramisu をちょっと、味見してみました。Tiramisu をちょっと、味見してみました。
Tiramisu をちょっと、味見してみました。
 
TVM VTA (TSIM)
TVM VTA (TSIM) TVM VTA (TSIM)
TVM VTA (TSIM)
 
Python profiling
Python profilingPython profiling
Python profiling
 
WebAssembly向け多倍長演算の実装
WebAssembly向け多倍長演算の実装WebAssembly向け多倍長演算の実装
WebAssembly向け多倍長演算の実装
 
Initiation concrète-à-la-virtualisation-devoxx-fr-2021
Initiation concrète-à-la-virtualisation-devoxx-fr-2021Initiation concrète-à-la-virtualisation-devoxx-fr-2021
Initiation concrète-à-la-virtualisation-devoxx-fr-2021
 
深層学習フレームワークにおけるIntel CPU/富岳向け最適化法
深層学習フレームワークにおけるIntel CPU/富岳向け最適化法深層学習フレームワークにおけるIntel CPU/富岳向け最適化法
深層学習フレームワークにおけるIntel CPU/富岳向け最適化法
 
TensorFlow XLA RPC
TensorFlow XLA RPCTensorFlow XLA RPC
TensorFlow XLA RPC
 

Similar to ExperiencesSharingOnEmbeddedSystemDevelopment_20160321

Rootkit on Linux X86 v2.6
Rootkit on Linux X86 v2.6Rootkit on Linux X86 v2.6
Rootkit on Linux X86 v2.6
fisher.w.y
 
Static analysis of C++ source code
Static analysis of C++ source codeStatic analysis of C++ source code
Static analysis of C++ source code
PVS-Studio
 
PVS-Studio 5.00, a solution for developers of modern resource-intensive appl...
PVS-Studio 5.00, a solution for developers of modern resource-intensive appl...PVS-Studio 5.00, a solution for developers of modern resource-intensive appl...
PVS-Studio 5.00, a solution for developers of modern resource-intensive appl...
Andrey Karpov
 
C aptitude questions
C aptitude questionsC aptitude questions
C aptitude questions
Srikanth
 
LSFMM 2019 BPF Observability
LSFMM 2019 BPF ObservabilityLSFMM 2019 BPF Observability
LSFMM 2019 BPF Observability
Brendan Gregg
 
Rootkit on linux_x86_v2.6
Rootkit on linux_x86_v2.6Rootkit on linux_x86_v2.6
Rootkit on linux_x86_v2.6
scuhurricane
 
TLPI - 6 Process
TLPI - 6 ProcessTLPI - 6 Process
TLPI - 6 Process
Shu-Yu Fu
 
Beyond Breakpoints: A Tour of Dynamic Analysis
Beyond Breakpoints: A Tour of Dynamic AnalysisBeyond Breakpoints: A Tour of Dynamic Analysis
Beyond Breakpoints: A Tour of Dynamic Analysis
Fastly
 
Unit 4
Unit 4Unit 4
Unit 4
siddr
 
Assignment no39
Assignment no39Assignment no39
Assignment no39
Jay Patel
 
Windbg랑 친해지기
Windbg랑 친해지기Windbg랑 친해지기
Windbg랑 친해지기
Ji Hun Kim
 
Getting started cpp full
Getting started cpp   fullGetting started cpp   full
Getting started cpp full
Võ Hòa
 
Exploitation of counter overflows in the Linux kernel
Exploitation of counter overflows in the Linux kernelExploitation of counter overflows in the Linux kernel
Exploitation of counter overflows in the Linux kernel
Vitaly Nikolenko
 
Exploring the x64
Exploring the x64Exploring the x64
Exploring the x64
FFRI, Inc.
 
bpftrace - Tracing Summit 2018
bpftrace - Tracing Summit 2018bpftrace - Tracing Summit 2018
bpftrace - Tracing Summit 2018
AlastairRobertson9
 
Austin c-c++-meetup-feb2018-spectre
Austin c-c++-meetup-feb2018-spectreAustin c-c++-meetup-feb2018-spectre
Austin c-c++-meetup-feb2018-spectre
Kim Phillips
 
Rust LDN 24 7 19 Oxidising the Command Line
Rust LDN 24 7 19 Oxidising the Command LineRust LDN 24 7 19 Oxidising the Command Line
Rust LDN 24 7 19 Oxidising the Command Line
Matt Provost
 
Address/Thread/Memory Sanitizer
Address/Thread/Memory SanitizerAddress/Thread/Memory Sanitizer
Address/Thread/Memory Sanitizer
Platonov Sergey
 
Rust: код может быть одновременно безопасным и быстрым, Степан Кольцов
Rust: код может быть одновременно безопасным и быстрым, Степан КольцовRust: код может быть одновременно безопасным и быстрым, Степан Кольцов
Rust: код может быть одновременно безопасным и быстрым, Степан Кольцов
Yandex
 
rrxv6 Build a Riscv xv6 Kernel in Rust.pdf
rrxv6 Build a Riscv xv6 Kernel in Rust.pdfrrxv6 Build a Riscv xv6 Kernel in Rust.pdf
rrxv6 Build a Riscv xv6 Kernel in Rust.pdf
Yodalee
 

Similar to ExperiencesSharingOnEmbeddedSystemDevelopment_20160321 (20)

Rootkit on Linux X86 v2.6
Rootkit on Linux X86 v2.6Rootkit on Linux X86 v2.6
Rootkit on Linux X86 v2.6
 
Static analysis of C++ source code
Static analysis of C++ source codeStatic analysis of C++ source code
Static analysis of C++ source code
 
PVS-Studio 5.00, a solution for developers of modern resource-intensive appl...
PVS-Studio 5.00, a solution for developers of modern resource-intensive appl...PVS-Studio 5.00, a solution for developers of modern resource-intensive appl...
PVS-Studio 5.00, a solution for developers of modern resource-intensive appl...
 
C aptitude questions
C aptitude questionsC aptitude questions
C aptitude questions
 
LSFMM 2019 BPF Observability
LSFMM 2019 BPF ObservabilityLSFMM 2019 BPF Observability
LSFMM 2019 BPF Observability
 
Rootkit on linux_x86_v2.6
Rootkit on linux_x86_v2.6Rootkit on linux_x86_v2.6
Rootkit on linux_x86_v2.6
 
TLPI - 6 Process
TLPI - 6 ProcessTLPI - 6 Process
TLPI - 6 Process
 
Beyond Breakpoints: A Tour of Dynamic Analysis
Beyond Breakpoints: A Tour of Dynamic AnalysisBeyond Breakpoints: A Tour of Dynamic Analysis
Beyond Breakpoints: A Tour of Dynamic Analysis
 
Unit 4
Unit 4Unit 4
Unit 4
 
Assignment no39
Assignment no39Assignment no39
Assignment no39
 
Windbg랑 친해지기
Windbg랑 친해지기Windbg랑 친해지기
Windbg랑 친해지기
 
Getting started cpp full
Getting started cpp   fullGetting started cpp   full
Getting started cpp full
 
Exploitation of counter overflows in the Linux kernel
Exploitation of counter overflows in the Linux kernelExploitation of counter overflows in the Linux kernel
Exploitation of counter overflows in the Linux kernel
 
Exploring the x64
Exploring the x64Exploring the x64
Exploring the x64
 
bpftrace - Tracing Summit 2018
bpftrace - Tracing Summit 2018bpftrace - Tracing Summit 2018
bpftrace - Tracing Summit 2018
 
Austin c-c++-meetup-feb2018-spectre
Austin c-c++-meetup-feb2018-spectreAustin c-c++-meetup-feb2018-spectre
Austin c-c++-meetup-feb2018-spectre
 
Rust LDN 24 7 19 Oxidising the Command Line
Rust LDN 24 7 19 Oxidising the Command LineRust LDN 24 7 19 Oxidising the Command Line
Rust LDN 24 7 19 Oxidising the Command Line
 
Address/Thread/Memory Sanitizer
Address/Thread/Memory SanitizerAddress/Thread/Memory Sanitizer
Address/Thread/Memory Sanitizer
 
Rust: код может быть одновременно безопасным и быстрым, Степан Кольцов
Rust: код может быть одновременно безопасным и быстрым, Степан КольцовRust: код может быть одновременно безопасным и быстрым, Степан Кольцов
Rust: код может быть одновременно безопасным и быстрым, Степан Кольцов
 
rrxv6 Build a Riscv xv6 Kernel in Rust.pdf
rrxv6 Build a Riscv xv6 Kernel in Rust.pdfrrxv6 Build a Riscv xv6 Kernel in Rust.pdf
rrxv6 Build a Riscv xv6 Kernel in Rust.pdf
 

ExperiencesSharingOnEmbeddedSystemDevelopment_20160321

  • 1. Experiences Sharing on Embedded System Development Teddy Hsiung / 熊厚祥Teddy Hsiung / 熊厚祥 hhhsiung@gmail.com
  • 2. Embedded System • An embedded system is a computer system with a dedicated function within a larger mechanical or electrical system, often with real-time computing constraints. • It is embedded as part of a complete device often• It is embedded as part of a complete device often including hardware and mechanical parts. • Embedded systems control many devices in common use today, 98 percents of all microprocessors being manufactured are used in embedded systems. • Definition from Wiki.
  • 3. Embedded System Restrictions • Limited CPU Speed • Limited Flash Size (code, constant data) • Limited RAM Size (data, run-time stack) • Limited Peripherals (GPIO Simulate?) • Low Power Consumption• Low Power Consumption • Low Per-Unit Cost • Small In Size • Rugged Operating Ranges? • Response in Real-Time?
  • 5. Task Monitor via COM port
  • 6. Memory Alignment Issue in memcpy() void *memcpy(void *dest, void *src, size_t count); memcpy( 4m , 4n , x ); 4 Times memcpy( 4m+1, 4n , x ); memcpy( 4m , 4n+1, x ); V.S. 4 Times Faster!!!
  • 7. Portable DVR Kits with CF Card
  • 8. CF Card Access Performance Issue wp = (FS_U16 *) word_buf; for (i=0; i<CF_WORDS_PER_PHY_SECTOR; i++) { *wp++ = *BYTDATREG; } wp = (FS_U16 *) word_buf; for (i=0; i<CF_DWORDS_PER_PHY_SECTOR; i++) { *wp++ = *BYTDATREG; *wp++ = *BYTDATREG; } Double Access Performance!!!
  • 10. Simulated I/F Access Timing Stability TI-DM270 Techwell TW2824
  • 11. Forgotten World Under Program Running – Runtime Stack • Why our function calls can return to it’s original address? • How the functions parameters passing? • Where are our local variables stored/located?• Where are our local variables stored/located? • Where is the program runtime stack located? • How to decide stack size for each task/process? • Recursive functions vs. runtime stack. • Buffer overflow attack.
  • 12. Machine status in “run-time stack” void interrupt (*old_isr)(...); void interrupt new_isr(…) { (*old_isr)(); } @new_isr$qve proc far push ax push bx push cx push dx push es push ds push si push di push bp mov bp,DGROUP mov ds,bp n-6 mov bp,DGROUP mov ds,bp mov bp,sp ; { ; (*old_isr)(); pushf call dword ptr DGROUP:_old_isr ; } pop bp pop di pop si pop ds pop es pop dx pop cx pop bx pop ax iret @new_isr$qve endp n-2 n n+2 n+4 n+6 n+8 n+10 n+12 n+14 n+16 n+18 n+22 n+24 CPU flags Return Address . . . ax axbx cx dx es ds si di bp sp, bp
  • 13. Parameters in “run-time stack” _DATA segment word public 'DATA' _c label byte db 97 _i label word db 52,18 _j label word db 120,86,0,0 _DATA ends _TEXT segment byte public 'CODE' ; ; void main(void) ; assume cs:_TEXT _main proc near char c='a'; int i=0x1234; long j=0x5678; int val; int func(char, int, long); void main(void) { val = func(c, i, j); } _main proc near push bp mov bp,sp ; ; { ; val = func(c, i, j); ; push word ptr DGROUP:_j+2 push word ptr DGROUP:_j push word ptr DGROUP:_i mov al,byte ptr DGROUP:_c push ax call near ptr _func add sp,8 mov word ptr DGROUP:_val,ax ; ; } ; pop bp ret _main endp _TEXT ends } n-16 n-14 n-12 n-10 n-8 n-6 n-4 n-2 n n+2 n+4 Return Address . . . low word of j i c bp high word of j sp bp
  • 14. Local variables in “run-time stack” _TEXT segment byte public 'CODE' ; ; int func(char cc,int ii,long jj) ; assume cs:_TEXT _func proc near push bp mov bp,sp sub sp,4 ; ; { ; int k=0, l=1; ; mov word ptr [bp-2],0 mov word ptr [bp-4],1 char c='a'; int i=0x1234; long j=0x5678; int val; int func(char cc, int ii, long jj) { int k=0, l=1; return ii; } void main(void) { val = func(c, i, j); } ENTER Instruction mov word ptr [bp-4],1 ; ; return k; ; mov ax,word ptr [bp+6] jmp short @1@58 @1@58: ; ; } ; mov sp,bp pop bp ret _func endp ; ; void main(void) ; assume cs:_TEXT _main proc near ... _main endp _TEXT ends } n-4 n-2 n n+2 n+4 n+6 n+8 n+10 n+12 n+14 n+16 Return Address . . . low word of j =jj I =ii c =cc bp high word of j =jj Return Address sp bpbp ?? = l ?? = k Control Link bp LEAVE Instruction
  • 15. Buffer/Stack Overflow in Local Array void foo(const char* input) { char buf[10]; sprintf(buf, "Hello World, %s.n“, input); } int main(int argc, char* argv[]) { buf[3] buf[2] buf[1] buf[0]int main(int argc, char* argv[]) { foo(argv[1]); return 0; } buf[3] buf[2] buf[1] buf[0] buf[7] buf[6] buf[5] buf[4] ……………….. buf[9] buf[8]
  • 16. Buffer Overflow Prevention • Use “snprintf()” instead of “sprintf()”:  int snprintf(char *str, size_t size, const char * restrict format, ...)  int sprintf( char * str, const char * format, ... )  Refer “用 snprintf / asprintf 取代不安全的 sprintf” • Use “strncpy()” instead of “strcpy()”:• Use “strncpy()” instead of “strcpy()”:  char *strncpy(char *dest, const char * src, size_t num)  char *strcpy(char *dest, const char *src)
  • 17. Buffer Overflow Attack #include <stdio.h> #include <string.h> int main(void) { char buff[15]; int pass = 0; printf("n Enter the password : n"); gets(buff); if(strcmp(buff, "thegeekstuff")) $ ./bfrovrflw Enter the password : thegeekstuff Correct Password Run with correct password: if(strcmp(buff, "thegeekstuff")) { printf ("n Wrong Password n"); } else { printf ("n Correct Password n"); pass = 1; } if(pass) { /* Now Give root or admin rights to user*/ printf ("n Root privileges given to user n"); } return 0; } Root privileges given to the user $ ./bfrovrflw Enter the password : hhhhhhhhhhhhhhhhhhhh Wrong Password Root privileges given to the user Run with buffer overflow attack:
  • 18. /* StackOverrun.c This program shows an example of how a stack-based buffer overrun can be used to execute arbitrary code. Its objective is to find an input string that executes the function bar. */ #pragma check_stack(off) #include <string.h> #include <stdio.h> void foo(const char* input) Stack Overrun Example from Howard and LeBlanc { char buf[10]; printf("My stack looks like:n%pn%pn%pn%pn%pn% pnn"); strcpy(buf, input); printf("%sn", buf); printf("Now the stack looks like:n%pn%pn%pn%pn%pn%pnn"); } void bar(void) { printf("Augh! I've been hacked!n"); } int main(int argc, char* argv[]) { //Blatant cheating to make life easier on myself printf("Address of foo = %pn", foo); printf("Address of bar = %pn", bar); if (argc != 2) { printf("Please supply a string as an argument!n"); return -1; } foo(argv[1]); return 0; }
  • 19. File Browse in Media Player Project
  • 23. Sorting Algorithm Comparison Sorted array: Reverse sorted array:
  • 24. Stack Overflow in Recursive QSort OS_STK *QSortStkLmt; void _CalcStkLmt(void) { QSortStkLmt = OSTCBCur->OSTCBStkBottom + QSORT_STK_CONSUPT; } _CODE_ACCESS void _QSort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *)) { register char *basep = base; /* POINTER TO ARRAY OF ELEMENTS */ register unsigned i = 0; /* left scan index */ register unsigned j = nmemb - 1; /* right scan index */ register unsigned pivot = (nmemb / 2); register char *pivp = basep + (pivot * size); // prevent stack overflow. //dprintf("Stack=%xnr", GetStkPtrReg()); if(GetStkPtrReg() <= (U32)QSortStkLmt) {if(GetStkPtrReg() <= (U32)QSortStkLmt) { dprintf("nrQSortStkOv:%x, Lmt:%x:", GetStkPtrReg(), QSortStkLmt); return; } if (nmemb <= 1) return; while( i < j ) { while( (*compar) (basep + (i * size), pivp) < 0 ) ++i; while( (*compar) (basep + (j * size), pivp) > 0 ) --j; if( i < j ) { _SwapItem(basep + (i * size), basep + (j * size), size); if ( pivot == i ) { pivot = j; pivp = basep + (pivot * size); } else if( pivot == j ) { pivot = i; pivp = basep + (pivot * size); } ++i; --j; } else if ( i == j ) { ++i; --j; break; } } if( j > 0) _QSort(basep, j + 1, size, compar); if( i < nmemb-1) _QSort(basep + (i * size), nmemb - i, size, compar); }
  • 25. Critical Section Issues class Counter { private int value = 1; //counter starts at one public Counter(int c) { //constructor initializes counterpublic Counter(int c) { //constructor initializes counter value = c; } public int inc() { //increment value & return prior value int temp = value; //start of danger zone value = temp+1; //end of danger zone return temp; } }
  • 26. Critical Section Issues • The problem occurs if two threads both read the value field at the line marked “start of danger zone”, and then both update that field at the line marked “end of danger zone”.at the line marked “end of danger zone”. int temp = value; value = temp+1;
  • 27. Critical Section Issues Value 2 3 2int temp = value; value = temp+1; read 1 read 1 write 2 read 2 write 3 write 2 time
  • 28. The secret of “volatile” keyword • void dummy_loop(int cnt) { volatile int i; for (i=0; i<cnt; i++) {} }} • volatile UINT32 *reg = 0x30000000; *reg = 100; *reg = 200; *reg = 300; • What’s the result after optimization?
  • 29. Variable Allocation in C/C++ • Global variables: int var; static int var; const int var = 100;const int var = 100; • Local variables: void func(void) { int var; static int var; }
  • 31. Reduce of Program Flash Usage • How to minimize the code size to fit into the limited flash memory? – What will be put into the flash memory after program compiled/linked?program compiled/linked? – Good algorithm reduced code size. – Good coding skill reduced code size. – Optimization during compiling. => Timing changed side effect => Usage of “volatile”
  • 32. Reduce of Data Memory Usage • How to minimize the data size to fit into the limited SRAM? – Usually more precious/limited than flash memory. – Where will our data located for different kind of– Where will our data located for different kind of variables? (local vs. global vs. static vs. const) – Constant tables put into flash instead of SRAM – Compact data structure design – Local variable vs. Global variable
  • 33. Conclusion (1/2) • Embedded system is a mix domain that cover various technical fields: – Computer Programming, Assembly Language – Data Structure, Algorithm – Operating System, Compiler– Operating System, Compiler – Computer Organization & Architecture – Digital System, Electrical Circuits – Microprocessor Systems – Digital Signal Processing – Specific Industry Domain Knowledge.
  • 34. Conclusion (2/2) • Workaround ≠ Solution • 工作年資 ≠ 經驗累積 • 成為嵌入式系統達人的必要條件: –– 廣泛的專業知識 – 敏銳的觀察力 – 追根究底的精神. – 面對問題的積極態度
  • 35. Q & A Thank You