computerorganizaon)kovan.ceng.metu.edu.tr/~erol/courses/ceng331/2012/ceng331-2012-w… ·...
TRANSCRIPT
-
Computer Organiza0on CENG331 Sec+on 3, Fall 2012-‐2013 1st Lecture
Instructor:
Erol Şahin
Acknowledgement: Most of the slides are adapted from the ones prepared
by R.E. Bryant, D.R. O’Hallaron, G. Kesden and Markus Püschel of
Carnegie-‐Mellon Univ.
-
Overview
Course theme
Five reali0es How the course fits into the CENG curriculum
Logis0cs
-
Course Theme: Abstrac0on Is Good But Don’t Forget Reality Most CENG courses emphasize abstrac0on
Abstract data types Asympto+c analysis
These abstrac0ons have limits Especially in the presence of bugs Need to understand details of underlying implementa+ons
Useful outcomes Become more effec+ve programmers
Able to find and eliminate bugs efficiently
Able to understand and tune for program performance
Prepare for later “systems” classes in CENG Compilers, Opera+ng Systems, Networks, Embedded Systems
-
Great Reality #1: Int’s are not Integers, Float’s are not Reals
Example 1: Is x2 ≥ 0? Float’s: Yes! Int’s:
40000 * 40000 -‐-‐> 1600000000
50000 * 50000 -‐-‐> ??
Example 2: Is (x + y) + z = x + (y + z)? Unsigned & Signed Int’s: Yes! Float’s:
(1e20 + -‐1e20) + 3.14 -‐-‐> 3.14
1e20 + (-‐1e20 + 3.14) -‐-‐> ??
-
Code Security Example
Similar to code found in FreeBSD’s implementa0on of getpeername
There are legions of smart people trying to find vulnerabili0es in programs
/* Kernel memory region holding user-accessible data */ #define KSIZE 1024 char kbuf[KSIZE];
/* Copy at most maxlen bytes from kernel region to user buffer */ int copy_from_kernel(void *user_dest, int maxlen) { /* Byte count len is minimum of buffer size and maxlen */ int len = KSIZE < maxlen ? KSIZE : maxlen; memcpy(user_dest, kbuf, len); return len; }
-
Typical Usage
/* Kernel memory region holding user-accessible data */ #define KSIZE 1024 char kbuf[KSIZE];
/* Copy at most maxlen bytes from kernel region to user buffer */ int copy_from_kernel(void *user_dest, int maxlen) { /* Byte count len is minimum of buffer size and maxlen */ int len = KSIZE < maxlen ? KSIZE : maxlen; memcpy(user_dest, kbuf, len); return len; }
#define MSIZE 528
void getstuff() { char mybuf[MSIZE]; copy_from_kernel(mybuf, MSIZE); printf(“%s\n”, mybuf); }
-
Malicious Usage
/* Kernel memory region holding user-accessible data */ #define KSIZE 1024 char kbuf[KSIZE];
/* Copy at most maxlen bytes from kernel region to user buffer */ int copy_from_kernel(void *user_dest, int maxlen) { /* Byte count len is minimum of buffer size and maxlen */ int len = KSIZE < maxlen ? KSIZE : maxlen; memcpy(user_dest, kbuf, len); return len; }
#define MSIZE 528
void getstuff() { char mybuf[MSIZE]; copy_from_kernel(mybuf, -MSIZE); . . . }
-
Computer Arithme0c
Does not generate random values Arithme+c opera+ons have important mathema+cal proper+es
Cannot assume all “usual” mathema0cal proper0es Due to finiteness of representa+ons Integer opera+ons sa+sfy “ring” proper+es
Commuta+vity, associa+vity, distribu+vity
Floa+ng point opera+ons sa+sfy “ordering” proper+es Monotonicity, values of signs
Observa0on Need to understand which abstrac+ons apply in which contexts Important issues for compiler writers and serious applica+on
programmers
-
Great Reality #2: You’ve Got to Know Assembly Chances are, you’ll never write program in assembly
Compilers are much beher & more pa+ent than you are But: Understanding assembly key to machine-‐level
execu0on model Behavior of programs in presence of bugs
High-‐level language model breaks down
Tuning program performance Understand op+miza+ons done/not done by the compiler
Understanding sources of program inefficiency
Implemen+ng system solware Compiler has machine code as target
Opera+ng systems must manage process state Crea+ng / figh+ng malware
x86 assembly is the language of choice!
-
Assembly Code Example
Time Stamp Counter Special 64-‐bit register in Intel-‐compa+ble machines Incremented every clock cycle Read with rdtsc instruc+on
Applica0on Measure +me (in clock cycles) required by procedure
double t; start_counter(); P(); t = get_counter(); printf("P required %f clock cycles\n", t);
-
Code to Read Counter
Write small amount of assembly code using GCC’s asm facility
Inserts assembly code into machine code generated by compiler
static unsigned cyc_hi = 0; static unsigned cyc_lo = 0;
/* Set *hi and *lo to the high and low order bits of the cycle counter. */ void access_counter(unsigned *hi, unsigned *lo) { asm("rdtsc; movl %%edx,%0; movl %%eax,%1"
: "=r" (*hi), "=r" (*lo) : : "%edx", "%eax");
}
asm ( “assembly instructions”! : output operands //optional! : input operands //optional! : list of clobbered regs //opt..!);!
-
Great Reality #3: Memory Maaers Random Access Memory Is an Unphysical Abstrac0on
-
Memory Referencing Bug Example
double fun(int i) { volatile double d[1] = {3.14}; volatile long int a[2]; a[i] = 1073741824; /* Possibly out of bounds */ return d[0]; }
fun(0) –> 3.14 fun(1) –> 3.14 fun(2) –> 3.1399998664856 fun(3) –> 2.00000061035156 fun(4) –> 3.14, then segmentation fault
volatile keyword is intended to prevent the compiler from applying any optimizations on the code that assume values of variables cannot change "on their own."
-
Memory Referencing Bug Example double fun(int i) { volatile double d[1] = {3.14}; volatile long int a[2]; a[i] = 1073741824; /* Possibly out of bounds */ return d[0]; }
fun(0) –> 3.14 fun(1) –> 3.14 fun(2) –> 3.1399998664856 fun(3) –> 2.00000061035156 fun(4) –> 3.14, then segmentation fault
Saved State
d7 … d4
d3 … d0
a[1]
a[0] 0
1
2
3
4
Loca0on accessed by fun(i)
Explana0on:
-
Memory Referencing Errors C and C++ do not provide any memory protec0on
Out of bounds array references Invalid pointer values Abuses of malloc/free
Can lead to nasty bugs Whether or not bug has any effect depends on system and compiler Ac+on at a distance
Corrupted object logically unrelated to one being accessed
Effect of bug may be first observed long aler it is generated
How can I deal with this? Program in Java or ML Understand what possible interac+ons may occur Use or develop tools to detect referencing errors
-
Memory System Performance Example
Hierarchical memory organiza0on
Performance depends on access paaerns Including how step through mul+-‐dimensional array
void copyji(int src[2048][2048], int dst[2048][2048]) { int i,j; for (j = 0; j < 2048; j++) for (i = 0; i < 2048; i++) dst[i][j] = src[i][j]; }
void copyij(int src[2048][2048], int dst[2048][2048]) { int i,j; for (i = 0; i < 2048; i++) for (j = 0; j < 2048; j++) dst[i][j] = src[i][j]; }
21 0mes slower (Pen0um 4)
-
The Memory Mountain
64M
8M 1M
128K
16K
2K 0
1000
2000
3000
4000
5000
6000
7000
s1
s3
s5
s7
s9
s11
s13
s15
s32 Size (bytes)
Rea
d th
roug
hput
(MB
/s)
Stride (x8 bytes)
L1"
L2"
Mem"
L3"
copyij
copyji
Intel Core i7"2.67 GHz"32 KB L1 d-cache"256 KB L2 cache"8 MB L3 cache"
-
Great Reality #4: There’s more to performance than asympto0c complexity
Constant factors maaer too!
And even exact op count does not predict performance Easily see 10:1 performance range depending on how code wrihen Must op+mize at mul+ple levels: algorithm, data representa+ons,
procedures, and loops
Must understand system to op0mize performance How programs compiled and executed How to measure program performance and iden+fy bohlenecks How to improve performance without destroying code modularity
and generality
-
Example Matrix Mul0plica0on
Standard desktop computer, vendor compiler, using op0miza0on flags
Both implementa0ons have exactly the same opera0ons count (2n3)
What is going on?
160x
Triple loop
Best code (K. Goto)
-
MMM Plot: Analysis
Memory hierarchy and other optimizations: 20x
Vector instructions: 4x
Multiple threads: 4x
Reason for 20x: Blocking or 0ling, loop unrolling, array scalariza0on, instruc0on scheduling, search to find best choice
Effect: less register spills, less L1/L2 cache misses, less TLB misses
-
Great Reality #5: Computers do more than execute programs
They need to get data in and out I/O system cri+cal to program reliability and performance
They communicate with each other over networks Many system-‐level issues arise in presence of network
Concurrent opera+ons by autonomous processes Coping with unreliable media
Cross plarorm compa+bility
Complex performance issues
-
Role within CENG Curriculum
CENG331
CENG334 Opera0ng Systems
CS 444 Compilers
Processes Mem. Mgmt
CENG336 Embedded Systems
CENG140 C(++) Programming
CS 352 Databases
Data Reps. Memory Model
CS 477 Computer Graphics
Machine Code Arithme0c
Computer Organiza@on
Execu0on Model Memory System
-
Course Perspec0ve
Most Systems Courses are Builder-‐Centric Computer Architecture
Design pipelined processor in Verilog Opera+ng Systems
Implement large por+ons of opera+ng system
Compilers Write compiler for simple language
Networking Implement and simulate network protocols
-
Course Perspec0ve (Cont.)
Our Course is Programmer-‐Centric Purpose is to show how by knowing more about the underlying
system, one can be more effec+ve as a programmer
Enable you to Write programs that are more reliable and efficient
Not just a course for dedicated hackers We bring out the hidden hacker in everyone
Cover material in this course that you won’t see elsewhere
-
Teaching staff Instructor
Dr. Erol Sahin Loca+on: B-‐111, Tel: 210 5539,
E-‐mail: [email protected]
Office hours: By appointment.
TA’s Fa+h Gokce (E-‐mail: [email protected]) Asli Genctav (E-‐mail: [email protected])
-
Textbooks
Randal E. Bryant and David R. O’Hallaron, “Computer Systems: A Programmer’s
Perspec+ve, Second Edi+on”, Pren+ce Hall 2011.
hhp://csapp.cs.cmu.edu This book really mahers for the
course!
How to solve labs
Prac+ce problems typical of exam problems
-
Course Components
Lectures Higher level concepts
Assignments (3) The heart of the course Provide in-‐depth understanding of an aspect of systems Programming and measurement
Exams (midterm + final) Test your understanding of concepts & mathema+cal principles
-
Policies: Grading
Midterm 1: 25%. Midterm 2: 25% Assignments: 20%.
4 homeworks Precondi+on for entering final exam:
Accumulate 25/100 overall from midterms and homeworks
Final: 30%.
-
Assignments 1. Binary bomb:
Defuse a binary bomb by disassembling and reverse engineering the program.
2. Buffer overflow: Modify the run-‐+me behaviour of a binary executable by using the
buffer overflow bug.
3. Architecture: Modify the HCL descrip+on of a processor to add new instruc+ons.
4. Performance: Op+mize the performance of a func+on.
Details regarding the scheduling and grading of these assignments will be announced later.
-
Assignment Ra0onale
Each assignment should have a well-‐defined goal such as solving a puzzle or winning a contest.
Doing an assignment should result in new skills and concepts
We try to use compe00on in a fun and healthy way. Set a reasonable threshold for full credit. Post intermediate results (anonymized) on Web page for glory!
-
Communica0on Class Web Pages
Web: hhp://kovan.ceng.metu.edu.tr/~erol/Courses/CENG331 Copies of lectures, exams, solu+ons
hhp://cow.ceng.metu.edu.tr/ Assignments, grades etc.
Newsgroup news://metu.ceng.course.331 Announcements about the course, clarifica+ons to assignments,
general discussion
Communica0on Ques+ons that are general should be posted to the newsgroup. Please
put [Sec+on 3 ] on the subject line of your pos+ng. If you have a specific ques+on you can send an e-‐mail to the instructors
or to your teaching assistants. However make sure that the subject line starts with CENG331 [capital lehers, and no spaces] to get faster reply.
-
Policies
Late assignments: Late submission policy will be announced for each assignment.
Academic dishonesty: All assignments submihed should be fully your own. We have a
zero tolerance policy on chea+ng and plagiarism. Your work will be regularly checked for such misconduct and persecuted.
We would like to remind you that, if found guilty, the legal code of the university proposes a minimum of six month expulsion from the university.
-
Chea0ng What is chea0ng?
Sharing code: either by copying, retyping, looking at, or supplying a copy of a file.
Coaching: helping your friend to write a lab, line by line. Copying code from previous course or from elsewhere on WWW
Only allowed to use code we supply, or from CS:APP website
What is NOT chea0ng? Explaining how to use systems or tools. Helping others with high-‐level design issues.
Penalty for chea0ng: Removal from course with failing grade.
Detec0on of chea0ng: We do check and our tools for doing this are much beher than you
think!
-
If you don’t want to cry at the end of the semester..
-
We’ll have fun!
-
Conclusion
5 Great Reali0es Ints are not Integers, Floats are not Reals You’ve Got to Know Assembly Memory Mahers There’s more to performance than asympto+c complexity Computers do more than execute programs
Abstrac+on Is Good But Don’t Forget Reality
-
A Tour of Computer Systems CENG331 Sec+on 1 & 2, Fall 2011-‐2012
Instructor:
Erol Şahin
Acknowledgement: Most of the slides are adapted from the ones prepared
by R.E. Bryant, D.R. O’Hallaron of Carnegie-‐Mellon Univ.
-
hello.c
#include
int main() {
printf(“Hello World”);
}
-
Compila0on of hello.c
Pre-"processor"
(cpp) "hello.i Compiler"
(cc1) "hello.s Assembler"
(as) "hello.o Linker"
(ld) "hello hello.c
Source!program!
(text)!Modified!source!
program!(text)!
Assembly!program!
(text)!Relocatable!
object!programs!(binary)!
Executable!object!
program!(binary)!
printf.o
-
Preprocessing
Pre-"processor"
(cpp) "hello.i hello.c
Source!program!
(text)!Modified!source!
program!(text)!
#include
int main() { printf(“Hello World”);
}
# 1 "hello.c"
# 1 "" # 1 "" # 1 "hello.c" # 1 "/usr/include/stdio.h" 1 3 4 …………………………………….. typedef unsigned char __u_char; typedef unsigned short int __u_short; typedef unsigned int __u_int; typedef unsigned long int __u_long; ……………………………………….. int main() {
printf(“Hello World”); }
cpp hello.c > hello.i"
-
Compiler # 1 "hello.c"!
# 1 ""!
# 1 ""!
# 1 "hello.c"!
# 1 "/usr/include/stdio.h" 1 3 4!
……………………………………..!
typedef unsigned char __u_char;!
typedef unsigned short int __u_short;!
typedef unsigned int __u_int;!
typedef unsigned long int __u_long;!
………………………………………..!
int main() {!
!printf(“Hello World”);!
}!
gcc -Wall -S hello.i > hello.s"
Compiler"(cc1) "
hello.s hello.i
.file "hello.c"! .section .rodata!.LC0:! .string "Hello World"! .text!.globl main! .type main, @function!main:! pushl %ebp! movl %esp, %ebp! subl $8, %esp! andl $-16, %esp! movl $0, %eax! addl $15, %eax! addl $15, %eax! shrl $4, %eax! sall $4, %eax! subl %eax, %esp! subl $12, %esp! pushl $.LC0! call printf! addl $16, %esp! leave! ret! .size main, .-main! .section .note.GNU-stack,"",@progbits! .ident "GCC: (GNU) 3.4.1"!
-
Assembler
as hello.s -o hello.o "
.file "hello.c"! .section .rodata!.LC0:! .string "Hello World"! .text!.globl main! .type main, @function!main:! pushl %ebp! movl %esp, %ebp! subl $8, %esp! andl $-16, %esp! movl $0, %eax! addl $15, %eax! addl $15, %eax! shrl $4, %eax! sall $4, %eax! subl %eax, %esp! subl $12, %esp! pushl $.LC0! call printf! addl $16, %esp! leave! ret! .size main, .-main! .section .note.GNU-stack,"",@progbits! .ident "GCC: (GNU) 3.4.1"!
hello.s Assembler"(as) "
hello.o
0000500 nul nul nul nul esc nul nul nul ht nul nul nul nul nul nul nul!0000520 nul nul nul nul d etx nul nul dle nul nul nul ht nul nul nul!0000540 soh nul nul nul eot nul nul nul bs nul nul nul % nul nul nul!0000560 soh nul nul nul etx nul nul nul nul nul nul nul d nul nul nul!0000600 nul nul nul nul nul nul nul nul nul nul nul nul eot nul nul nul!0000620 nul nul nul nul + nul nul nul bs nul nul nul etx nul nul nul!0000640 nul nul nul nul d nul nul nul nul nul nul nul nul nul nul nul!0000660 nul nul nul nul eot nul nul nul nul nul nul nul 0 nul nul nul!0000700 soh nul nul nul stx nul nul nul nul nul nul nul d nul nul nul!0000720 ff nul nul nul nul nul nul nul nul nul nul nul soh nul nul nul!0000740 nul nul nul nul 8 nul nul nul soh nul nul nul nul nul nul nul!0000760 nul nul nul nul p nul nul nul nul nul nul nul nul nul nul nul!0001000 nul nul nul nul soh nul nul nul nul nul nul nul H nul nul nul!0001020 soh nul nul nul nul nul nul nul nul nul nul nul p nul nul nul!0001040 2 nul nul nul nul nul nul nul nul nul nul nul soh nul nul nul!0001060 nul nul nul nul dc1 nul nul nul etx nul nul nul nul nul nul nul!0001100 nul nul nul nul " nul nul nul Q nul nul nul nul nul nul nul!0001120 nul nul nul nul soh nul nul nul nul nul nul nul soh nul nul nul!0001140 stx nul nul nul nul nul nul nul nul nul nul nul , stx nul nul!0001160 sp nul nul nul nl nul nul nul bs nul nul nul eot nul nul nul!0001200 dle nul nul nul ht nul nul nul etx nul nul nul nul nul nul nul!0001220 nul nul nul nul L etx nul nul nak nul nul nul nul nul nul nul!0001240 nul nul nul nul soh nul nul nul nul nul nul nul nul nul nul nul!0001260 nul nul nul nul nul nul nul nul nul nul nul nul soh nul nul nul!0001300 nul nul nul nul nul nul nul nul eot nul q del nul nul nul nul!0001320 nul nul nul nul nul nul nul nul etx nul soh nul nul nul nul nul!0001340 nul nul nul nul nul nul nul nul etx nul etx nul nul nul nul nul!0001360 nul nul nul nul nul nul nul nul etx nul eot nul nul nul nul nul!0001400 nul nul nul nul nul nul nul nul etx nul enq nul nul nul nul nul!0001420 nul nul nul nul nul nul nul nul etx nul ack nul nul nul nul nul!0001440 nul nul nul nul nul nul nul nul etx nul bel nul ht nul nul nul!0001460 nul nul nul nul . nul nul nul dc2 nul soh nul so nul nul nul!0001500 nul nul nul nul nul nul nul nul dle nul nul nul nul h e l!0001520 l o . c nul m a i n nul p r i n t f!0001540 nul nul nul nul sp nul nul nul soh enq nul nul % nul nul nul!0001560 stx ht nul nul!0001564!
od –a hello.o"
-
Linker
0000500 nul nul nul nul esc nul nul nul ht nul nul nul nul nul nul nul!0000520 nul nul nul nul d etx nul nul dle nul nul nul ht nul nul nul!0000540 soh nul nul nul eot nul nul nul bs nul nul nul % nul nul nul!0000560 soh nul nul nul etx nul nul nul nul nul nul nul d nul nul nul!0000600 nul nul nul nul nul nul nul nul nul nul nul nul eot nul nul nul!0000620 nul nul nul nul + nul nul nul bs nul nul nul etx nul nul nul!0000640 nul nul nul nul d nul nul nul nul nul nul nul nul nul nul nul!0000660 nul nul nul nul eot nul nul nul nul nul nul nul 0 nul nul nul!0000700 soh nul nul nul stx nul nul nul nul nul nul nul d nul nul nul!0000720 ff nul nul nul nul nul nul nul nul nul nul nul soh nul nul nul!0000740 nul nul nul nul 8 nul nul nul soh nul nul nul nul nul nul nul!0000760 nul nul nul nul p nul nul nul nul nul nul nul nul nul nul nul!0001000 nul nul nul nul soh nul nul nul nul nul nul nul H nul nul nul!0001020 soh nul nul nul nul nul nul nul nul nul nul nul p nul nul nul!0001040 2 nul nul nul nul nul nul nul nul nul nul nul soh nul nul nul!0001060 nul nul nul nul dc1 nul nul nul etx nul nul nul nul nul nul nul!0001100 nul nul nul nul " nul nul nul Q nul nul nul nul nul nul nul!0001120 nul nul nul nul soh nul nul nul nul nul nul nul soh nul nul nul!0001140 stx nul nul nul nul nul nul nul nul nul nul nul , stx nul nul!0001160 sp nul nul nul nl nul nul nul bs nul nul nul eot nul nul nul!0001200 dle nul nul nul ht nul nul nul etx nul nul nul nul nul nul nul!0001220 nul nul nul nul L etx nul nul nak nul nul nul nul nul nul nul!0001240 nul nul nul nul soh nul nul nul nul nul nul nul nul nul nul nul!0001260 nul nul nul nul nul nul nul nul nul nul nul nul soh nul nul nul!0001300 nul nul nul nul nul nul nul nul eot nul q del nul nul nul nul!0001320 nul nul nul nul nul nul nul nul etx nul soh nul nul nul nul nul!0001340 nul nul nul nul nul nul nul nul etx nul etx nul nul nul nul nul!0001360 nul nul nul nul nul nul nul nul etx nul eot nul nul nul nul nul!0001400 nul nul nul nul nul nul nul nul etx nul enq nul nul nul nul nul!0001420 nul nul nul nul nul nul nul nul etx nul ack nul nul nul nul nul!0001440 nul nul nul nul nul nul nul nul etx nul bel nul ht nul nul nul!0001460 nul nul nul nul . nul nul nul dc2 nul soh nul so nul nul nul!0001500 nul nul nul nul nul nul nul nul dle nul nul nul nul h e l!0001520 l o . c nul m a i n nul p r i n t f!0001540 nul nul nul nul sp nul nul nul soh enq nul nul % nul nul nul!0001560 stx ht nul nul!0001564!
od –a hello"
0000000 del E L F soh soh soh nul nul nul nul nul nul nul nul nul!0000020 stx nul etx nul soh nul nul nul @ stx eot bs 4 nul nul nul!0000040 X cr nul nul nul nul nul nul 4 nul sp nul bel nul ( nul!0000060 ! nul rs nul ack nul nul nul 4 nul nul nul 4 nul eot bs!0000100 4 nul eot bs ` nul nul nul ` nul nul nul enq nul nul nul!0000120 eot nul nul nul etx nul nul nul dc4 soh nul nul dc4 soh eot bs!0000140 dc4 soh eot bs dc3 nul nul nul dc3 nul nul nul eot nul nul nul!0000160 soh nul nul nul soh nul nul nul nul nul nul nul nul nul eot bs!0000200 nul nul eot bs bs eot nul nul bs eot nul nul enq nul nul nul!0000220 nul dle nul nul soh nul nul nul bs eot nul nul bs dc4 eot bs!0000240 bs dc4 eot bs nul soh nul nul eot soh nul nul ack nul nul nul!0000260 nul dle nul nul stx nul nul nul dc4 eot nul nul dc4 dc4 eot bs!0000300 dc4 dc4 eot bs H nul nul nul H nul nul nul ack nul nul nul!0000320 eot nul nul nul eot nul nul nul ( soh nul nul ( soh eot bs!0000340 ( soh eot bs sp nul nul nul sp nul nul nul eot nul nul nul!0000360 eot nul nul nul Q e t d nul nul nul nul nul nul nul nul!0000400 nul nul nul nul nul nul nul nul nul nul nul nul ack nul nul nul!0000420 eot nul nul nul / l i b / l d - l i n u!0000440 x . s o . 2 nul nul eot nul nul nul dle nul nul nul!0000460 soh nul nul nul G N U nul nul nul nul nul stx nul nul nul!0000500 stx nul nul nul enq nul nul nul etx nul nul nul ack nul nul nul!0000520 enq nul nul nul soh nul nul nul etx nul nul nul nul nul nul nul!0000540 nul nul nul nul nul nul nul nul stx nul nul nul nul nul nul nul!……………………………………………………………………………..!
hello.o Linker"(ld) "
hello
Relocatable!object!
programs!(binary)!
Executable!object!
program!(binary)!
printf.o
gcc hello.o –o hello"
-
Finally…
$ gcc hello.o -o hello
$ ./hello
Hello World$
-
How do you say “Hello World”?
-
Typical Organiza0on of System
Main"memory"
I/O "bridge"Bus interface"
ALU"
Register file"CPU"
System bus" Memory bus"
Disk "controller"
Graphics"adapter"
USB"controller"
Mouse"Keyboard" Display"Disk"
I/O bus"Expansion slots for"other devices such"as network adapters"
hello executable !stored on disk!
PC"
-
Main"memory"
I/O "bridge"Bus interface"
ALU"
Register file"
CPU"
System bus" Memory bus"
Disk "controller"
Graphics"adapter"
USB"controller"
Mouse"Keyboard" Display"Disk"
I/O bus"Expansion slots for"other devices such"as network adapters"
PC"
"hello"!
User!types!
"hello"!
Reading hello command from keyboard
-
Byte-‐Oriented Memory Organiza0on
Programs Refer to Virtual Addresses Conceptually very large array of bytes Actually implemented with hierarchy of different memory types System provides address space private to par+cular “process”
Program being executed
Program can clobber its own data, but not that of others
Compiler + Run-‐Time System Control Alloca0on Where different program objects should be stored All alloca+on within single virtual address space
• • •"
-
Machine Words
Machine Has “Word Size” Nominal size of integer-‐valued data
Including addresses Most current machines use 32 bits (4 bytes) words
Limits addresses to 4GB
Becoming too small for memory-‐intensive applica+ons
High-‐end systems use 64 bits (8 bytes) words Poten+al address space ≈ 1.8 X 1019 bytes x86-‐64 machines support 48-‐bit addresses: 256 Terabytes
Machines support mul+ple data formats Frac+ons or mul+ples of word size
Always integral number of bytes
-
Word-‐Oriented Memory Organiza0on
Addresses Specify Byte Loca0ons Address of first byte in word Addresses of successive words differ
by 4 (32-‐bit) or 8 (64-‐bit)
0000 0001 0002 0003 0004 0005 0006 0007 0008 0009 0010 0011
32-bit"Words" Bytes" Addr."
0012 0013 0014 0015
64-bit"Words"
Addr "="??
Addr "="??
Addr "="??
Addr "="??
Addr "="??
Addr "="??
0000
0004
0008
0012
0000
0008
-
Data Representa0ons
C Data Type Typical 32-bit Intel IA32 x86-64
char 1 1 1
short 2 2 2
int 4 4 4
long 4 4 8
long long 8 8 8
float 4 4 4
double 8 8 8
long double 8 10/12 10/16
pointer 4 4 8
-
Byte Ordering
How should bytes within a mul0-‐byte word be ordered in memory?
Conven0ons Big Endian: Sun, PPC Mac, Internet
Least significant byte has highest address
Lihle Endian: x86 Least significant byte has lowest address
-
Byte Ordering Example
Big Endian Least significant byte has highest address
Liale Endian Least significant byte has lowest address
Example Variable x has 4-‐byte representa+on 0x01234567 Address given by &x is 0x100
0x100 0x101 0x102 0x103
01 23 45 67
0x100 0x101 0x102 0x103
67 45 23 01
Big Endian"
Little Endian"
01 23 45 67
67 45 23 01
-
The origin of the word Endian from Wikipedia
http://sisu.typepad.com/sisu/images/gulliver.jpg
http://www.tallstories.org.uk/shows/other/the-egg.jpg
-
Address "Instruction Code "Assembly Rendition" 8048365: 5b pop %ebx 8048366: 81 c3 ab 12 00 00 add $0x12ab,%ebx 804836c: 83 bb 28 00 00 00 00 cmpl $0x0,0x28(%ebx)
Reading Byte-‐Reversed Lis0ngs
Disassembly Text representa+on of binary machine code Generated by program that reads the machine code
Example Fragment
Deciphering Numbers Value: 0x12ab Pad to 32 bits: 0x000012ab Split into bytes: 00 00 12 ab Reverse: ab 12 00 00
-
Examining Data Representa0ons
Code to Print Byte Representa0on of Data Cas+ng pointer to unsigned char * creates byte array
Printf directives:"%p: "Print pointer"%x: "Print Hexadecimal"
typedef unsigned char *pointer;!
void show_bytes(pointer start, int len){! int i;! for (i = 0; i < len; i++)! printf(”%p\t0x%.2x\n",start+i, start[i]);! printf("\n");!}!
-
show_bytes Execu0on Example
int a = 15213; printf("int a = 15213;\n"); show_bytes((pointer) &a, sizeof(int));
Result (Linux):"int a = 15213; 0x11ffffcb8 0x6d 0x11ffffcb9 0x3b 0x11ffffcba 0x00 0x11ffffcbb 0x00
-
Represen0ng Integers Decimal: "15213
Binary: 0011 1011 0110 1101 Hex: 3 B 6 D
6D 3B 00 00
IA32, x86-64"
3B 6D
00 00
Sun"
int A = 15213;
93 C4 FF FF
IA32, x86-64"
C4 93
FF FF
Sun"
Twoʼs complement representation"(Covered later)"
int B = -15213;
long int C = 15213;
00 00 00 00
6D 3B 00 00
x86-64"
3B 6D
00 00
Sun"
6D 3B 00 00
IA32"
-
Represen0ng Pointers
Different compilers & machines assign different loca+ons to objects
int B = -15213; int *P = &B;
x86-64"Sun" IA32"EFFFFB2C
D4F8FFBF
0C89ECFFFF7F0000
-
Represen0ng Strings
Strings in C Represented by array of characters Each character encoded in ASCII format
Standard 7-‐bit encoding of character set
Character “0” has code 0x30
– Digit i has code 0x30+i String should be null-‐terminated
Final character = 0
Compa0bility Byte ordering not an issue
Linux/Alpha" Sun"
313832343300
313832343300
-
Boolean Algebra
Developed by George Boole in 19th Century Algebraic representa+on of logic
Encode “True” as 1 and “False” as 0
And A&B = 1 when both A=1 and B=1
Or A|B = 1 when either A=1 or B=1
Not ~A = 1 when A=0
Exclusive-‐Or (Xor) A^B = 1 when either A=1 or B=1, but not both
-
Applica0on of Boolean Algebra
Applied to Digital Systems by Claude Shannon 1937 MIT Master’s Thesis Reason about networks of relay switches
Encode closed switch as 1, open switch as 0
A"
~A"
~B"
B"
Connection when"
A&~B | ~A&B"
A&~B"
~A&B" = A^B"
-
General Boolean Algebras
Operate on Bit Vectors Opera+ons applied bitwise
All of the Proper0es of Boolean Algebra Apply
01101001 & 01010101 01000001
01101001 | 01010101 01111101
01101001 ^ 01010101 00111100
~ 01010101 10101010 01000001 01111101 00111100 10101010
-
Represen0ng & Manipula0ng Sets
Representa0on Width w bit vector represents subsets of {0, …, w–1} a[j] = 1 if j ∈ A
01101001 { 0, 3, 5, 6 }
76543210
01010101 { 0, 2, 4, 6 } 76543210
Opera0ons & Intersec+on 01000001 { 0, 6 } | Union 01111101 { 0, 2, 3, 4, 5, 6 } ̂ Symmetric difference 00111100 { 2, 3, 4, 5 } ~ Complement 10101010 { 1, 3, 5, 7 }
-
Bit-‐Level Opera0ons in C
Opera0ons &, |, ~, ^ Available in C Apply to any “integral” data type
long, int, short, char, unsigned View arguments as bit vectors Arguments applied bit-‐wise
Examples (Char data type) ~0x41 ➙ 0xBE
~010000012 ➙ 101111102 ~0x00 ➙ 0xFF
~000000002 ➙ 111111112 0x69 & 0x55 ➙ 0x41
011010012 & 010101012 ➙ 010000012 0x69 | 0x55 ➙ 0x7D
011010012 | 010101012 ➙ 011111012
-
Contrast: Logic Opera0ons in C
Contrast to Logical Operators &&, ||, !
View 0 as “False” Anything nonzero as “True”
Always return 0 or 1
Early termina+on
Examples (char data type) !0x41 ➙ 0x00 !0x00 ➙ 0x01 !!0x41 ➙ 0x01
0x69 && 0x55 ➙ 0x01 0x69 || 0x55 ➙ 0x01 p && *p (avoids null pointer access)
-
Shio Opera0ons
Leo Shio: x > y Shil bit-‐vector x right y posi+ons
Throw away extra bits on right Logical shil
Fill with 0’s on lel Arithme+c shil
Replicate most significant bit on right
Undefined Behavior Shil amount < 0 or ≥ word size
01100010 Argument x
00010000 > 2
00011000 Arith. >> 2
10100010 Argument x
00010000 > 2
11101000 Arith. >> 2
00010000 00010000
00011000 00011000
00011000 00011000
00010000
00101000
11101000
00010000
00101000
11101000
C, however, has only one right shift operator, >>. Many C compilers choose which right shift to perform depending on what type of integer is being shifted; often signed integers are shifted using the arithmetic shift, and unsigned integers are shifted using the logical shift.
-
Swap
Challenge: Can you code swap func+on without using a temporary variable?
Hint: Use bitwise XOR (^)
void swap(int *x, int *y)
{ int temp; temp = *x; *x = *y; *y = temp;
}
-
Swapping with Xor
Bitwise Xor is a form of addi+on
With extra property that every value is its own addi+ve inverse
A ^ A = 0
B A Begin B A^B 1 (A^B)^B = A A^B 2 A (A^B)^A = B 3 A B End
*y *x
-
What’s the story behind C and UNIX?