The document discusses how a "Hello World" program works behind the scenes. It covers topics like compilation, linking, executable file formats, loading programs into memory, and process creation. The key points are:
1) A C program is compiled into an object file, then linked with library files to create an executable. The linker resolves symbols and relocates addresses.
2) Executable files use formats like ELF that contain machine code, data, symbol tables, and sections. Object files have a similar format.
3) When a program runs, the OS loads pages of the executable into memory as needed and sets up the process with its own virtual address space.
4) System calls
Introduce Brainf*ck, another Turing complete programming language. Then, try to implement the following from scratch: Interpreter, Compiler [x86_64 and ARM], and JIT Compiler.
Introduce Brainf*ck, another Turing complete programming language. Then, try to implement the following from scratch: Interpreter, Compiler [x86_64 and ARM], and JIT Compiler.
Build a full-functioned virtual machine from scratch, when Brainfuck is used. Basic concepts about interpreter, optimizations techniques, language specialization, and platform specific tweaks.
It is the presentation file used by Jim Huang (jserv) at OSDC.tw 2009. New compiler technologies are invisible but highly integrated around our world, and we can enrich the experience via facilitating LLVM.
Jim Huang (jserv) from 0xlab.org prepared the technical training for ARM and SoC. In part I, it introduced the overview of ARM architecture, family, ISA feature, SoC overview, and several practical approaches to Xscale SoC as example.
GNU Toolchain is the de facto standard of IT industrial and has been improved by comprehensive open source contributions. In this session, it is expected to cover the mechanism of compiler driver, system interaction (take GNU/Linux for example), linker, C runtime library, and the related dynamic linker. Instead of analyzing the system design, the session is use case driven and illustrated progressively.
Let's turn the table. Suppose your goal is to deliberately create buggy programs in C and C++ with serious security vulnerabilities that can be "easily" exploited. Then you need to know about things like stack smashing, shellcode, arc injection, return-oriented programming. You also need to know about annoying protection mechanisms such as address space layout randomization, stack canaries, data execution prevention, and more. These slides will teach you the basics of how to deliberately write insecure programs in C and C++.
A PDF version of the slides can be downloaded from my homepage: http://olvemaudal.com/talks
Here is a video recording of me presenting these slides at NDC 2014: http://vimeo.com/channels/ndc2014/97505677
Enjoy!
The promise of the IoT won’t be fulfilled until integrated
software platforms are available that allow software
developers to develop these devices efficiently and in
the most cost-effective manner possible.
This presentation introduces F9 microkernel, new open source
implementation built from scratch, which deploys
modern kernel techniques dedicated to deeply
embedded devices.
Доклад рассказывает об устройстве и опыте применения инструментов динамического тестирования C/C++ программ — AddressSanitizer, ThreadSanitizer и MemorySanitizer. Инструменты находят такие ошибки, как использование памяти после освобождения, обращения за границы массивов и объектов, гонки в многопоточных программах и использования неинициализированной памяти.
Title: Working Remotely (via SSH) Rocks!
Intro: Consistent & Persistent development environment from any location any client.
"SSH + TMUX + CLI" Rocks!
Nice material about "SSH Tunneling": http://www.slideshare.net/osoco/ssh-tunneling-recipes-10284950
The beautiful thing about software engineering is that it gives you the warm and fuzzy illusion of total understanding: I control this machine because I know how it operates. This is the result of layers upon layers of successful abstractions, which hide immense sophistication and complexity. As with any abstraction, though, these sometimes leak, and that's when a good grounding in what's under the hood pays off.
The second talk in this series peels a few layers of abstraction and takes a look under the hood of our "car engine", the CPU. While hardly anyone codes in assembly language anymore, your C# or JavaScript (or Scala or...) application still ends up executing machine code instructions on a processor; that is why Java has a memory model, why memory layout still matters at scale, and why you're usually free to ignore these considerations and go about your merry way.
You'll come away knowing a little bit about a lot of different moving parts under the hood; after all, isn't understanding how the machine operates what this is all about?
(From a talk given at BuildStuff 2016 in Vilnius, Lithuania.)
CMake is an open-source cross-platform build system. It is increasingly becoming the build system of choice for open source projects. The Qt project recently announced that Qbs, the replacement build system for qmake, will no longer be supported and future efforts will focus on CMake. It may become the default build system for Qt version 6.
CMake has offered support for building Qt applications for some time, and is supported within the Qt Creator IDE. In this webinar we will:
-Introduce you to CMake
-Cover its basic features and how to use it
-Show some CMake configurations including Qt-based applications
-Prove how easy it is to use Cmake with Qt so you'll be ready to use it for your C++ and Qt-based applications!
Build a full-functioned virtual machine from scratch, when Brainfuck is used. Basic concepts about interpreter, optimizations techniques, language specialization, and platform specific tweaks.
It is the presentation file used by Jim Huang (jserv) at OSDC.tw 2009. New compiler technologies are invisible but highly integrated around our world, and we can enrich the experience via facilitating LLVM.
Jim Huang (jserv) from 0xlab.org prepared the technical training for ARM and SoC. In part I, it introduced the overview of ARM architecture, family, ISA feature, SoC overview, and several practical approaches to Xscale SoC as example.
GNU Toolchain is the de facto standard of IT industrial and has been improved by comprehensive open source contributions. In this session, it is expected to cover the mechanism of compiler driver, system interaction (take GNU/Linux for example), linker, C runtime library, and the related dynamic linker. Instead of analyzing the system design, the session is use case driven and illustrated progressively.
Let's turn the table. Suppose your goal is to deliberately create buggy programs in C and C++ with serious security vulnerabilities that can be "easily" exploited. Then you need to know about things like stack smashing, shellcode, arc injection, return-oriented programming. You also need to know about annoying protection mechanisms such as address space layout randomization, stack canaries, data execution prevention, and more. These slides will teach you the basics of how to deliberately write insecure programs in C and C++.
A PDF version of the slides can be downloaded from my homepage: http://olvemaudal.com/talks
Here is a video recording of me presenting these slides at NDC 2014: http://vimeo.com/channels/ndc2014/97505677
Enjoy!
The promise of the IoT won’t be fulfilled until integrated
software platforms are available that allow software
developers to develop these devices efficiently and in
the most cost-effective manner possible.
This presentation introduces F9 microkernel, new open source
implementation built from scratch, which deploys
modern kernel techniques dedicated to deeply
embedded devices.
Доклад рассказывает об устройстве и опыте применения инструментов динамического тестирования C/C++ программ — AddressSanitizer, ThreadSanitizer и MemorySanitizer. Инструменты находят такие ошибки, как использование памяти после освобождения, обращения за границы массивов и объектов, гонки в многопоточных программах и использования неинициализированной памяти.
Title: Working Remotely (via SSH) Rocks!
Intro: Consistent & Persistent development environment from any location any client.
"SSH + TMUX + CLI" Rocks!
Nice material about "SSH Tunneling": http://www.slideshare.net/osoco/ssh-tunneling-recipes-10284950
The beautiful thing about software engineering is that it gives you the warm and fuzzy illusion of total understanding: I control this machine because I know how it operates. This is the result of layers upon layers of successful abstractions, which hide immense sophistication and complexity. As with any abstraction, though, these sometimes leak, and that's when a good grounding in what's under the hood pays off.
The second talk in this series peels a few layers of abstraction and takes a look under the hood of our "car engine", the CPU. While hardly anyone codes in assembly language anymore, your C# or JavaScript (or Scala or...) application still ends up executing machine code instructions on a processor; that is why Java has a memory model, why memory layout still matters at scale, and why you're usually free to ignore these considerations and go about your merry way.
You'll come away knowing a little bit about a lot of different moving parts under the hood; after all, isn't understanding how the machine operates what this is all about?
(From a talk given at BuildStuff 2016 in Vilnius, Lithuania.)
CMake is an open-source cross-platform build system. It is increasingly becoming the build system of choice for open source projects. The Qt project recently announced that Qbs, the replacement build system for qmake, will no longer be supported and future efforts will focus on CMake. It may become the default build system for Qt version 6.
CMake has offered support for building Qt applications for some time, and is supported within the Qt Creator IDE. In this webinar we will:
-Introduce you to CMake
-Cover its basic features and how to use it
-Show some CMake configurations including Qt-based applications
-Prove how easy it is to use Cmake with Qt so you'll be ready to use it for your C++ and Qt-based applications!
Apache Arrow Workshop at VLDB 2019 / BOSS SessionWes McKinney
Technical deep dive for database system developers in the Arrow columnar format, binary protocol, C++ development platform, and Arrow Flight RPC.
See demo Jupyter notebooks at https://github.com/wesm/vldb-2019-apache-arrow-workshop
How to approach a problem from a performance standpoint. A small real world application is used as a case study.
I\'ve presented "High Performance With Java" at Codebits\'2008 held from 13 to 15 November 2008
(*) Codebits is a programming contest held in Portugal held the spirit of Yahoo Hack! Day
Linux Kernel Booting Process (2) - For NLKBshimosawa
Describes the bootstrapping part in Linux, and related architectural mechanisms and technologies.
This is the part two of the slides, and the succeeding slides may contain the errata for this slide.
En esta presentación se muestran un conjunto de librerías y frameworks en Python para poder realizar pruebas tanto funcionales com ono funcionales, a diferentes niveles (unitario, aceptación y e2)
This presentation covers the general concepts about real-time systems, how Linux kernel works for preemption, the latency in Linux, rt-preempt, and Xenomai, the real-time extension as the dual kernel approach.
* Know the reasons why various operating systems exist and how they are functioned for dedicated purposes
* Understand the basic concepts while building system software from scratch
• How can we benefit from cheap ARM boards and the related open source tools?
- Raspberry Pi & STM32F4-Discovery
Introduce F9 microkernel, new open source implementation built from scratch, which deploys modern kernel techniques, derived from L4 microkernel designs, to deep embedded devices.
:: https://github.com/f9micro
Characteristics of F9 microkernel
– Efficiency: performance + power consumption
– Security: memory protection + isolated execution
– Flexible development environment
(1) Analysis of Large-scale system software
(2) Diagnose faults inside system software, especially for
device drivers
(2) Deal with faulty device driver implementation
TECHNICAL TRAINING MANUAL GENERAL FAMILIARIZATION COURSEDuvanRamosGarzon1
AIRCRAFT GENERAL
The Single Aisle is the most advanced family aircraft in service today, with fly-by-wire flight controls.
The A318, A319, A320 and A321 are twin-engine subsonic medium range aircraft.
The family offers a choice of engines
Vaccine management system project report documentation..pdfKamal Acharya
The Division of Vaccine and Immunization is facing increasing difficulty monitoring vaccines and other commodities distribution once they have been distributed from the national stores. With the introduction of new vaccines, more challenges have been anticipated with this additions posing serious threat to the already over strained vaccine supply chain system in Kenya.
Immunizing Image Classifiers Against Localized Adversary Attacksgerogepatton
This paper addresses the vulnerability of deep learning models, particularly convolutional neural networks
(CNN)s, to adversarial attacks and presents a proactive training technique designed to counter them. We
introduce a novel volumization algorithm, which transforms 2D images into 3D volumetric representations.
When combined with 3D convolution and deep curriculum learning optimization (CLO), itsignificantly improves
the immunity of models against localized universal attacks by up to 40%. We evaluate our proposed approach
using contemporary CNN architectures and the modified Canadian Institute for Advanced Research (CIFAR-10
and CIFAR-100) and ImageNet Large Scale Visual Recognition Challenge (ILSVRC12) datasets, showcasing
accuracy improvements over previous techniques. The results indicate that the combination of the volumetric
input and curriculum learning holds significant promise for mitigating adversarial attacks without necessitating
adversary training.
Water scarcity is the lack of fresh water resources to meet the standard water demand. There are two type of water scarcity. One is physical. The other is economic water scarcity.
Student information management system project report ii.pdfKamal Acharya
Our project explains about the student management. This project mainly explains the various actions related to student details. This project shows some ease in adding, editing and deleting the student details. It also provides a less time consuming process for viewing, adding, editing and deleting the marks of the students.
Saudi Arabia stands as a titan in the global energy landscape, renowned for its abundant oil and gas resources. It's the largest exporter of petroleum and holds some of the world's most significant reserves. Let's delve into the top 10 oil and gas projects shaping Saudi Arabia's energy future in 2024.
Automobile Management System Project Report.pdfKamal Acharya
The proposed project is developed to manage the automobile in the automobile dealer company. The main module in this project is login, automobile management, customer management, sales, complaints and reports. The first module is the login. The automobile showroom owner should login to the project for usage. The username and password are verified and if it is correct, next form opens. If the username and password are not correct, it shows the error message.
When a customer search for a automobile, if the automobile is available, they will be taken to a page that shows the details of the automobile including automobile name, automobile ID, quantity, price etc. “Automobile Management System” is useful for maintaining automobiles, customers effectively and hence helps for establishing good relation between customer and automobile organization. It contains various customized modules for effectively maintaining automobiles and stock information accurately and safely.
When the automobile is sold to the customer, stock will be reduced automatically. When a new purchase is made, stock will be increased automatically. While selecting automobiles for sale, the proposed software will automatically check for total number of available stock of that particular item, if the total stock of that particular item is less than 5, software will notify the user to purchase the particular item.
Also when the user tries to sale items which are not in stock, the system will prompt the user that the stock is not enough. Customers of this system can search for a automobile; can purchase a automobile easily by selecting fast. On the other hand the stock of automobiles can be maintained perfectly by the automobile shop manager overcoming the drawbacks of existing system.
Cosmetic shop management system project report.pdfKamal Acharya
Buying new cosmetic products is difficult. It can even be scary for those who have sensitive skin and are prone to skin trouble. The information needed to alleviate this problem is on the back of each product, but it's thought to interpret those ingredient lists unless you have a background in chemistry.
Instead of buying and hoping for the best, we can use data science to help us predict which products may be good fits for us. It includes various function programs to do the above mentioned tasks.
Data file handling has been effectively used in the program.
The automated cosmetic shop management system should deal with the automation of general workflow and administration process of the shop. The main processes of the system focus on customer's request where the system is able to search the most appropriate products and deliver it to the customers. It should help the employees to quickly identify the list of cosmetic product that have reached the minimum quantity and also keep a track of expired date for each cosmetic product. It should help the employees to find the rack number in which the product is placed.It is also Faster and more efficient way.
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxR&R Consult
CFD analysis is incredibly effective at solving mysteries and improving the performance of complex systems!
Here's a great example: At a large natural gas-fired power plant, where they use waste heat to generate steam and energy, they were puzzled that their boiler wasn't producing as much steam as expected.
R&R and Tetra Engineering Group Inc. were asked to solve the issue with reduced steam production.
An inspection had shown that a significant amount of hot flue gas was bypassing the boiler tubes, where the heat was supposed to be transferred.
R&R Consult conducted a CFD analysis, which revealed that 6.3% of the flue gas was bypassing the boiler tubes without transferring heat. The analysis also showed that the flue gas was instead being directed along the sides of the boiler and between the modules that were supposed to capture the heat. This was the cause of the reduced performance.
Based on our results, Tetra Engineering installed covering plates to reduce the bypass flow. This improved the boiler's performance and increased electricity production.
It is always satisfying when we can help solve complex challenges like this. Do your systems also need a check-up or optimization? Give us a call!
Work done in cooperation with James Malloy and David Moelling from Tetra Engineering.
More examples of our work https://www.r-r-consult.dk/en/cases-en/
Event Management System Vb Net Project Report.pdfKamal Acharya
In present era, the scopes of information technology growing with a very fast .We do not see any are untouched from this industry. The scope of information technology has become wider includes: Business and industry. Household Business, Communication, Education, Entertainment, Science, Medicine, Engineering, Distance Learning, Weather Forecasting. Carrier Searching and so on.
My project named “Event Management System” is software that store and maintained all events coordinated in college. It also helpful to print related reports. My project will help to record the events coordinated by faculties with their Name, Event subject, date & details in an efficient & effective ways.
In my system we have to make a system by which a user can record all events coordinated by a particular faculty. In our proposed system some more featured are added which differs it from the existing system such as security.
Welcome to WIPAC Monthly the magazine brought to you by the LinkedIn Group Water Industry Process Automation & Control.
In this month's edition, along with this month's industry news to celebrate the 13 years since the group was created we have articles including
A case study of the used of Advanced Process Control at the Wastewater Treatment works at Lleida in Spain
A look back on an article on smart wastewater networks in order to see how the industry has measured up in the interim around the adoption of Digital Transformation in the Water Industry.
8. SMP & Multi-core Processor
• Symmetrical Multi-Processing
•
CPU number↑ → Speed ↑?
•
A program can not be divided multiple independent subprogram
• Server application
• Multi-core Processor
• Share caches with other processor
9. Software Architecture
• Any problem in computer science
can be solved by another layer of
indirection
• API: Application Programming
Interface
• System call interface
• Hardware specification
Applications:
Web Browser
Video Player
Word Processor
Email Client
Image Viewer
…
Development Tools:
C/C++ Compiler
Assembler
Library Tools
Debug Tools
Development Libraries
…
Operating System API
System Call
Runtime Library
Operating System Kernel
Hardware
Hardware Specific
10. Operating System
• Abstract interface
• Hardware resource
CPU
Multiprogramming
Time-Sharing System
Multi-tasking
Process
Preemptive
Memory
I/O devices
Device Driver
11. Memory
• How to allocate limited physical memory to lots of programs?
• Assume we have 128MB physical memory
• Program A needs 10MB
• Program B needs 100MB
• Program C needs 20MB
• Solution 1
•
A gets 0~10MB, B gets 10~110MB
•
No address space isolation
•
Inefficiency
•
Undetermined program address
Program A
Program B
Physical Memory
Address Space
0x00000000
0x00A00000
0x06E00000
12. Address Space Isolation
• Own the whole computer
• CPU, Memory
• Address Space(AS)
•
Array - depends on address length
•
32bit system →
•
0x0000000 ~ 0xFFFFFFFF
•
Virtual Address Space
•
Imagination
•
Process use their own virtual address
space
• Physical Address Space
0x00000000
0xFFFFFFFF
Physical Memory
512MB
0x1FFFFFFF
I/O Devices
Physical Address Space
13. Segmentation
• Virtual AS map to Physical AS
• No address space isolation
• Inefficiency
• Undetermined program address
Physical
Address Space
of B
Physical
Address Space
of A
Virtual Address
Space of B
Virtual Address
Space of A
0x00000000
0x00100000
0x00B00000
0x00C00000
0x07000000
0x00000000
0x00A00000
0x00000000
0x06400000
14. Paging
• Frequently use a small part(locality)
• 8 pages, each 1 KB, total 8KB
• Only 6KB physical memory
• PP6, PP7 unused
• Page Fault
• Access attributes
• Read
• Write
• Execute
VP7
VP6
VP5
VP4
VP3
VP2
VP1
VP0
PP7
PP6
PP5
PP4
PP3
PP2
PP1
PP0
VP7
VP6
VP5
VP4
VP3
VP2
VP1
VP0
DP1
DP0
Disk
Process 1
Virtual Space
Process 2
Virtual Space
Physical
Memory
15. MMU
• Memory Management Unit
• Usually place on CPU board
CPU MMU
Physical
Memory
Virtual Address Physical Address
21. File Format
• Executable file format
Derived from COFF(Common Object File Format)
Windows : PE (Portable Executable)
Linux: ELF (Executable Linkable Format)
Dynamic Linking Library (DLL)
Windows (.dll); Linux (.so)
Static Linking Library
Windows (.lib); Linux (.a)
• Intermediate file between compilation and linking → Object file
Windows (.obj); Linux (.o)
Like executable file format
22. File Content
• Machine code, data, symbol table, string table
• File divided by sections
• Code Section (.code, .text)
• Data Section (.data)
int global_init_var = 84;
int global_uninit_var;
void func1(int i) {
printf(“%dn”, i)
}
int main(void) {
static int static_init_var = 85;
static int static_uninit_var2;
int a = 1;
int b;
func(static_var + static_var2);
}
File Header
.text section
.data section
.bss section
Executable File /
Object File
23. File Content
• File Header
Is executable
Static Link or Dynamic Link
Entry address
Target hardware / OS
Section Table
• Code & Data
Security
Cache
Share code section(multiple process)
File Header
.text section
.data section
.bss section
Executable File /
Object File
28. Symbol
• Object file B use function(variable) “foo” in object file A
• A defined function(variable) “foo”
• B reference function(variable) “foo”
• Symbol name(function name, variable name)
• Every object file has a symbol table which record symbol value
• Symbol type
•
Symbol defined in current object file
•
External Symbol
•
…
34. Symbol Address
• Calculation of symbol address
•
function in text section has offset X
•
text section in executable file has offset Y
•
→ function in executable file has offset X + Y
• Example:
• “swap” in “b.o.text” has offset 0x00000000
• “b.o.text” in “ab” has offset 0x0040010f
• → “swap” in “ab” has offset
0x00000000 + 0x0040010f = 0x0040010f
Symbol Type Virtual Address
main function 0x004000e8
swap function 0x0040010f
shared variable 0x006001b8
Process Virtual
Memory Layout
Operating
System
.data
.text
0xC0000000
0x006001b8
0x004000e8
0x00400159
0x006001bc
35. Relocation
a.o
Filename: a.c
extern int shared;
int main() {
int a = 100;
swap(&a, &shared);
}
Linking
ab
Symbol Type Virtual
Address
main function 0x004000e8
swap function 0x0040010f
shared variable 0x006001b8
38. Static Library Linking
hello.o
main() {
printf();
}
printf.o
printf() {
vprintf(stdou);
}
vprintf.o
vprintf() {
...
}
Other .o files
libc.a
Linker
hello.o
printf.o
vprintf.o
Executable Program
other .o files
• OS provide Application Programming
Interface(API)
• Language Library
• Collection of object files
• C language static library in Linux → li
bc.a
40. Program & Process
• Analogy
Program ↔ Recipe
CPU ↔ Man
Hardware ↔ Kitchenware
Process ↔ Cooking
Two CPU can execute the same program
• Process own independent Virtual Address Space
• Process access not allowed address → “Segmentation fault”
User Process
Linux OS
0xC0000000
0x00000000
41. Loading
• Overlay
Programmer divided progra
m
Implement Overlay Manager
Ex.
Three modules: main, A, B
main → 1024 bytes
A → 512 Bytes
B → 256 Bytes
Total → 1792 Bytes
A will not call B
• Paging
Overlay Manager
main
A
B
1024
Bytes
512
Bytes
256
Bytes
Physical Memory
41
43. Creation of Process
1. Create a independent virtual AS
page directory(Linux)
2. Read executable file header, cre
ate mapping between virtual AS
and executable file
VMA, Virtual Memory Area
3. Assign entry address to program
register(PC)
Switch between kernel stack and pro
cess stack
CPU access attribute
ELF
Header
.text
Executable
User Process
Operating
System
0xC0000000
0x00000000
.text
0x08048000
0x08049000
Process
Virtual Space
44. Page Fault
• Executable file has not been loaded into physical memory yet
• Page fault
1. Found 0x08048000 ~ 0x08049000 is an empty page
2. Page handler load page into memory
3. Return to process
ELF
Header
.text
Executable
Page
Physical
Memory
MMUOS
Process
Virtual Space
User Process
Operating
System
.text
0xC0000000
0x00000000
0x08048000
0x08049000
45. Segment
• Page alignment
More than a dozen sections
Waste space
• OS only cares access rights of sections
Readable & Executable(code)
Readable & Writable(data)
Read Only(rodata)
• Merge the same access rights of sections
.text section is 4097 bytes
.init section is 512 bytes
page
page
Process Virtual Space
(Segment)
.init page
.text page
.text page
Process Virtual Space
(No Segment)
.init
.text
Header
Executable
50. Disadvantage of Static Linking
• Advantage
Independent development
Test individual modules
• Disadvantage
Waste memory and disk space
Every program has a copy of runt
ime library(printf, scanf, strlen,
...)
Difficulty of updating module
Need to re-link and publish to us
er when a module is updated
50
Lib.o
Program1.o
Lib.o
Program2.o
Physical Memory
Lib.o
Program1.o
Program1
Lib.o
Program2.o
Program2
Hard Disk
51. Dynamic Linking
• Delay linking until execution
• Example:
Program1.o, Program2.o, Lib.o
Execute Program1 → Load Program1.o
Program1 uses Lib → Load Lib.o
Execute Program2 → Load Program2.o
Program2 uses Lib → Lib.o has already bee
n loaded into physical memory
• Advantage
Save space
Easier to update modules
51
Program1.o
Lib.o
Program2.o
Physical Memory
Program1.o
Program1
Program2.o
Program2
Hard Disk
Lib.o
Lib
52. Basic Implementation
• Operating system support
Process virtual address space allocation
Storage manipulation
Memory share
• Dynamic Shared Objects, DSO, .so file(in Linux)
• Dynamical Linking Library, .dll file(in Windows)
• Dynamic loader loads all dynamic linking libraries into memory
• Every time we execute the program, the loader will relocate the program
• Slowly
Lazy Binding 52
56. Static Shared Library
• Not Static Library
• Load module into particular position
• Ex.
Allocate 0x1000~0x2000 to Module A
Allocate 0x2000~0x3000 to Module B
• Collision
User D allocate 0x1000~0x2000 to Module C
Then other people can not use Module A and Module C simultaneously
56
57. Load Time Relocation
• Relocate absolute address at load time instead of link time
• Example:
Function “foobar” has offset 0x100
Module is loaded into 0x10000000
Then we know function “foobar” at 0x10000100
Traverse the relocation table, relocate function “foobar” to 0x10000100
• Multiple processes use the same object, but relocation are differe
nt between processes
They can not use the same copy of shared object
• Compile with “-shared” argument
58. Position-independent Code (PIC)
• Move the part which should be modified out of normal code sectio
n, then every process can have an individual copy of that section
• Address reference type
Type 1 - Inner-module call
Type 2 - Inner-module data access
Type 3 - Inter-module call
Global Offset Table, GOT
Type 4 - Inter-module data access
Same as type 3
• Compile with “-fPIC” argument
Type 2 - Inner-module data
access
Type 4 - Inter-module data
access
Type 1 - Inner-module call
Type 3 - Inter-module call
59. Global Offset Table (GOT)
.data
.text
.text
.data
int b = 100;
GOT
Process Virtual Space
0x10000000
0x20002000
void ext();0x20001000
...
0x20002000
0x20001000
b
ext()
60. Dynamic Linking Overhead
• Although dynamic linking program is more flexible, but...
• Static linking is faster than dynamic linking program about 1% to
5%
Global , static data access and inter-module calls need complex GOT re-
location
Load program → Dynamic loader have to link the program
61. Lazy Binding
• Bind when the first time use the function(relocation, symbol sea
rching)
• Dynamic loader view
“liba.so” calls function “bar” in “libc.so”
We need dynamic loader do address binding, and assume the work is d
one by function “lookup”
Function “lookup” needs two parameters: module & function
“lookup()” in Glibc is “_dl_runtime_resolve()”
• Procedure Linkage Table, PLT
61
62. Implementation of PLT
• Inter-module function call → GOT
• Inter-module function call → PLT → GOT
• Every inter-module function have a corresponding entry in PLT
Function “bar” in PLT → bar@plt
bar@GOT = next instruction(push n)
n = index of “bar” in “.rel.plt”
• “_dl_runtime_resolve” will modify
“bar@GOT” to actual “bar” address
62
bar@plt
jmp *(bar@GOT)
push n
push moduleID
jump _dl_runtime_resolve
65. Stack
• Stack Frame(Activate Record)
• Return address, arguments
• Temporary variables
• Context
• Frame Pointer(ebp on i386)
• Stack Pointer(esp on i386)
65
Arguments
Return Address
Old EBP
Saved Registers
Local Variables
Others
Activate Record
ebp
esp
0xBFFFFFFF
0xBFFFFFFB
0xBFFFFFF8
0xBFFFFFF4
Stack Example
Stack Bottom
esp
push
pop
66. Calling Convention
• Consistency between caller and callee
• Argument passing order and method
• Stack, Register(eax for return value on i386)
• Stack maintainer
• Keep consistency before and after function call
• Responsibility of caller or callee
• Name-mangling
• Default calling convention in C language is “cdecl”
Arguments passing Stack maintainer Name-mangling
Push into stack from right to
left
Caller Underscore in front of function
name
67. Calling Convention Example
67
int f(int y) {
printf(“%d”, y);
return 0;
}
int main() {
int x = 1;
f(x);
return 0;
}
old ebp
Saved registers & local variables
ebp
esp
x
Return address
old ebp
Saved registers & local variables
ebp
esp
y
Return address
old ebp
Saved registers & local variables
ebp
esp
68. Heap
• Dynamic allocate memory
• Implementation under Linux
int brk(void *end_data_segment)
void *mmap(void *start, size_t length, int prot, int flags, int fd, off_t offset)
• Algorithms for memory allocation
Free List
Bitmap
Object Collection
68
1
2
3
4
5
int main() {
char *p = (char *)malloc(1000 * sizeof(char));
/* use p as an array of size 1000 */
free(p);
}
70. System Call?
• Process can not access system resource directly
• File, Network, Input/Output, Device
• Something we need OS help us
• e.g. for(int i = 0; i < 10000; i++)
• Process management, system resource access, GUI operation...
• Drawbacks
•
Too native → Runtime Library
•
Difference between various OSs
70
71. Privilege
• Modern CPU architectures usually have multi-level design
• User Mode
• Kernel Mode
• high privilege → low privilege is allowed
• low privilege → high privilege is not easy
• Restrict some operations in low privileged mode
• Stability
• Security
• OS usually uses interrupt as mode switch signal
71
72. Interrupt
• Polling
• Interrupt
• Interrupt Index
• Interrupt Service Routine (ISR)
• Hardware interrupt & Software interrupt
72
User mode
execution
Interruption
occured
Next
instruction
Interrupt
Handler
Interrupt
Vector
Table
User Mode
Kernel Mode
73. System Call Example
• rtenv+
• ARM Cortex-M3
• https://hackpad.com/RTENV-xzo9mDkptBW#
73
74. Thinking
• Why do we need to compile the program
• What is in an executable file
• What is the meaning of “#include<stdio.h>”
• Difference between
Compiler(Microsoft VC, GCC)
Hardware architecture(ARM, x86)
• How to execute a program
What does OS do
Before main function
Memory layout
If we don’t have OS
0
1
2
3
~$ vim hello.c
~$ gcc hello.c
~$ ./a.out
Hello World!
Filename: hello.c
0
1
2
3
4
5
6
7
#include <stdio.h>
int main(int argc, char *argv[])
{
printf(“Hello World!n”);
return 0;
}
74