bitwise operators - george mason university

28
Page ‹#› Bitwise Operators Symbol Operation Usage Precedence Assoc ~ bitwise NOT ~x 4 r-to-l << left shift x << y 8 l-to-r >> right shift x >> y 8 l-to-r & bitwise AND x & y 11 l-to-r ^ bitwise XOR x ^ y 12 l-to-r | bitwise OR x | y 13 l-to-r Operate on variables bit-by-bit. Like LC-3 AND and NOT instructions. Shift operations are logical (not arithmetic). Operate on values -- neither operand is changed. fread and fwrite Binary files are read and written using fread() and fwrite() size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream) size_t fwrite(void *ptr, size_t size, size_t nmemb, FILE *stream) The function fread() reads nmemb objects, each size bytes long, from the stream pointed to by stream, storing them at the location given by ptr. The function fwrite() writes nmemb objects, each size bytes long, to the stream pointed to by stream, obtaining them from the location given by ptr Both functions advance the file position indicator for the stream by the number of bytes read or written. They return the number of objects read or written. If an error occurs, or the end-of-file is reached, the return value is a short object count (or zero).

Upload: others

Post on 03-Feb-2022

4 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Bitwise Operators - George Mason University

Page ‹#›

Bitwise OperatorsSymbol Operation Usage Precedence Assoc

~ bitwise NOT ~x 4 r-to-l<< left shift x << y 8 l-to-r>> right shift x >> y 8 l-to-r& bitwise AND x & y 11 l-to-r^ bitwise XOR x ^ y 12 l-to-r| bitwise OR x | y 13 l-to-r

Operate on variables bit-by-bit.• Like LC-3 AND and NOT instructions.

Shift operations are logical (not arithmetic).Operate on values -- neither operand is changed.

fread and fwriteBinary files are read and written using fread() and fwrite()

size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream)

size_t fwrite(void *ptr, size_t size, size_t nmemb, FILE *stream)

The function fread() reads nmemb objects, each size bytes long, from thestream pointed to by stream, storing them at the location given by ptr.The function fwrite() writes nmemb objects, each size bytes long, to thestream pointed to by stream, obtaining them from the location given by ptrBoth functions advance the file position indicator for the stream by thenumber of bytes read or written. They return the number of objects read orwritten. If an error occurs, or the end-of-file is reached, the return value is ashort object count (or zero).

Page 2: Bitwise Operators - George Mason University

Page ‹#›

Example showing using of fread() and fwrite() to read andwrite blocks of binary data

#include <stdio.h>

int main()

{

int row, column; FILE *my_stream; int close_error; char my_filename[] = "my_numbers.dat"; size_t object_size = sizeof(int): size_t object_count = 25; size_t op_return;

Example cont’dint my_array[5][5] = { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50 }; printf ("Initial values of array:\n"); for (row = 0; row <= 4; row++) { for (column = 0; column <=4; column++)

printf ("%d ", my_array[row][column]); printf ("\n"); }

Page 3: Bitwise Operators - George Mason University

Page ‹#›

my_stream = fopen (my_filename, "w"); op_return = fwrite (&my_array, object_size, object_count, my_stream); if (op_return != object_count) printf ("Error writing data to file.\n"); else printf ("Successfully wrote data to file.\n");

/* Close stream; skip error-checking for brevity of example */ fclose (my_stream); printf ("Zeroing array...\n"); for (row = 0; row <= 4; row++) for (column = 0; column <=4; column++) {

my_array[row][column] = 0; printf ("%d ", my_array[row][column]);

} printf ("\n"); }

Example cont’d

printf ("Now reading data back in...\n");my_stream = fopen (my_filename, "r"); op_return = fread (&my_array, object_size, object_count, my_stream); if (op_return != object_count) { printf ("Error reading data from file.\n"); } else printf ("Successfully read data from file.\n"); for (row = 0; row <= 4; row++) for (column = 0; column <=4; column++) {

printf ("%d ", my_array[row][column]); printf ("\n"); } /* Close stream; skip error-checking for brevity of example */ fclose (my_stream); return 0;}

Example cont’d

Page 4: Bitwise Operators - George Mason University

Page ‹#›

From C Programs to Processes:Linking, Loading, & Virtual Memory

