## OSTEP [虚拟] Chapt. 13-15 - 内存虚拟入门

2019-04-16 21:01 CST
2019-06-06 23:24 CST
CC BY-NC 4.0

## 13.4 Goals

• 透明性：在程序眼里就是霸占了物理内存；
• 效率：尽可能高效的虚拟化；
• 内存保护：保护每个进程的内存，实现进程隔离
##### TIP: The Principle Of Isolation

Isolation is a key principle in building reliable systems. If two entities are properly isolated from one another, this implies that one can fail without affecting the other. Operating systems strive to isolate processes from each other and in this way prevent one from harming the other. By using memory isolation, the OS further ensures that running programs cannot affect the operation of the underlying OS. Some modern OS’s take isolation even further, by walling off pieces of the OS from other pieces of the OS. Such microkernels thus may provide greater reliability than typical monolithic kernel designs.

## 14.1 Types of Memory

C程序中有两种分配的内存：栈区内存(stack memory)，由编译器隐式分配，或者叫自动内存(automatic memory)；和堆区内存(heap memory)，由用户显式分配。

14.2 - 14.3 介绍了两个🍔🍔都会用的API：malloc()free()，没啥好学的了。

## 14.4 Common Errors

##### 书上提供的两个提示：
1. Segmentation fault is a fancy term for YOU DID SOMETHING WRONG WITH MEMORY YOU FOOLISH PROGRAMMER AND I AM ANGRY.
2. It compiled or it ran does not equal to it is correct. The problem is usually right where you think it would be, in your code.

• 忘了分配内存 (use strdup() to make life easier)；
• 内存分的不够；
• 忘了初始化分配的内存；
• 忘了释放内存（内存泄漏）；
• 提前释放内存（悬空指针）；
• 重复释放内存 (double free)；
• free()了非malloc()分配的内存；
• ……………………

## 14.5 Underlying OS Support

malloc()free()一类的函数都没有直接接触到系统调用，他们都是库函数。内存管理的系统调用有：

• brksbrk：调整堆区底部位置，但永远不要直接调用这两个系统调用。
• mmap()：在程序中创建一块可以像堆区一样使用的匿名内存区域。

## 14.6 Other Calls

• calloc()：分配并清零内存空间；
• realloc()：分配一块更大的，然后把原来的拷过去。

## 15.1 Assumptions

• 用户的地址空间在物理内存中是连续的；
• 地址空间的大小不是很大，小于物理内存的大小；
• 每个地址空间的大小都一样。

## 15.2 An Example

##### TIP: Interposition Is Powerful

Interposition is a generic and powerful technique that is often used to great effect in computer systems. In virtualizing memory, the hardware will interpose on each memory access, and translate each virtual address issued by the process to a physical address where the desired information is actually stored. However, the general technique of interposition is much more broadly applicable; indeed, almost any well-deﬁned interface can be interposed upon, to add new functionality or improve some other aspect of the system. One of the usual beneﬁts of such an approach is transparency; the interposition often is done without changing the client of the interface, thus requiring no changes to said client.

## 15.3 Dynamic (Hardware-based Relocation)

base和bounds寄存器是芯片中的硬件结构（每个CPU一个），有时也叫做内存管理单元(memory management unit, MMU)。bound寄存器的使用方式有两种：要么保存内存空间的长度/大小，或者保存内存空间尾部的物理地址