TopicsTopics Static linking Object files Static libraries Dynamic linking of shared libraries Loading executables Processes Virtual Memory

8

A Simplistic Program TranslationScheme

Problems:• Efficiency: small change requires complete recompilation• Modularity: hard to share common functions (e.g. printf)

Solution:• Static linker (or linker)

Translator

m.c

p

ASCII source file

Binary executable object file(memory image on disk)

Page 5: Bitwise Operators - George Mason University

Page ‹#›

9

A Better Scheme Using a Linker

Linker (ld)

Translators

m.c

m.o

Translators

a.c

a.o

p

Separately compiledrelocatable object files

Executable object file (contains codeand data for all functions defined in m.cand a.c)

10

Translating the Example ProgramCompiler driverCompiler driver coordinates all steps in the translation coordinates all steps in the translation

and linking process.and linking process. Typically included with each compilation system (e.g., gcc) Invokes preprocessor (cpp), compiler (cc1), assembler (as),

and linker (ld). Passes command line arguments to appropriate phases

Example: create executable Example: create executable pp from from m.cm.c and and a.ca.c::bass> gcc -O2 -v -o p m.c a.c cpp [args] m.c /tmp/cca07630.i cc1 /tmp/cca07630.i m.c -O2 [args] -o /tmp/cca07630.s as [args] -o /tmp/cca076301.o /tmp/cca07630.s <similar process for a.c>ld -o p [system obj files] /tmp/cca076301.o /tmp/cca076302.o bass>

Page 6: Bitwise Operators - George Mason University

Page ‹#›

11

What Does a Linker Do?Merges object filesMerges object files

Merges multiple relocatable (.o) object files into a single executableobject file that can loaded and executed by the loader.

Resolves external referencesResolves external references As part of the merging process, resolves external references.

External reference: reference to a symbol defined in another object file.

Relocates symbolsRelocates symbols Relocates symbols from their relative locations in the .o files to

new absolute positions in the executable. Updates all references to these symbols to reflect their new

positions. References can be in either code or data

» code: a(); /* reference to symbol a */» data: int *xp=&x; /* reference to symbol x */

12

Why Linkers?ModularityModularity

Program can be written as a collection of smaller sourcefiles, rather than one monolithic mass.

Can build libraries of common functions (more on this later) e.g., Math library, standard C library

EfficiencyEfficiency Time:

Change one source file, compile, and then relink. No need to recompile other source files.

Space: Libraries of common functions can be aggregated into a single

file... Yet executable files and running memory images contain only

code for the functions they actually use.

Page 7: Bitwise Operators - George Mason University

Page ‹#›

13

Executable and Linkable Format(ELF)

Standard binary format for object filesStandard binary format for object filesDerives from AT&T System V UnixDerives from AT&T System V Unix

Later adopted by BSD Unix variants and Linux

One unified format forOne unified format for Relocatable object files (.o), Executable object files Shared object files (.so)

Generic name: ELF binariesGeneric name: ELF binariesBetter support for shared libraries than old Better support for shared libraries than old a.outa.out formats. formats.

14

ELF Object File FormatElf headerElf header

Magic number, type (.o, exec, .so),machine, byte ordering, etc.

Program header tableProgram header table Page size, virtual addresses memory

segments (sections), segment sizes.

.text.text section section Code

.data.data section section Initialized (static) data

..bssbss section section Uninitialized (static) data Has section header but occupies no space

ELF header

Program header table(required for executables)

.text section

.data section

.bss section

.symtab

.rel.txt

.rel.data

.debug

Section header table(required for relocatables)

0

Page 8: Bitwise Operators - George Mason University

Page ‹#›

15

ELF Object File Format (cont)..symtabsymtab section section

Symbol table Procedure and static variable names Section names and locations

..rel.textrel.text section section Relocation info for .text section Addresses of instructions that will need to

be modified in the executable Instructions for modifying.

..rel.datarel.data section section Relocation info for .data section Addresses of pointer data that will need to

be modified in the merged executable.debug.debug section section

Info for symbolic debugging (gcc -g)

ELF header

Program header table(required for executables)

.text section

.data section

.bss section

.symtab

.rel.text

.rel.data

.debug

Section header table(required for relocatables)

0

16

Example C Program

int e=7; int main() { int r = a(); exit(0); }

m.c a.cextern int e; int *ep=&e;int x=15; int y; int a() { return *ep+x+y; }

Page 9: Bitwise Operators - George Mason University

Page ‹#›

17

Merging Relocatable Object Filesinto an Executable Object File

main()m.o

int *ep = &e

a()

a.o

int e = 7

headers

main()

a()

0system code

int *ep = &e

int e = 7

system data

more system code

int x = 15int y

system data

int x = 15

Relocatable Object Files Executable Object File

.text

.text

.data

.text

.data

.text

.data

.bss .symtab.debug

.data

uninitialized data .bss

system code

18

Relocating Symbols and ResolvingExternal References

Symbols are lexical entities that name functions and variables. Each symbol has a value (typically a memory address). Code consists of symbol definitions and references. References can be either local or external.

int e=7; int main() { int r = a(); exit(0); }

m.c a.cextern int e; int *ep=&e;int x=15; int y; int a() { return *ep+x+y; }

Def of localsymbol e

Ref to external symbol exit(defined in libc.so)

Ref toexternalsymbol e

Def oflocal symbol ep

Defs oflocalsymbolsx and y

Refs of localsymbols ep,x,y

Def oflocal symbol a

Ref to external symbol a

Page 10: Bitwise Operators - George Mason University

Page ‹#›

19

m.o Relocation InfoDisassembly of section .text: 00000000 <main>: 00000000 <main>: 0: 55 pushl %ebp 1: 89 e5 movl %esp,%ebp 3: e8 fc ff ff ff call 4 <main+0x4> 4: R_386_PC32 a 8: 6a 00 pushl $0x0 a: e8 fc ff ff ff call b <main+0xb> b: R_386_PC32 exit f: 90 nop

Disassembly of section .data: 00000000 <e>: 0: 07 00 00 00

source: objdump

int e=7; int main() { int r = a(); exit(0); }

m.c

20

a.o Relocation Info (.text)a.cextern int e; int *ep=&e;int x=15; int y; int a() { return *ep+x+y; }

Disassembly of section .text:

00000000 <a>: 0: 55 pushl %ebp 1: 8b 15 00 00 00 movl 0x0,%edx 6: 00 3: R_386_32 ep 7: a1 00 00 00 00 movl 0x0,%eax 8: R_386_32 x c: 89 e5 movl %esp,%ebp e: 03 02 addl (%edx),%eax 10: 89 ec movl %ebp,%esp 12: 03 05 00 00 00 addl 0x0,%eax 17: 00 14: R_386_32 y 18: 5d popl %ebp 19: c3 ret

Page 11: Bitwise Operators - George Mason University

Page ‹#›

21

a.o Relocation Info (.data)a.cextern int e; int *ep=&e;int x=15; int y; int a() { return *ep+x+y; }

Disassembly of section .data:

00000000 <ep>: 0: 00 00 00 00

0: R_386_32 e 00000004 <x>: 4: 0f 00 00 00

22

Executable After Relocation andExternal Reference Resolution (.text)

08048530 <main>: 8048530: 55 pushl %ebp 8048531: 89 e5 movl %esp,%ebp 8048533: e8 08 00 00 00 call 8048540 <a> 8048538: 6a 00 pushl $0x0 804853a: e8 35 ff ff ff call 8048474 <_init+0x94> 804853f: 90 nop 08048540 <a>: 8048540: 55 pushl %ebp 8048541: 8b 15 1c a0 04 movl 0x804a01c,%edx 8048546: 08 8048547: a1 20 a0 04 08 movl 0x804a020,%eax 804854c: 89 e5 movl %esp,%ebp 804854e: 03 02 addl (%edx),%eax 8048550: 89 ec movl %ebp,%esp 8048552: 03 05 d0 a3 04 addl 0x804a3d0,%eax 8048557: 08 8048558: 5d popl %ebp 8048559: c3 ret

Page 12: Bitwise Operators - George Mason University

Page ‹#›

23

Executable After Relocation andExternal Reference Resolution(.data)

Disassembly of section .data:

0804a018 <e>: 804a018: 07 00 00 00

0804a01c <ep>: 804a01c: 18 a0 04 08

0804a020 <x>: 804a020: 0f 00 00 00

int e=7; int main() { int r = a(); exit(0); }

m.c

a.cextern int e; int *ep=&e;int x=15; int y; int a() { return *ep+x+y; }

24

Packaging Commonly UsedFunctionsHow to package functions commonly used by programmers?How to package functions commonly used by programmers?

Math, I/O, memory management, string manipulation, etc.

Awkward, given the linker framework so far:Awkward, given the linker framework so far: Option 1: Put all functions in a single source file

Programmers link big object file into their programs Space and time inefficient

Option 2: Put each function in a separate source file Programmers explicitly link appropriate binaries into their programs More efficient, but burdensome on the programmer

Solution: Solution: static librariesstatic libraries (. (.aa archive filesarchive files)) Concatenate related relocatable object files into a single file with an

index (called an archive). Enhance linker so that it tries to resolve unresolved external

references by looking for the symbols in one or more archives. If an archive member file resolves reference, link into executable.

Page 13: Bitwise Operators - George Mason University

Page ‹#›

25

Static Libraries (archives)

Translator

p1.c

p1.o

Translator

p2.c

p2.o libc.astatic library (archive) ofrelocatable object filesconcatenated into one file.

executable object file (only contains codeand data for libc functions that are calledfrom p1.c and p2.c)

Further improves modularity and efficiency by packagingcommonly used functions [e.g., C standard library (libc),math library (libm)]

Linker selectively only the .o files in the archive that areactually needed by the program.

Linker (ld)

p

26

Creating Static Libraries

Translator

atoi.c

atoi.o

Translator

printf.c

printf.o

libc.a

Archiver (ar)

... Translator

random.c

random.o

ar rs libc.a \ atoi.o printf.o … random.o

Archiver allows incremental updates:• Recompile function that changes and replace .o file inarchive.

C standard library

Page 14: Bitwise Operators - George Mason University

Page ‹#›

27

Commonly Used Librarieslibc.alibc.a (the C standard library) (the C standard library)

8 MB archive of 900 object files. I/O, memory allocation, signal handling, string handling, data and

time, random numbers, integer mathlibm.alibm.a (the C math library) (the C math library)

1 MB archive of 226 object files. floating point math (sin, cos, tan, log, exp, sqrt, …)

% ar -t /usr/lib/libc.a | sort …fork.o … fprintf.o fpu_control.o fputc.o freopen.o fscanf.o fseek.o fstab.o …

% ar -t /usr/lib/libm.a | sort …e_acos.o e_acosf.o e_acosh.o e_acoshf.o e_acoshl.o e_acosl.o e_asin.o e_asinf.o e_asinl.o …

28

Using Static LibrariesLinkerLinker’’s algorithm for resolving external references:s algorithm for resolving external references:

Scan .o files and .a files in the command line order. During the scan, keep a list of the current unresolved

references. As each new .o or .a file obj is encountered, try to resolve

each unresolved reference in the list against the symbols inobj.

If any entries in the unresolved list at end of scan, then error.

Problem:Problem: Command line order matters! Moral: put libraries at the end of the command line.

bass> gcc -L. libtest.o -lmine bass> gcc -L. -lmine libtest.o libtest.o: In function `main': libtest.o(.text+0x4): undefined reference to `libfun'

Page 15: Bitwise Operators - George Mason University

Page ‹#›

29

Loading Executable Binaries

ELF header

Program header table(required for executables)

.text section

.data section

.bss section

.symtab

.rel.text

.rel.data

.debug

Section header table(required for relocatables)

0

.text segment(r/o)

.data segment(initialized r/w)

.bss segment(uninitialized r/w)

Executable object file for example program p

Process image

0x08048494

init and shared libsegments

0x080483e0

Virtual addr

0x0804a010

0x0804a3b0

30

Shared LibrariesStatic libraries have the following disadvantages:Static libraries have the following disadvantages:

Potential for duplicating lots of common code in the executablefiles on a filesystem. e.g., every C program needs the standard C library

Potential for duplicating lots of code in the virtual memory space ofmany processes.

Minor bug fixes of system libraries require each application toexplicitly relink

Solution:Solution: Shared libraries (dynamic link libraries, DLLs) whose members are

dynamically loaded into memory and linked into an application atrun-time. Dynamic linking can occur when executable is first loaded and run.

» Common case for Linux, handled automatically by ld-linux.so. Dynamic linking can also occur after program has begun.

» In Linux, this is done explicitly by user with dlopen().» Basis for High-Performance Web Servers.

Shared library routines can be shared by multiple processes.

Page 16: Bitwise Operators - George Mason University

Page ‹#›

31

Dynamically Linked Shared Libraries

libc.so functions called by m.cand a.c are loaded, linked, and(potentially) shared amongprocesses.

Shared library of dynamicallyrelocatable object files

Translators(cc1, as)

m.c

m.o

Translators(cc1,as)

a.c

a.o

libc.so

Linker (ld)

p

Loader/Dynamic Linker(ld-linux.so)

Fully linked executablep’ (in memory)

Partially linked executablep(on disk)

P’

32

The Complete Picture

Translator

m.c

m.o

Translator

a.c

a.o

libc.so

Static Linker (ld)

p

Loader/Dynamic Linker(ld-linux.so)

libwhatever.a

p’

libm.so

Page 17: Bitwise Operators - George Mason University

Page ‹#›

33

Next Step: LoadingA loader is a system program that copies the code andA loader is a system program that copies the code and

data in the executable object file from disk intodata in the executable object file from disk intomemory, and then runs the program by jumping tomemory, and then runs the program by jumping toits first instruction.its first instruction.

Copying a program into memory and then running it isCopying a program into memory and then running it isknown as known as loadingloading

A running program is called a A running program is called a processprocessOn modern computer systems, there are manyOn modern computer systems, there are many

processes running at the same timeprocesses running at the same timeHow does this work? I.e., how does the CPU executeHow does this work? I.e., how does the CPU execute

instructions for multiple processes at the same time?instructions for multiple processes at the same time?How is the memory on the computer shared betweenHow is the memory on the computer shared between

the running processes?the running processes?

34

Private Address SpacesEach process has its own private address space.Each process has its own private address space.

kernel virtual memory(code, data, heap, stack)

memory mapped region forshared libraries

run-time heap(managed by malloc)

user stack(created at runtime)

unused0

%esp (stack pointer)

memoryinvisible touser code

brk

0xc0000000

0x08048000

0x40000000

read/write segment(.data, .bss)

read-only segment(.init, .text, .rodata)

loaded from the executable file

0xffffffff

Page 18: Bitwise Operators - George Mason University

Page ‹#›

35

Linux Memory LayoutStackStack

Runtime stack (8MB limit)

HeapHeap Dynamically allocated storage When call malloc, calloc, new

DLLsDLLs Dynamically Linked Libraries Library routines (e.g., printf, malloc) Linked into object code when first executed

DataData Statically allocated data E.g., arrays & strings declared in code

TextText Executable machine instructions Read-only

Upper2 hexdigits ofaddress

Red Hatv. 6.2~1920MBmemorylimit

FF

BF

7F

3F

C0

80

40

00

Stack

DLLs

TextData

Heap

Heap

08

36

Linux Memory AllocationLinked

BF

7F

3F

80

40

00

Stack

DLLs

TextData

08

SomeHeap

BF

7F

3F

80

40

00

Stack

DLLs

TextData

Heap

08

MoreHeap

BF

7F

3F

80

40

00

Stack

DLLs

TextDataHeap

Heap

08

InitiallyBF

7F

3F

80

40

00

Stack

TextData

08

Page 19: Bitwise Operators - George Mason University

Page ‹#›

37

ProcessesDef: A Def: A processprocess is an instance of a running program. is an instance of a running program.

One of the most profound ideas in computer science. Not the same as “program” or “processor”

Process provides each program with two keyProcess provides each program with two keyabstractions:abstractions: Logical control flow

Each program seems to have exclusive use of the CPU. Private address space

Each program seems to have exclusive use of main memory.

How are these Illusions maintained?How are these Illusions maintained? Process executions interleaved (multitasking) Address spaces managed by virtual memory system

38

Logical Control Flows

Time

Process A Process B Process C

Each process has its own logical control flow

Page 20: Bitwise Operators - George Mason University

Page ‹#›

39

Context Switching in Multi-taskedOperating Systems

Processes are managed by a shared chunk of OS codeProcesses are managed by a shared chunk of OS codecalled the called the kernelkernel Important: the kernel is not a separate process, but rather

runs as part of some user process

Control flow passes from one process to another via aControl flow passes from one process to another via acontext switch.context switch.

Process Acode

Process Bcode

user code

kernel code

user code

kernel code

user code

Timecontext switch

context switch

40

Private Address SpacesEach process has its own private address space.Each process has its own private address space.

kernel virtual memory(code, data, heap, stack)

memory mapped region forshared libraries

run-time heap(managed by malloc)

user stack(created at runtime)

unused0

%esp (stack pointer)

memoryinvisible touser code

brk

0xc0000000

0x08048000

0x40000000

read/write segment(.data, .bss)

read-only segment(.init, .text, .rodata)

loaded from the executable file

0xffffffff

Page 21: Bitwise Operators - George Mason University

Page ‹#›

41

Memory Allocation for ProcessesEach process has its own private address spaceEach process has its own private address spaceRange of Memory Addresses for a CPU with a 32-bitRange of Memory Addresses for a CPU with a 32-bit

address: 0 address: 0 –– 2 23232 -1 (4 GB!!) -1 (4 GB!!)Referred to as Address SpaceReferred to as Address SpaceHow can multiple processes be allocated memory at theHow can multiple processes be allocated memory at the

same time?same time?Size of address space of even one process willSize of address space of even one process willtypically exceed size of physical memory!typically exceed size of physical memory!

On many systems, there can be hundreds of On many systems, there can be hundreds ofprocesses running at the same time!processes running at the same time!

42

The Solution: Virtual MemoryVirtual memory: an abstraction for main memoryVirtual memory: an abstraction for main memoryThe idea: Treat main memory (physical memory) as aThe idea: Treat main memory (physical memory) as a

cache for an address space that is stored on diskcache for an address space that is stored on diskOnly the active memory of a running process isOnly the active memory of a running process is

allocated physical memory, with the inactive part ofallocated physical memory, with the inactive part ofthe address space stored on diskthe address space stored on disk

Page 22: Bitwise Operators - George Mason University

Page ‹#›

43

A System with Physical Memory OnlyExamples:Examples:

most Cray machines, early PCs, nearly all embeddedsystems, etc.

Addresses generated by the CPU correspond directly to bytes inphysical memory

CPU

0:1:

N-1:

Memory

PhysicalAddresses

44

A System with Virtual MemoryExamples:Examples:

workstations, servers, modern PCs, etc.

Address Translation: Hardware converts virtual addresses tophysical addresses via OS-managed lookup table (page table)

CPU

0:1:

N-1:

Memory

0:1:

P-1:

Page Table

Disk

VirtualAddresses Physical

Addresses

Page 23: Bitwise Operators - George Mason University

Page ‹#›

45

Motivation for Virtual MemoryUse Physical DRAM as a Cache for the DiskUse Physical DRAM as a Cache for the Disk

Address space of a process can exceed physical memory size Sum of address spaces of multiple processes can exceed

physical memory

Simplify Memory ManagementSimplify Memory Management Multiple processes resident in main memory.

Each process with its own address space Only “active” code and data is actually in memory

Allocate more memory to process as needed.

Provide ProtectionProvide Protection One process can’t interfere with another.

because they operate in different address spaces. User process cannot access privileged information

different sections of address spaces have different permissions.

46

Motivation #1: DRAM a “Cache” for DiskFull address space is quite large:Full address space is quite large:

32-bit addresses: ~4,000,000,000 (4 billion) bytes 64-bit addresses: ~16,000,000,000,000,000,000 (16 quintillion)

bytes

Disk storage is ~300X cheaper than DRAM storageDisk storage is ~300X cheaper than DRAM storage 80 GB of DRAM: ~ $33,000 80 GB of disk: ~ $110

To access large amounts of data in a cost-effective manner,To access large amounts of data in a cost-effective manner,the bulk of the data must be stored on diskthe bulk of the data must be stored on disk

1GB: ~$200 80 GB: ~$110

4 MB: ~$500

DiskDRAMSRAM

Page 24: Bitwise Operators - George Mason University

Page ‹#›

47

VM Address Translation: Hit

Processor

HardwareAddr TransMechanism

MainMemorya

a'

physical addressvirtual address part of the on-chipmemory mgmt unit (MMU)

48

VM Address Translation: Miss

Processor

HardwareAddr TransMechanism

faulthandler

MainMemory

Secondarymemorya

a'

page fault

physical address OS performsthis transfer(only if miss)

virtual address part of the on-chipmemory mgmt unit (MMU)

Page 25: Bitwise Operators - George Mason University

Page ‹#›

49

A System with Virtual MemoryExamples:Examples:

workstations, servers, modern PCs, etc.

Address Translation: Hardware converts virtual addresses tophysical addresses via OS-managed lookup table (page table)

CPU

0:1:

N-1:

Memory

0:1:

P-1:

Page Table

Disk

VirtualAddresses Physical

Addresses

50

Page Faults (like “Cache Misses”)What if an object is on disk rather than in memory?What if an object is on disk rather than in memory?

Page table entry indicates virtual address not in memory OS exception handler invoked to move data from disk into

memory current process suspends, others can resume OS has full control over placement, etc.

CPU

Memory

Page Table

Disk

VirtualAddresses Physical

Addresses

CPU

Memory

Page Table

Disk

VirtualAddresses Physical

Addresses

Before fault After fault

Page 26: Bitwise Operators - George Mason University

Page ‹#›

51

Servicing a Page FaultProcessor Signals ControllerProcessor Signals Controller

Read block of length Pstarting at disk address X andstore starting at memoryaddress Y

Read OccursRead Occurs Direct Memory Access (DMA) Under control of I/O controller

I / O Controller SignalsI / O Controller SignalsCompletionCompletion Interrupt processor OS resumes suspended

process

diskDiskdiskDisk

Memory-I/O bus

Processor

Cache

MemoryI/O

controller

Reg

(2) DMATransfer

(1) Initiate Block Read

(3) ReadDone

52

Motivation #2: Memory ManagementMultiple processes can reside in physical memory.Multiple processes can reside in physical memory.How do we resolve address conflicts?How do we resolve address conflicts?

what if two processes access something at the sameaddress?

kernel virtual memory

Memory mapped region forshared libraries

runtime heap (via malloc)

program text (.text)initialized data (.data)

uninitialized data (.bss)

stack

forbidden0

%esp

memory invisible to user code

the “brk” ptr

Linux/x86processmemoryimage

Page 27: Bitwise Operators - George Mason University

Page ‹#›

53

VirtualAddressSpace forProcess 1:

PhysicalAddressSpace(DRAM)

VP 1VP 2

PP 2Address Translation0

0

N-1

0

N-1M-1

VP 1VP 2

PP 7

PP 10

(e.g., read/onlylibrary code)

Solution: Separate Virt. Addr. Spaces Virtual and physical address spaces divided into equal-sized

blocks blocks are called “pages” (both virtual and physical)

Each process has its own virtual address space operating system controls how virtual pages as assigned to

physical memory

...

...

VirtualAddressSpace forProcess 2:

54

Motivation #3: ProtectionPage table entry contains access rights informationPage table entry contains access rights information

hardware enforces this protection (trap into OS if violationoccurs) Page Tables

Process i:

Physical AddrRead? Write? PP 9Yes No

PP 4Yes Yes

XXXXXXX No No

VP 0:

VP 1:

VP 2:•••

••••••

Process j:

0:1:

N-1:

Memory

Physical AddrRead? Write? PP 6Yes Yes

PP 9Yes No

XXXXXXX No No•••

••••••

VP 0:

VP 1:

VP 2:

Page 28: Bitwise Operators - George Mason University

Page ‹#›

55

Concluding RemarksProcesses and Virtual Memory are two of the greatProcesses and Virtual Memory are two of the great

ideas in computer scienceideas in computer scienceCS 471 (Operating Systems) will cover these conceptsCS 471 (Operating Systems) will cover these concepts

in detailin detailCS 365 (Computer Architecture) discusses memoryCS 365 (Computer Architecture) discusses memory

management and virtual memorymanagement and virtual memory

Next lecture: Writing programs thatNext lecture: Writing programs that Create and manipulate processes Send and receive “signals”