Sei sulla pagina 1di 106

Kernel

Kernel

Kernel
II

HISTORIAL DE REVISIONES
NMERO

FECHA

v1.0.0

2013 May 5

MODIFICACIONES

NOMBRE
CA

Kernel
III

ndice
1. Introduction

1.1. Objetivos: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

1.2. Ejercicios Basicos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

2. References

2.1. OFICIALES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

2.1.1. online . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

2.2. Admon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

2.3. Basica . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

2.4. University . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

2.4.1. La construccin del sistema operativo Linux 2.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

2.4.2. Sistemas operativo docente xv6 MIT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

2.4.3. Otros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

2.4.4. Minirighi: IA-32 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

2.4.5. JOS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

2.4.6. linux-book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

2.4.7. linux-slides . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

2.4.8. Universidad de Cantabria . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

2.5. Planetas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

2.6. Apuntes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

2.7. Tutoriales . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

2.8. Libros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

2.8.1. Interfaz del usuario al Kernel: linux programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

2.8.2. Kernel Internals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

2.8.3. Biblioteca . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

2.8.4. Advanced UNIX programming / Marc J. Rochkind . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

2.9. Manuales online . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

2.10. Libros Administracion S.O. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

2.11. Libros generales de SO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

2.12. Metodo aprendizaje . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

2.12.1. Generalidades SO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

3. Tutorial Primer
3.1. Descarga de los fuentes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4. UNIX-like systems: UN*X / *nix

8
8
9

4.1. Asociaciones . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

4.2. Fundamentos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Kernel
IV

5. Linux

11

5.1. Linux Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11


5.1.1. Libros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
5.1.2. Tutoriales . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
5.2. Linux . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
5.3. Linux Standard Base: API, ABI, ELF, DWARF . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
5.4. Linux Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
5.5. Intel-Linux . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
5.6. Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
5.7. LFS: Linux From Scratch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
5.8. Linux-Libre . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
6. Boot-Grub-BIOS

12

6.1. boot-BIOS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
7. Process

12

7.1. Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
7.2. Dudas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
7.3. Parametros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
8. Memory

13

9. Interrupciones

13

10. Drivers

13

11. Instalacin

13

11.1. how-to . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
11.2. postinstalacin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
11.2.1. kernel files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
11.2.2. imagen vmlinux . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
12. Interfaz User-Kernel

14

12.1. Referencia . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
12.2. Introduccion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
12.3. Inter Process Communications (IPC) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
12.4. Interfaz tipo Fichero . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
12.4.1. procfs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
12.4.2. sysfs

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

12.4.3. udev . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
12.4.4. debugfs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
12.4.5. configfs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17

Kernel
V

12.5. Interfaz tipo Socket . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17


12.5.1. Referencias . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
12.5.2. Introduccion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
12.5.3. Mtodo de estudio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
12.5.4. Domain-Type-Protocol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
12.5.5. Diferencia entre socket y fichero . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
12.5.6. Diferencia entre socket y port . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
12.5.7. Linux Command . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
12.5.8. Programming sockets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
12.6. Interfaz System Calls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
12.7. Interfaz ioctl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
12.8. Interfaz signal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
12.9. Interfaz upcall . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
12.10.Interfaz mmap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
12.11.Interfaz sysctl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
13. Virtual File System (Virtual File Switch en Linux-VFS)

23

13.1. Referencias . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
13.2. Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
13.2.1. Metodo de Aprendizaje . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
13.2.2. Fichero . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
13.2.3. Tipos de ficheros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
13.2.4. Bloque . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
13.2.5. Gestor de Ficheros del Kernel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
13.3. Diversidad de Sistemas de Ficheros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
13.3.1. Linux . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
13.3.2. Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
13.3.3. Solaris . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
13.3.4. BSD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
13.3.5. IBM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
13.3.6. btrfs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
13.3.7. Comparativa: Ext, NTFS, etc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
13.4. Lineas Futuras . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
13.5. EXT: Linux File System Evolution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
13.5.1. Referencias Basicas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
13.5.2. Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
13.5.3. EXT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
13.5.4. EXT2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
13.5.5. EXT3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

Kernel
VI

13.5.6. EXT4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
13.6. EXT: Caractersticas Generales . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
13.7. EXT4: Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
13.7.1. Referencias . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
13.8. EXT4: Caractersticas Principales: High Level . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
13.9. EXT4: Caractersticas Principales: Low Level . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
13.9.1. Layout Disk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
13.9.2. Layout Partition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
13.9.3. Layout File System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
13.9.4. Layout SuperBlock . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
13.9.5. Layout Inode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
13.9.6. Directory Indexing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
13.10.Architecture (Capas, Multinivel) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
13.10.1.Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
13.10.2.Estructura top-down del subsistema VFS del kernel. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
13.10.3.Kernel Modules (Device Driver) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
13.10.4.Data Representation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
13.10.5.Data Flow, Control Flow, and Dependencies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
13.11.File Systems Objects (abstracciones) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
13.12.File Descriptor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
13.13.File Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
13.14.Directory Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
13.15.Path . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
13.16.dentry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
13.17.Node . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
13.18.Superblock . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
13.19.Tipos de FS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
13.20.Root File System level: VFS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
13.21.Root File System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
13.21.1.mount . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
13.21.2.CHROOT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
13.22.Devices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
13.22.1.Device File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
13.22.2./dev/loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
14. Virtual Disks

37

Kernel
VII

15. File System EXERCICE

37

15.1. Referencias . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
15.2. Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
15.3. losetup (loop-setup) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
15.4. Tutorial Basico. I. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
15.5. Analisis de la imagen de un sistema de ficheros virtual . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
15.6. FS contenedor del fichero imagen y FS contenido en el fichero imagen . . . . . . . . . . . . . . . . . . . . . . . 42
15.7. Particiones del sistema de ficheros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
15.8. Tutorial Basico. II. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
15.9. tutorial basico III: NTFS virtual disk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
16. File System FORENSICS

47

16.1. Tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
16.2. Books . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
16.3. Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
17. Otros Sistemas de Ficheros

48

17.1. NTFS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
17.2. Fuse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
17.3. gvfs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
17.4. usb:mtp,ptp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
18. DMA

49

19. Graphics: Screen Printing (Video)

49

20. Networking

49

20.1. Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
20.2. ISO Stack Layer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
20.3. TCP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
20.4. WIFI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
21. INTEL: Interfaces Usuario-Sistema: Normativa Unix

50

21.1. Developer Manual . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50


21.2. API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
21.3. ABI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
21.4. ISA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50

Kernel
VIII

22. Compilacin kernel

51

22.1. Tutoriales . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
22.1.1. Excesivamente simple . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
22.1.2. Completo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
22.2. Flavors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
22.2.1. PC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
22.3. Versiones . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
22.4. Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
22.5. Debugger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
23. Instalacion del Kernel

52

23.1. Formato del ncleo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52


24. Kernel Compilation Tutorial : initramfs Gentoo

52

25. Kernel Compilation Tutorial : LFS oficial

52

26. Kernel Compilation Tutorial :desde cero (LFS) para Embedded

53

26.1. Referencia . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
26.2. Introduccin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
26.3. Herramientas Necesarias . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
26.4. Compilacion del Kernel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
26.4.1. Introduccion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
26.4.2. Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
26.4.3. Buildroot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
26.4.4. Download kernel, busybox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
26.4.5. Download uclibc, buildroot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
26.4.6. Create uclibc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
26.4.7. Create toolchain for uclibc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
26.4.8. Duda . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
26.4.9. Create kernel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
26.4.10.Create filesystem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
26.4.11.Create Busybox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
26.4.12.Fill filesystem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
26.5. Emulate kernel and filesystem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
26.6. FUNCIONA O NO FUNCIONA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
27. QEMU

58

28. Kernel Compilation and QEMU Tutorial: ARM

58

28.1. blogs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58

Kernel
IX

29. Kernel Compilation Tutorials: Embedded

58

29.1. General . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
29.2. Flavors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
29.3. Platforms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
30. Kernel: Small, Tiny

59

30.1. Referencias . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
30.2. How to Build A Custom Linux Kernel For Qemu (2015 Edition) . . . . . . . . . . . . . . . . . . . . . . . . . . 59
31. TEST

59

31.1. Evaluacin del Kernel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59


32. TODO: ME GUSTARIA

60

32.1. bare metal con la bios . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60


32.2. Juntar los tutoriales bare_metal vga color y teclado . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
32.3. baremetal-qemu-kernel(keyboard-busybox)-file system . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
33. Tutorial Boot Sector Susam Palm

60

34. Tutorial Bare Metal: osdever hello world

61

35. Tutorial Bare Bones: Viridis

61

36. Tutorial Bare Bones: Arjun Sreedharan

62

36.1. Kernel 101 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62


36.1.1. intro . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
36.1.2. kernel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
36.1.3. boot process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
36.1.4. kernel building . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
36.1.5. Emulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
36.1.6. Building a bootable cdrom image . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
36.1.7. Bootloader on disk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
36.2. Kernel 201 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
36.2.1. info . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
36.2.2. source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
36.2.3. Build . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
37. Tutoriales Bare Bones OsDev

66

38. Tutorial Bare Bones: OSDev Myos: 64 bits

66

Kernel
X

39. Tutorial Bare Bones: OSDev MyOS: i686-elf

66

39.1. Boot y kernel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66


39.2. Emulacion del kernel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
39.3. Emulacin del multiboot con grub . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
39.4. Kernel Debug . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
40. Tutorial BareMetal Farid

74

40.1. Introduccin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
40.2. Hello World con kernel freebsd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
40.3. Hello World Bare Metal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
40.3.1. Introduccin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
40.3.2. carpeta tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
40.3.3. fundamentals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
40.3.4. Source Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
40.3.5. Compilation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
40.3.6. Execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
40.3.7. Desensamblaje . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
41. Tutorial Baremetal: hello world rectangle Bosch

83

42. Tutorial Baremetal framebuffer

83

43. Tutorial BareMetal: O.S. Development Series de Mike (Neptune)

84

43.1. Tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
43.1.1. Problemas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
43.2. Referencia . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
43.3. Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
43.3.1. C and executable formats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
43.3.2. kernel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
43.3.3. physical address space . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
43.3.4. Dynamic Memory Allocation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
43.3.5. Inline Assembly . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
43.3.6. C standard library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
43.3.7. C Run Time Library (RTL) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
43.3.8. Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
43.4. Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
43.4.1. Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
43.5. The Build Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
43.5.1. VFD - Virtual Floppy Drive . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
43.5.2. Floppy Image on linux . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86

Kernel
XI

43.5.3. NASM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
43.5.4. Copying the Boot Loader . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
43.5.5. Test del floppy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
43.5.6. Bochs Emulator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
43.5.7. Error . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
43.5.8. boot2.asm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
43.5.9. BIOS Parameter Block(BPB) (OEM Parameter) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
43.6. Basic Theory and History . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
44. Websofia BareMetal: Writing your own toy operating system

90

45. Princeton BareMetal

90

46. TUTORIAL PERSONAL PRIMER

90

46.1. Descargar el source kernel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91


46.2. Anlisis de los fuentes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
46.3. preBuild . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
46.4. tools: kconfig, makefile, config. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
46.5. Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
46.6. Build core vmlinux image and their modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
46.7. Anlisis del ncleo vmlinux generado y sus mdulos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
46.8. Resumen de comandos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
46.9. eclipse & source code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
46.10.compile & debug & qemu & eclipse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
47. Glosario

94

Kernel
XII

ndice de cuadros
1.

Tipos de IPC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

2.

Comparativa . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

Kernel
1 / 94

1.

Introduction

1.1.

Objetivos:

Estudiar exhaustivamente la estructura interna del ncleo del Sistema Operativo Linux
Interactuar con la estructura del kernel a travs de APIs del Sistema Operativo
Info del gestor de procesos
Info del gestor de memoria
Info de la red
Info del sistema virtual de ficheros
Info del sistema de ficheros de dispositivos tipo bloque
Info de los dispositivos de tipo carcter
Info de los mdulos del kernel drivers

1.2.

Ejercicios Basicos

Drivers: desarrollar un driver sencillo


Sistema de Ficheros: crear una jaula chroot
Instalar el Kernel desde cero

2.

References

2.1.

OFICIALES

2.1.1.

online

http://www.linfo.org/kernelresources.html
phoronix
News Linux: HW architecture, Kernel
https://www.kernel.org: no solo tengo los fuentes, tambin documentacin, herramientas, etc
https://www.kernel.org/pub/software/scm/git/: aqu tengo la herramienta git
https://www.kernel.org/category/releases.html: al final estn las wikis, planet
source home release
Puedo DESCARGA la versin estable 3.9.2 el 15 de Mayo 2013: versin git, versin comprimida tar 69 MB.
https://www.kernel.org/pub/linux/kernel/v3.x/ TODAS LAS VERSIONES
https://github.com/torvalds/linux
git online tree: recomendado
Por ejemplo DMA-API_HOWTO
documentation: recomendado. Enlaces a las fuentes oficiales de diferentes topics: C, ABI, ELF, ARM, SUS, etc
Doc:

Kernel
2 / 94

 Linux kernel source tree documentation. Se puede hacer un make en los fuentes linux-3.9.2$ make pdfdocs
y generar pdf si estn bien instaladas los paquetes utils-docbook y latex
 informacin sobre la arquitectura del kernel
[Error: itemizedlist too deeply nested]
 referencias sobre libros
 HOWTO: No es info tecnica sino how to become a Linux kernel developer and how to learn to work with the Linux
kernel development community: referencias a recursos como libros
API: librera de funciones para desarrollar el kernel.
Ejemplo de doc : proc filesystem
 esta misma info est en http://tldp.org/LDP/Linux-Filesystem-Hierarchy/html/proc.html
 esta info esta en la distribucin
wiki: info de algunos topicos: ata,
Linux Source Code - Linux Cross Reference:
Cdigo fuente de todas las versiones del kernel: Navegable
Entre los archivos del kernel en la carpeta pub estn los archivos pblicos, entre los cuales se provee de una serie de servicios,
utilidades, etc:
distribucion knopixx
utils
util-linux
 comando losetup (loop-setup) que asocia un fichero al pseudo-device loop
 klibc: libera c del kernel
 http://code.metager.de/source/xref/linux/klibc/usr/utils/ : losetup.c source code
utils
open group: SUS manual: API
exhaustivo
Miles de Articulos muy avanzados de aspectos muy concretos del kernel
Fuentes del kernel
tdlp: viejo pero bsico
linux home: Muy general. Cursos malillos primer, intermediate, avanced
http://www.makelinux.net: recomendado
http://www.makelinux.net/resources links a libros
linux kernel: online
Advancede Linux Programming
poster
glossary
proyectos: bueno
proyectos de aprendizaje practico
Documentos: articulos bsicos, listado de libros
osdever:muchos tutoriales y diversos a nivel bajo

Kernel
3 / 94

2.2.

Admon

Red Hat
Debian
Oracle
pdf
html
Archlinux
archlinux
gentoo

2.3.

Basica

http://en.wikipedia.org/wiki/Linux

2.4.
2.4.1.

University
La construccin del sistema operativo Linux 2.0

En polaco: pero en translate castellano funciona bastante bien.


2.4.2.

Sistemas operativo docente xv6 MIT

2.4.3.

Otros

http://inst.eecs.berkeley.edu/~cs194-24/sp13/index_overview.html: Lectures,linux, QEMU,VMware


http://cs.smith.edu/~nhowe/262/csc262.html
http://www.cs.rutgers.edu/~pxk/416/notes/index.html
decente: historia, linux kernel style, etc
rutgers: muy claro. Por ejemplo la gestin de memoria con buenas referencias
ops-class: compila el kernel, clases en video, practicas con gdb, git, eclipse, etc
slides argentina
rochester
Silberschatz, Galvin, and Gagne, (SGG), Gary Nutt, Andrew S. Tanenbaum, Dave OHallaron, Randal Bryant, and Kai Shen
Linux: Bovet, Love, Mauerer, Stevens
QEMU
Realizo apuntes con los ejercicios del curso: Apuntes Rochester
Osvaldo Argentina
slides buenos pero hay que saber interpretarlos
http://www.cs.uic.edu/~jbell/CourseNotes/OperatingSystems/
los apuntes esquematicos del libro de Silberschatz permiten un recordatorio rpido

Kernel
4 / 94

http://cseweb.ucsd.edu/classes/su10/cse120/
los apuntes esquematicos del libro de Silberschatz permiten un recordatorio rpido
http://www.shsu.edu/csc_tjm/cs431/
los apuntes esquematicos del libro de Silberschatz permiten un recordatorio rpido
http://pages.cs.wisc.edu/~dusseau/Classes/CS537-F04/#schedule
CS 537: Introduction to Operating Systems . Fall 2004. Operating System Concepts (6th Edition), by Silberschatz, Galvin,
and Gagne;Modern Operating Systems by Andrew Tanenbaum. Operating Systems: A Modern Perspective by Gary Nutt
Ejercicios con soluciones.
http://etc.unitbv.ro/~danciu/cursuri_so/
buenas transparencias
http://www.win.tue.nl/~aeb/linux/lk/lk.html: del 2003 pero es corto y claro.
carnegie mellon
http://www.enseignement.polytechnique.fr/informatique/INF583/
buscar en delicious
2.4.4.

Minirighi: IA-32

minirighi
Minirighi is a multi-threading operating system for IA-32 architecture. The main feature of Minirighi is its light kernel, easy
to read from all, simply by analyzing the source code, unlike many other open-source kernels.
Ver el apartado Device Drivers: rs232, keyboar, etc
2.4.5.

JOS

Sistemas operativo docente xv6 MIT


The JOS lab was developed at MIT, and has been used at several other universities, including Stanford, Texas, and UCLA.
Harvard 2011
CSE 506: Operating Systems F14
CSE 506: Operating Systems F12
Harvard 2004
harvard 2015
pc bootstrapping : Bochs emulation
Stanford
NYU mwalfish:2014
ucla university jos?

Kernel
5 / 94

2.4.6.

linux-book

MCS-378: Operating Systems (Fall 2009)


LIbro recomendado :Operating Systems and Middleware: Supporting Controlled Interaction
Genera un kernel desde ubuntu
The Art of Linux Kernel Design: Illustrating the Operating System Design Principle and Implementation.Lixiang Yang
http://www.blaess.fr/christophe/category/livres/
Principles of Operating Systems: Design and Applications (Advanced Topics) 1st Edition by Brian Stuart (Author) ISBN-13:
978-1418837693
2.4.7.

linux-slides

http://linux.linti.unlp.edu.ar/index.php?title=P%C3%A1gina_principal
2.4.8.

Universidad de Cantabria

http://www.ctr.unican.es/asignaturas/dec/Doc/kernel_cpu_memoria.pdf

2.5.

Planetas

vicente navarra: compila el kernel para la tarjeta grfica VIA EPIA y configura el sistema operativo para dicha tarjeta.

2.6.

Apuntes

universidad polaca: guin con referencias al cdigo fuente del kernel del repositorio Linux Source Code - Linux Cross Reference

2.7.

Tutoriales

osdever: Recomendado mltiples tutoriales


brans development:
info sobre como desarrollar un kernel bsico. Como inicializar las interruciones
escribir un sector del disco: utiliza bochs
Cmo desarrollar un kernel simple

2.8.
2.8.1.

Libros
Interfaz del usuario al Kernel: linux programming

Advanced Programming in the UNIX Environment


Programacin en C desde el espacio de usuario pero a muy bajo nivel, interactuando con el Kernel de Unix, con llamadas
al sistema muy primitivas. This book describes the programming interface to the Unix systemthe system call interface and
many of the functions provided in the standard C library
online
Descargado.Recomendado. Semilla Un clsico. Prctico.
El 17 de Mayo 2013 sale la 3 Edicin. Linux 3.2.0.STREAMS-related material was removed. No pirateado

Kernel
6 / 94

(Addison-Wesley Professional Computing Series) [Hardcover].W. Richard Stevens, Stephen A. Rago. 2 Edicin 2005.
university
Advanced UNIX Programming:
Marc J. Rochkind. 2 Edition. Addison Wesley Professional Computing Series.
Detalle de las interfaces HOW TO.
Recomendado. Lo cojo de la biblioteca
Linux System Programming (December 5, 2007):
Love. Programacin en C desde el espacio de usuario pero a muy bajo nivel, interactuando con el Kernel de Linux, con
llamadas al sistema muy primitivas. Equivalente al de Richard Stevens pero en lugar de Unix/BSD, lo hace con Linux.
Descargado.
Linux Programming Interface:
Realmente intenta abarcar conceptos generales de sistemas operativos y las intefaces. Es decir, no est estrictamente especializado en programacin.
Michael Kerrisk.2010.Descargado. recomendado
beginning
Beginning Linux Programming 4th Edition Neil Matthew Richard Stones
Sencillo. No requiere muchos conocimientos de S.O. Explica hasta como compilar, shell programming.
ethz:
Escueto pero recomendado. ONLINE.
This document is written for programmers with some experience in system programming
Hace referencias a fuentes de informacin especializadas en el kernel, por lo que no es un documento cerrado. No recomendado para principiantes pero s ayuda a extraer los conceptos pilares del kernel.
listado de libros:
kernelnewbies: referenciado en la linux foundation.
Art of linux programming:
Eric Raymond. Filosofico. Descargado
unix system programming:
Robbins. Practico. 2 Edicin. Descargado
the documentation linux project:
guides
Programacin de Sistemas Pablo Garaizar Sagarminaga
Lo escrito es bsico y muy claro. El problema es que trata pocos temas: procesos con tuberas

Kernel
7 / 94

2.8.2.

Kernel Internals

http://oss.sgi.com/LDP/HOWTO/Kernel-HOWTO/index.html
Prof Linux Kernel Arch Wolfgang Mauerer
Recomendado Descargado
Muy sintetizado
Referencias a modulos fuente del kernel que definen funciones.
listado de libros
Linux Kernel Development, Second Edition (March 9, 2005): Love 2 Edicion
Linux Kernel Development, Third Edition (December 15,2010): Love . Recomendado
The Linux Kernel Primer (October 5, 2005):The Linux Kernel Primer: A Top-Down Approach for x86 and PowerPC Architectures . Descargado. En la biblioteca.
Understanding the Linux Kernel, 3rd Edition (November 22, 2005): Daniel P. Bovet. OReilly. Descargado. Explicacin de
la funcionalidad del kernel linux y su implementacin en el cdigo fuente. Recomendado.
Understanding Linux Network Internals (January 24, 2006) Oreilly
User Mode Linux (May 16, 2006): UML. Virtualizacion. Descargado
Linux Kernel in a Nutshell (February 7, 2007): Kroah. online. Descargado. download, compile, and install a new kernel
California-Irvine: demasiado terico.
https://gustavus.edu/+max/os-book/: recomendado ms arriba
https://0xax.gitbooks.io/linux-insides/content/index.html: recomendado ingls y espaol. Lo he utilizado para estudiar un
poco la gestin de las interrupciones.
https://github.com/leolas95/linux-insides: en espaol
2.8.3.

Biblioteca

Advanced UNIX programming / Marc J. Rochkind


UPNA ARRO DPTO PISO 2 O 551d Unix-11-1-2004 Disponible
Advanced programming in the UNIX environment / W. Richard Stevens, Stephen A. Rago
UPNA ARRO ALUM O 551d Unix-5-1-2005 Disponible
UNIX programacin prctica / Kay A. Robbins y Steven Robbins ; traduccin [de la 1 ed. en ingls] Roberto Escalona Garca
; revisin tcnica, Gabriel Guerrero
UPNA ARRO ALUM O 551d Unix-3-4 Disponible
UPNA ARRO DPTO PISO 2 O 549 UNIX-15-1 Prestado hasta 21.03.14
2.8.4.

Advanced UNIX programming / Marc J. Rochkind

El objetivo del libro no es como est implementado el kernel, ni como utilizar los comandos del interprete bash shell. El
objetivo es ensear a utilizar las llamadas al sistema, call system, del kernel desde las aplicaciones de usuario. Se ensea el
How y tambin se indican las virtudes y defectos de las llamadas.
El libro empieza indicando como podemos especificar en una plataforma determinada qu API utilizar, y que opciones de una
API determinada autorizar.

Kernel
8 / 94

2.9.

Manuales online

debian-reference

2.10.

Libros Administracion S.O.

Essential System Administration


Linux Administration Handbook
Linux User Guide ,tdlp.

2.11.

Libros generales de SO

Operating System, Gary Nutt: Libro general sobre sistemas operativos


Stalling
Silberchatz
Tanembaum
referencias

2.12.

Metodo aprendizaje

2.12.1.

Generalidades SO

Professional Linux Kernel Architecture Wolfgang Mauerer. Libro de arranque.


Gary Nutt : Procesos
Michael Kerrisk para el detalle de Unix/Linux: sistemas de ficheros, etc . Pasarlo al kernel
Rotchking para la programacin en C de aplicaciones con llamadas al Kernel (procesos, dispositivos, etc). Detalle de las
interfaces de las llamadas, HOW usarlas. Pasarlo al kernel.

3.
3.1.

Tutorial Primer
Descarga de los fuentes

Descargo la versin que tiene un mantenimiento a largo plazo. En https://www.kernel.org/category/releases.html observo que
la versin 3.2 tiene mantenimiento hasta el 2016.
En ubuntu uname -r veo que precisamente tiene la versin 3.2
3.2.0-61-generic : al haber un guin despus de la versin significa que no es un kernel puro sino una distribucin.
sitio de descarga
en protocolos http, ftp, tengo
signatures, archivo tar y patch. Los patch son desviaciones del original para solucionar problemas o aadir una extensin
particular. ftp://ftp.kernel.org/pub/ linux kernel : ftp://ftp.kernel.org/pub/linux/kernel/v3.x/
tambin tengo tools crosscompilers
Pincho en 3.2.59 cgit pincho en el titulo index : kernel/git/stable/linux-stable.git
Me imagino que https://github.com/torvalds/linux es el repositorio git de la ltima versin o de qu versin
Hay que leerse el README: These are the release notes for Linux version 3.

Kernel
9 / 94

4.
4.1.

UNIX-like systems: UN*X / *nix


Asociaciones

Linux Foundation :
La fundacin linux es la madre de linux
Servicios: Noticiario, blogs, documentos
Linux Foundation: news, tutorials, etc
http://www.linuxfoundation.org/
https://www.usenix.org/about
the USENIX Association has brought together the community of engineers, system administrators, scientists,
members login

4.2.

Fundamentos

Versin 7 Unix
nacimiento de Unix en los laboratorios Bell en 1979: la versin 7 es la primera versin portable
Es el origen de C, make, lint, lex, yacc, herramientas bsicas de desarrollo, bash, awk, umask, system calls, pcc compiler,
....
brief history and book
The UNIX V7 Product Standard is a significantly enhanced version of the UNIX 03 Product Standard. The most significant
change is alignment with the Single UNIX Specification, Version 4 that includes The Open Group Base Specifications,
Issue 7, and approved Technical Corrigenda (if any).
ms historia hasta el pinguino
UN*X: 2 versiones principales de Unix:
BSD de Berkeley University comercializado por Sun y SysV creado y comercializdo por AT&T
SysV:
Unin entre AT&T y Sun microsystems
Versin comercial: System V Release 4 - SVR4
SysV: en las distintas versiones se puede ver la compatibilidad de SVR4 con posix, abi, etc
unix war:
rbol genealgico de las familias *nix
Guerra entre OSF de HP, DEC, IBM y Unix International de AT&T,Sun por la creacin de un open standard standard
pblico. En Europa el X/Open de Bull, ICL, Siemens, Olivetti, and Nixdorf estaba en tierra de nadie.
La paz llega en 1996 con el Open group formado por empresas y asociaciones gubernamentales americanas y japonesas
como: Capgemini, Fujitsu, Oracle, Hitachi, HP, Orbus Software, IBM, Kingdee, NEC, SAP, US Department of Defense,
NASA and others.
Open group:
Standard Single Unix Specification-SUS
Extiende la norma POSIX y actualmente es la definicin OFICIAL de un sistema Unix.
actualmente en la norma Versin 4
SUS-v4

Kernel
10 / 94

The Single UNIX Specification Version 4 - incorporating POSIX (IEEE Std 1003.1 ISO/IEC 9945:2009) and integrating
the industrys Open Systems standards
Compatible con The ISO/IEC 9899:1999 standard Standard C.
There are now 1833 interfaces defined in the Single UNIX Specification, Version 4. The table below gives the breakdown
for each volume of the Single UNIX Specification: XSH(1191)+ XCU(174)+ XBD(82)+ XCURSES(386).
Tiene links a test de software test-suite: Unix, linux, embedded, posix, real-time
Manual PDF: 5 Volmenes: XBD, XSH,XCU,XRAT y XCURSES
POSIX: Manual: Clicar Frames Index para tener a la derecha un ndice.
"Portable Operating System Interface"
Core programming interface : Describe las llamadas al sistema
standarizado por la Asociacin IEcubo: IEEE Std 1003.1-1988 llamado Internacionalmente como ISO/IEC 9945:2009 (
A technical corrigendum was approved in August 2012 - ISO/IEC 9945:2009/Cor 1:2013(E))
la ltima versin es Posix-2008.1 (IEEE Std 1003.1-2008) que incluye 4 volumenes:
 the Base Definitions, Issue 7 (Open Group) : Volumen XBD.Glosario de reglas y definiciones. Por ejemplo dice que
cuando emplea el verbo shall significa de obligado cumplimiento.
 the System Interfaces and Headers, Issue 7, : Volumen XSH.Describe las Interfaces de LLamadas al kernel del sistema
que las implementar el Kernel mediante funciones de C. Define las Cabeceras de las Interfaces al Sistema. Describe
la interfaz de una librera: prototipos y cabeceras:The C POSIX library is a specification of a C standard library for
POSIX systems
[Error: itemizedlist too deeply nested]
 the Commands and Utilities, Issue 7. : Volumen XCU. Shell & Utilities: Lenguaje de Comandos para el interprete shell.
Trata sobre la sintaxis mas que sobre el lxico. Es decir trata del HOW utilizar los comandos y realizar un programa
mediante el lenguaje de comandos. Respecto de las utilidades: dd, cp, awk, bc, sed, yacc, make,c99, ctags, kill . . . ,
acceder desde el men principal. Hay utilidades que se corresponden con la misma funcionalidad que una llamada al
sistema, por eso en la descripcin de la utilidad aparece la notacin XSI (Ver codes en el manual XBD), indicando que
se acuda a la informacin del volumen del manual XSI a la interfaz del sistema con el mismo nombre: Un ejemplo es
la utilidad kill y la llamada kill() [Error: itemizedlist too deeply nested]
 Rationale for base definition: Volumen XRAT. Explica cual ha sido el razonamiento para desarrollar la norma
[Error: itemizedlist too deeply nested]
 XCURSES is not part of the Base Specifications, Issue 7, but is a separate Open Group Technical Standard. XCURSES
describes a set of interfaces providing a terminal-independent method of updating character screens that are available
to application programs on systems conformant to this part of the Single UNIX Specification.
[Error: itemizedlist too deeply nested]
Berkeley Software Distribution-BSD:
BSD, despus de la Unix-war no form parte del Open Group y fue por libre
openBSD
netBSD
DragonFly_BSD
FreeNAS : FreeNAS is a free, open source, Network-Attached Storage operating system based on FreeBSD
freeBSD: FreeBSD has long been a popular choice for server systems and embedded applications requiring a high level
of security and stability
GNU
1983: sistema operativo UN*X
gnu project
http://en.wikipedia.org/wiki/GNU_Hurd [kernel gnu hurd]
Resumen

Kernel
11 / 94

Hay dos lneas unix: BSD y SysV


La asociacin Open Group dentro de las diferentes normas que tiene, tiene dos relacionadas con Unix que son SUSv4 y POSIX
y que estn alineadas por lo que son la misma. Slo hay una documentacin oficial: la SUSv4.
Se pueden bajar los 5 volumenes en formato html o el 5 volumen xcurses en formato pdf

5.
5.1.
5.1.1.

Linux
Linux Programming
Libros

Ver books en referencias


5.1.2.

Tutoriales

http://www.linuxjournal.com/article/8381

5.2.

Linux

Linux cumple con el API POSIX y con el ABI LSB que est basado en el ABI SYSV-X86-64
GNU es una extensin de POSIX creando un Sistema Operativo mucho ms eficaz.

5.3.

Linux Standard Base: API, ABI, ELF, DWARF

http://www.linuxfoundation.org/collaborate/workgroups/lsb
http://es.wikipedia.org/wiki/Linux_Standard_Base
Linux Standard Base
Linux Standard Base Doc: mal camino ya que se llega a documentacin obsoleta
Especificaciones de Referencia de Linux Fundation: camino correcto hacia info actualizada
LSB: Incluye tanto API (interfaces de lenguajes de alto nivel como C) como ABI (interfaces en lenguaje mquina o ensamblador) pero est obsoleto
FHS: Jerarqua del sistema de ficheros
API
DWARF: Compatible with the DWARF debugging format used at the time by SVR4 compilers and debuggers from AT&T.
Ver gdb
wikipedia

5.4.

Linux Images

downloads ISO: muchos enlaces rotos

5.5.

Intel-Linux

intel open software: tools, kernel, etc

Kernel
12 / 94

5.6.

Documentation

http://linux.die.net/: manuals, commands, docs

5.7.

LFS: Linux From Scratch

Linux from scratch


http://www.linuxfromscratch.org/lfs/

5.8.

Linux-Libre

GNU FSF kernel

6.
6.1.

Boot-Grub-BIOS
boot-BIOS

boot-BIOS

7.
7.1.

Process
Commands

leer el man ps
ps --help
ps -aucandido : list process (all of user candido)
ps -e: todos los del sistema
ps -C firefox : proceso cuyo nombre comando es firefox
ps -fC firefox : full format : ojo , importa el orden de las opciones
ps -jC firefox: job format
ps -ejH | more : all system, job format, Hierarchy : tree padres e hijos de todo el sistema
pstree : arbol de todos los procesos
top
pgrep firefox : visualiza el pid
pgrep sh
ps H : only threaders
ps -eo pid,user,args,flags --sort user :
e: all system, o: output format
especificadores de formato: primera columna pid, 2 user, 3 args, 4 flags
sort user: agrupar por usuarios

Kernel
13 / 94

ps -eo eip,esp : instruction pointer, stack pointer


tree de un proceso en concreto
pstree pgrep firefox
candido@lur:~$ pgrep firefox
7048
candido@lur:~$ pstree 7048 --> PID como argumento
firefox─┬─plugin-containe───3*[{plugin- containe}]
└─38*[{firefox}]
----------------------------------> 1 padre y
37 hijos
candido@lur:~$ pstree pgrep firefox
firefox─┬─plugin-containe───3*[{plugin- containe}]
└─38*[{firefox}]

pstree -p pgrep firefox


kill -s SIGTSTP %1 : enva una seal al proceso
cat ~/.bash_history - historial de los comandos ejecutados en la sesin

7.2.

Dudas

How can I log all process launches in Linux?

7.3.

Parametros

Un proceso est asociado a un:


sesion
usuario
terminal

8.

Memory

Understanding The Linux Virtual Memory Manager. Mel Gorman Prentice Hall. Descargado

9.

Interrupciones

interrupciones

10.

Drivers

11.

Instalacin

11.1.

how-to

https://www.kernel.org/
git tutorial

Kernel
14 / 94

11.2.

postinstalacin

11.2.1.

kernel files

http://oss.sgi.com/LDP/HOWTO/Kernel-HOWTO/kernel_files_info.html
11.2.2.

imagen vmlinux

http://blog.packagecloud.io/eng/2016/03/08/how-to-extract-and-disassmble-a-linux-kernel-image-vmlinuz/
https://raw.githubusercontent.com/torvalds/linux/master/scripts/extract-vmlinux

12.

Interfaz User-Kernel

12.1.

Referencia

Referencia : http://people.ee.ethz.ch/~arkeller/linux/kernel_user_space_howto.html

12.2.

Introduccion

Debido a que el kernel tiene privilegios que no tiene el usuario como por ejemplo el acceso al hardware, es necesario que el
kernel y el usuario se comuniquen de distintas maneras (Ver IPC, interprocess communications), mediante distintas interfaces:
procfs
sysfs
debugfs
configfs
socket
ioctl
system call
signal
upcall
mmap
sysctl

12.3.

Inter Process Communications (IPC)

http://en.wikipedia.org/wiki/Inter-process_communication#Main_IPC_methods
Cuadro 1: Tipos de IPC
Method

Short Description

File

A record stored on disk that can be


accessed by name by any process

Provided by (operating systems or


other env.)
Most operating systems

Kernel
15 / 94

Cuadro 1: (continued)
Method

Short Description

Signal

A system message sent from one


process to another, not usually used
to store information but instead give
commands.

Socket

A data stream sent over a network


interface, either to a different
process on the same computer or to
another computer
An anonymous data stream similar to
the pipe, but stores and retrieves
information in packets.
A two-way data stream interfaced
through standard input and output and
is read character by character.
A pipe implemented through a file on
the file system instead of standard
input and output.
A simple structure that synchronizes
threads or processes acting on shared
resources.
Multiple processes given access to
the same memory, allowing all to
change it and read changes made by
other processes.
Similar to the message queue.

Message
queue
Pipe

Named pipe

Semaphore

Shared
memory

Message
passing
(shared
nothing)
Memory-mapped
file

12.4.

A file mapped to RAM and can be


modified by changing memory addresses
directly instead of outputting to a
stream, shares same benefits as a
standard file.

Provided by (operating systems or


other env.)
Most operating systems;
some systems, such as
Windows, implement
signals in only the C
run-time library and
provide no support for
their use as an IPC
method[citation needed]
Most operating systems

Most operating systems

All POSIX systems,


Windows
All POSIX systems,
Windows
All POSIX systems,
Windows
All POSIX systems,
Windows

Used in MPI paradigm,


Java RMI, CORBA, DDS,
MSMQ, MailSlots, QNX,
others
All POSIX systems,
Windows

Interfaz tipo Fichero

Una forma de comunicarse usuario y kernel es mediante un sistema de ficheros como forma de almacenar datos estructurados
en ficheros.
El kernel genera un sistema de ficheros en el espacio de usuario que es utilizado para escribir/leer por ambos (el kernel y por
usuario)
El usuario puede escribir parmetros de configuracin del kernel mientras este se est ejecutando
El sistema de ficheros es virtual, se implementa en RAM. Tambin se llama pseudo-file system por ser virtual y no tener
asociado un dispositivo de almacenamiento permanente que almacene bloques.

Kernel
16 / 94

12.4.1.

procfs

Sistema de ficheros con info de los procesos en ejecucin


Se monta en /proc
El subdirectorio /proc/sys no utiliza la intefaz tipo sistema de ficheros sino la interfaz tipo sysctl
Hay que configurar el kernel para que al compilarlo genere el procfs: CONFIG_PROC_FS=y
API
dos apis como interfaz de operaciones de los mdulos del kernel:
1. Legacy procfs API: The use of this API is well described in the "Linux Kernel Procfs Guide" distributed with the Linux
kernel source code
2. The seq_file API:
12.4.2.

sysfs

Tipo nodev, es decir, no tiene un device fsico asignado por lo que es virtual.
Sistema de ficheros con info de los devices y los drives
inicialmente se denomin ddfs: device driver file system
Es sistema de ficheros (estructura en arbol con directorios,subdirectorios,ficheros y enlaces entre s) est montado en
$mount
sysfs on /sys type sysfs (rw,noexec,nosuid,nodev)
12.4.3.

udev

https://docs.oracle.com/cd/E37670_01/E41138/html/ch07s03.html
https://wiki.debian.org/udev
udev device manager dynamically creates or removes device node files at boot time or later
When creating a device node, udev reads the devices /sys directory for attributes such as the label, serial number, and bus
device number.
Udev uses rules files that determine how it identifies devices and creates device name
Create a rule file under /etc/udev/rules.d with a file name such as 10-local.rules that udev will read before any other rules file
udev on /dev type devtmpfs (rw,mode=0755)
The /dev directory contains device files (also sometimes known as device special files and device nodes)
Ejemplo de comandos
Ver ejemplo en apuntes smartphone

Kernel
17 / 94

12.4.4.

debugfs

Tipo nodev, es decir, no tiene un device fsico asignado por lo que es virtual.
Sistema de ficheros que se utiliza para depurar un sistema de ficheros. Permite analizar y tambin configuarlo. Por ejemplo se
utiliza para recuperar archivos borrados.
Se monta en /sys/kernel/debug
$ mount | grep debugfs
none on /sys/kernel/debug type debugfs (rw)
$ sudo ls -l /sys/kernel/debug/
[sudo] password for candido:
total 0
drwxr-xr-x 2 root root 0 Jul 25
drwxr-xr-x 31 root root 0 Jul 25
drwxr-xr-x 3 root root 0 Jul 25
drwxr-xr-x 4 root root 0 Jul 25
drwxr-xr-x 2 root root 0 Jul 25
-r--r--r-- 1 root root 0 Jul 25
drwxr-xr-x 3 root root 0 Jul 25
drwxr-xr-x 2 root root 0 Jul 25
drwxr-xr-x 2 root root 0 Jul 25
drwxr-xr-x 2 root root 0 Jul 25
drwxr-xr-x 3 root root 0 Jul 25
drwxr-xr-x 2 root root 0 Jul 25
drwxr-xr-x 3 root root 0 Jul 25
-rw-r--r-- 1 root root 0 Jul 25
-r--r--r-- 1 root root 0 Jul 25
drwxr-xr-x 6 root root 0 Jul 25
drwxr-xr-x 3 root root 0 Jul 25
-r--r--r-- 1 root root 0 Jul 25
drwxr-xr-x 2 root root 0 Jul 25

2013
14:46
14:43
2013
2013
2013
14:43
2013
14:43
2013
2013
2013
2013
2013
2013
2013
2013
2013
2013

acpi
bdi
bluetooth
dri
extfrag
gpio
ieee80211
kprobes
kvm
mce
mmc0
regmap
regulator
sched_features
suspend_stats
tracing
usb
wakeup_sources
x86

info
man debugfs
kernel documentation
$ ls -l /usr/src/linux-3.4.4/Documentation/filesystems/debugfs.txt
-rw-rw-r-- 1 root root 8322 Jun 22 2012 /usr/src/linux-3.4.4/Documentation/filesystems/ debugfs.txt
-> el documento tiene poco inters.

tutoriales
no he encontrado, por lo que solo queda experimentar
12.4.5.

configfs

12.5.

Interfaz tipo Socket

12.5.1.

Referencias

12.5.2.

Introduccion

Socket: Enchufe
Es un tipo de inter-process communication (IPC).
La idea principal es:

Kernel
18 / 94

Un socket es una INTERFAZ para los programas de usuario que facilita las comunicaciones IPC, por ejemplo para comunicarse a travs de internet queremos una herramienta que comunique el proceso cliente con el proceso servidor a travs de una
red de comunicaiones. El socket es una herramienta proporcionada por el sistema operativo. Un smil entre socket y telfono:
El telfono sera la aplicacin de usario (agenda, marcador, etc ) y el socket sera todo lo relacionado con lo necesario por el
usuario para la conexin con la red de telefona (terminal telefnico, compaia proveedora de la red, nmero de telfono origen, nmero de telfono destino, seal acstica, colgar, descolgar, etc). La implementacin de todas esas funciones y recursos
(socket) para el usuario, es responsabilidad del sistema operativo.
Visualizacin
Diagrama User communications applications process socket port TCP IP

La frontera entre user y kernel es el socket.


Ejemplo
user application: navegador firefox application level: HTTP
Transport level : TCP (fiable)
la frontera entre HTTP y TCP la establece el socket
Network Level: IP
Link Level: ethernet
Beside the file system based mechanism described in the last section, there are mechanisms based on the socket interface. Sockets
allow the Linux kernel to send notifications to a user space application. This is in contrast to the file system mechanisms, where
the kernel can alter a file, but the user program does not know of any change until it choses to access that file, por lo que la
comunicacin es asncrona. The socket based mechanisms allow the applications to listen on a socket, and the kernel can send
them messages at any time, por lo que la comunicacin entre los procesos es en tiempo real. This leads to a communication
mechanism in which user space and kernel space are equal partners.
Un socket es una plataforma que abstrae las comunicaciones entre 2 procesos (IPC), por lo tanto lleva asociado una interfaz para
el usario y su implementacin por parte del kernel del S.O. Se utiliza principalmente en las comunicaciones a traves de una red
como internet en arquitecturas cliente/servidor. El socket abstrae las comunicaciones proporcionando al usuario una interfaz. La
interfaz del socket lleva asociados los siguintes recursos: network socket, API socket, address socket.
Las aplicaciones utilizan sockets por lo tanto es necesario aprender a programar con sockets
La implementacin de sockets se realiza con sistemas de ficheros: SOCKFS (Socket File System).: como los sockets no son
ficheros, se habla de falsos (fake) ficheros, falsos sistemas de ficheros.

Kernel
19 / 94

12.5.3.

Mtodo de estudio

Comprender los conceptos


Practicar con la lnea de comandos
Comprender de forma simple la programacin de un socket
12.5.4.

Domain-Type-Protocol

http://techpubs.sgi.com/library/dynaweb_docs/0530/SGI_Developer/books/IRIX_NetPG/sgi_html/ch04.html
A socket is an endpoint of communication to which a name can be bound. Each socket has one or more associated processes
Para generar un socket es necesario tener en cuenta el tipo de comunicaciones al que queremos acceder. Inicialmente la
forma de definir el tipo de comunicaciones era a partir de 3 argumentos: dominio-tipo-protocolo. Al mismo tiempo que se
desarrollaban los sockets tambin se estaban desarrollando las comunicaciones. Hoy en da no hay una flexibilidad al 100 %
para poder seleccionar el tipo de protocolo, el tipo de socket y el dominio de las comunicaciones de forma independiente sino
que al seleccionar el dominio tenemos limitados los protocolos, etc
A socket domain is an abstraction that provides an addressing structure and a set of protocols, por lo tanto define la
arquitectura de las comunicaciones. Sockets connect only with sockets in the same domain
The sockets facility supports three communication domains: unix-internet-raw
The UNIX domain is used only for on-system communication: sockets are named with UNIX pathnames; a socket, for
example, may be named /dev/foo.
The Internet domain is used by processes that communicate using the Internet standard communication protocols IP/TCP/UDP.
The Raw domain provides access to the link-level protocols of network interfaces (unique to IRIX).
Each interfaz socket in use has a type . Socket types define the communication properties visible to the application (INTERFAZ ARGUMENTS). Processes communicate only between sockets of the same type
stream socket interfaz: provide a bidirectional, reliable, sequenced, and unduplicated flow of message data.
datagram socket : support bidirectional data flow, but dont guarantee that the message data is sequenced, reliable, or
unduplicated.
raw socket interfaz :give you access to the underlying communication protocols that support socket abstractions.
Cada socket tiene asociado un protocolo
Ver Capa de transporte de ISO network.
Un socket es una plataforma que lleva asociados los siguintes recursos:
network socket: endpoint of an inter-process communication flow across a computer network. Define los eventos y su organizacin para permitir que la comunicacin tenga lugar: protocolos de comunicaciones.
socket API: BSD socket. Son llamadas al kernel (system call)
socket()
creates an endpoint for communication and returns a file descriptor for the socket.
socket() takes three arguments: domain, type, protocol
bind()
listen()
close()
socket address is the combination of an IP address and a port number

Kernel
20 / 94

12.5.5.

Diferencia entre socket y fichero

Los sockets y los ficheros comparten el nmero del descriptor de fichero.


Adems de la principal diferencia en cuanto a que el fichero es un IPC asncrono y el socket es un IPC que se utiliza en tiempo
real, There are others some differences, however, between sockets and opened files. The following list highlights some of these
differences:
You cannot lseek(2) on a socket (this restriction also applies to pipes).
Sockets can have addresses associated with them. Files and pipes do not have network addresses.
Sockets have different option capabilities that can be queried and set using ioctl(2).
Sockets must be in the correct state to perform input or output. Conversely, opened disk files can be read from or written to at
any time.
12.5.6.

Diferencia entre socket y port

A socket address is the combination of an IP address and a port number


12.5.7.

Linux Command

LINUX Network Administrators Guide


http://www.faqs.org/docs/linux_network/index.html: http://www.faqs.org/docs/linux_network/x-087-2-iface.netstat.html
netstat
supports a set of options to display active or passive sockets. The options -t, -u, -w, and -x show active TCP, UDP, RAW, and
Unix socket connections. If you provide the -a flagin addition, sockets that are waiting for a connection (i.e., listening) are
displayed as well. This display will give you a list of all servers that are currently running on your system.
TCP sockets
netstat -t
Active Internet connections (w/o servers)
Proto Recv-Q Send-Q Local Address
tcp
0 25612 lur.local:47336
tcp
0
0 lur.local:52831
tcp
0
1 lur.local:53133
tcp
0
0 lur.local:35327
tcp
0
0 lur.local:47604
tcp
1
0 lur.local:43541
tcp
0
0 lur.local:50652
tcp
0
0 lur.local:36267
tcp
0
0 lur.local:46749
tcp
0
0 lur.local:50652
tcp
0
0 lur.local:36267

Foreign Address
77.69.18.95.dynam:37945
84.77.96.85:6686
222.83-213-87.dyna:4662
grape.canonical.c:https
peerbooter.peerate:7111
mistletoe.canonica:http
90.165.121.7:47470
host56-68-dynamic.:4662
16.Red-83-55-189.:55085
90.165.121.7:47470
host56-68-dynamic.:4662

State
ESTABLISHED
ESTABLISHED
FIN_WAIT1
ESTABLISHED
ESTABLISHED
CLOSE_WAIT
ESTABLISHED
ESTABLISHED
ESTABLISHED
ESTABLISHED
ESTABLISHED

unix sockets
netstat -x
unix 3
unix 3
Hx1mck4n
unix 3
unix 3
khJk3eHX
unix 3
unix 3
y8275KZu

[ ]
[ ]

STREAM
STREAM

CONNECTED
CONNECTED

777062
777395

@/dbus-vfs-daemon/socket- -

[ ]
[ ]

STREAM
STREAM

CONNECTED
CONNECTED

778262
777394

@/dbus-vfs-daemon/socket- -

[ ]
[ ]

STREAM
STREAM

CONNECTED
CONNECTED

778261
777393

@/dbus-vfs-daemon/socket- -

Kernel
21 / 94

unix 3
unix 3
tBhvWrSI
unix 3
unix 3

12.5.8.

[ ]
[ ]

STREAM
STREAM

CONNECTED
CONNECTED

777048
777392

@/dbus-vfs-daemon/socket- -

[ ]
[ ]

STREAM
STREAM

CONNECTED
CONNECTED

777047
777391

@/tmp/dbus-4AKNj7Vwtg

Programming sockets

http://linuxeco.com/?p=1: leerlo despus de conocer los conceptos. Comenta de forma bsica las funciones y procedimientos
para programar con sockets.
All Linux networking works with System Calls creating network sockets (using the Socket
System Call). The Socket System Call returns an integer (socket descriptor).
Writing or reading to/from that socket descriptor (as though it were a file) using
generic System Calls write / read respectively creates TCP network traffic rather
than file-system writes/reads.

Note: The file-system descriptor would have been created by the Open system call IF ... the descriptor were a regular file-system descriptor, intended for regular / file- system writes and reads (via System Calls write/read respectively) to files etc.
Further Note: This implies that the network socket descriptor created by the socket System Call will be used by systems programmer to write/read , using the same System Calls write/read used for regular file system writes/reads (System Calls that would, under normal and other circumstances, write/read data to/from memory).
Further further Note: A System Call write (to the descriptor that was created by the socket System Call) must translate magically into a TCP transaction that writes the data across the network (ostensibly to the client on the other end), with the data written encapsulated within the payload section of a TCP packet.
This process of adapting and hijacking the kernel file-system infrastructure to incorporate network operations /socket operations is called SOCKFS (Socket File System ).
So how does the linux kernel accomplish this process, where a file-system write is faked into a network-system write, if indeed it can be called that ?
Well...as is usually the case, the linux kernels methods begins at System / Kernel Initialization, when a special socket file-system (statically defined sock_fs_type)
for networks is registered by register_file_system. This happens in sock_init. File systems are registered so that disk partitions can be mounted for that file system.
The kernel registered file system type sock_fs_type so that it could create a fake mount point using kern_mount (for the file system sock_fs_type). This mount point is necessary if the kernel is to later create a fake file
*struct file using
existing/generic mechanisms and infrastructure made available for the Virtual File System (VFS). These mechanisms and infrastructure would include a mount point being available.
Note:

No actual mount point exists, not in the sense an inode etc etc.
We will blog on file systems later.

Then when the socket System Call is initiated (to create the socket descriptor), the kernel executes sock_create to create a new descriptor (aka the socket descriptor). The kernel also executes sock_map_fd, which creates a
fake file , and assigns the fake file to the socket descriptor. The fake files ops ( file->f_op) are then initialized to be socket_file_ops (statically defined at compile time in source/net/ socket.c).

Kernel
22 / 94

The kernel assigns/maps the socket descriptor created earlier to the new fake
using fd_install.

file

This socket descriptor is returned by the Socket System Call (as required by the MAN page
of the Socket System Call) to the user program.

I only call it fake file because a System Call write executed against that socket descriptor will use the VFS infrastructure created, but the data will not be written into a disk-file anywhere. It will, instead, be translated into a network operation because of the f_ops assigned to the fake file (socket_file_ops).
The kernel is now set up to create network traffic when System Calls write/read are executed to/from to the fake file descriptor (the socket descriptor) which was returned to the user when System Call socket was executed.
In point of fact, a System Call write to the fake files socket descriptor will then translate into a call to __sock_sendmsg within the kernel, instead of a write into the regular file system. Because that is how socket_file_ops is statically defined before assignment to the fake file.
And then we are into networking space. And the promised Lan of milk, honey,
SOCKFS and File Systems.

TCP traffic,

No one said understanding the kernel was easy. But extremely gratification awaits those that work on it. And also creates enormous opportunities for innovation. I explain Linux Kernel concepts and more in my classes ( Advanced Linux Kernel Programming @UCSC -Extension, and also in other classes that I teach independently).

12.6.

Interfaz System Calls

12.7.

Interfaz ioctl

12.8.

Interfaz signal

12.9.

Interfaz upcall

12.10.

Interfaz mmap

12.11.
.

Interfaz sysctl

Kernel
23 / 94

13.

Virtual File System (Virtual File Switch en Linux-VFS)

13.1.

Referencias

13.2.

Introduction

13.2.1.

Metodo de Aprendizaje

El gestor de ficheros del kernel de linux se puede estudiar desde distintos puntos de vista ya que est estructurado en capas. El
mtodo ms recomendable es el TOP DOWN, estudiando primero aplicaciones o herramientas de uso del sistema de ficheros
por parte del usuario y finalizando con los aspectos internos del diseo y desarrollo del kernel en lenguaje C. Este estudio vertical
no puede ser lineal y no tiene sentido estudiar primero el TOP sin saber nada del nivel DOWN.
Se recomienda estudira primero lo bsico del TOP, luego lo bsico del DOWN, profundizar en el TOP teniendo en cuenta lo
aprendido en el DOWN, profundizar en el DOWM, y as ir realimentando los dos niveles.
Un posible orden sera:
Nivel intermedio:
comprender que es un sistema de ficheros: discos, tipos, sistemas intefaz con el kernel como /sys, virtuales
crear un sistema de ficheros , enlazarlo con el /dev/loop y montarlo en un punto del file system root
Nivel intermedio: comprender la estructura de capas del sistema VFS
Nivel bajo:
comprender un poco que es un fichero, un inode, un superblock
comprobar la utilidad de la herramienta debugfs, stat, ls -i, etc
instalar el paquete gratuito de file system forensics http://www.sleuthkit.org/
comprobar los nuevos comandos herramienta: istat, etc
Nivel top :
No es fundamental conocer la IMPLEMENTACION del sistema de ficheros estructurado sino el para que. No el HOW sino
el WHAT
estudiar la evolucin del sistema de ficheros ext:
CARACTERISTICAS, OBJETIVOS Y LIMITACIONES.
coger un libro con generalidades sobre sistemas de archivos y en concreto sobre el sistema ext4 de linux.
libro silbertchaz
libro love linux programming
linux admon guide
wiki sobre ext4: estudiar unicamente las lneas generales, sin detalles.
articulo:
Practicar lo aprendido con los comandos
Nivel intermedio EXT4:
profundizar en EXT4

wiki oficial
linux guide
libro silber
libro love programming

Kernel
24 / 94

proceedings linux: developers


Nivel down
herramientas de analisis
measurement
forensics
El artculo de Kevin D. Fairbanks, An analysis of Ext4 for digital forensics es demasiado avanzado pero es prctico y
centrado. Es necesario desarrollar un script para automatizar el proceso de creacin de directorios, ficheros, borrar, etc
awk, bash, python, perl ?

importante
Hay que estudiar pensando que el sistema de ficheros actual EXT4 evoluciona y probablemente sea sustituido por uno
nuevo. Por lo que son muy importante las caractersticas de los sistemas de archivos, los objetivos que persiguen y
sus limitaciones.

13.2.2.

Fichero

Puntos de Vista de la organizacin de datos


Records(nivel aplicacin, datos segn su significado o funcin) stream de bytes (nivel sistema operativo: FILE)
bloques distribuidos (nivel hardware, disco duro)
Fichero
es la estructura lgica de los datos manejados por el sistema operativo
es una estructura de datos masivos que en Linux es un stream de bytes.
Cualquier stream de datos
Desde el punto de vista lgico es una secuencia de bytes ordenada: un stream de bytes o una cadena de bytes
Desde el punto de vista lgico se implementa como un inode: estructura de datos que describe al fichero y que apunta a los
datos del fichero (string de bytes)
Desde el punto de vista fsico:
Los datos se almacenan en un medio persistente como los HDD,CD,DVD,USB,SD, etc
Los datos se agrupan en bloques. Un bloque puede ser un sector del disco duro.
Otro tipo de organizacin seran los records, en lugar de bytes.
13.2.3.

Tipos de ficheros

Regular
Directorio
especiales
device
block
character
FIFO: pipe
symlink
socket

Kernel
25 / 94

13.2.4.

Bloque

La organizacin de los datos del disco duro en bloques significa que nos transfieren bytes sino conjuntos de bytes denominados
bloques. Se utiliza el ancho de banda del bus SCSI para transferir por ejemplo un bloque de 512 bytes con la consiguiente
optimizacin del ancho de banda efectivo.
Los dispositivos orientados a caracter transmiten byte a byte.
13.2.5.

Gestor de Ficheros del Kernel

Virtual File System Manager


Objetivo del gestor de sistemas de ficheros Virtual
Organizar los datos de las unidades de almacenamiento permanente masivo como los HDD,CD,DVD,USB,etc
Gestionar distintos sistema de ficheros lgicos como ext4 (linux), ntfs (windows), etc
Los sistemas de ficheros lgicos reales organizan y estructura ficheros lgicos que se implementan fsicamente en unidades
de almacenanmiento masivo como discos duros, compact disc, flash memory, etc
En el SO Linux el Sistema de Ficheros Virtual se denomina Virtual File_system Switch (VFS)
Switch porque filtra o conmuta entre los distintos FS lgicos (ext4, ntfs, fat, etc)
Un sistema de ficheros es una estructura de datos basada en ficheros
estructurada a distintos niveles: lgicos (multinivel) y fsico.
El gestor FS es uno de los Subsistema del kernel de linux: interacciona con otros subistemas como gestor de memoria, gestor
de procesos, etc
Es el gestor de los distintos sistemas de ficheros: estructura de datos cuya unidad lgica es el fichero
El nivel superior (root level) de la estructura del sistema de ficheros es VIRTUAL ya que su implementacin no es real en un
disco duro, sino que son funciones y estructuras de datos que abstraen operaciones e informacin relativa al almacenamiento
masivo de informacin.
La implementacin de los las operaciones y datos es en RAM en el espacio de kernel. Las estructuras de datos del nivel
superior se denominan objetos del sistema de ficheros.
Es un programa de gestin con su estructura de datos tipo ficheros.

13.3.

Diversidad de Sistemas de Ficheros

13.3.1.

Linux

Ao 2013: EXT4
13.3.2.

Windows

Ao 2013: NTFS
13.3.3.

Solaris

Ao 2013: UFS

Kernel
26 / 94

13.3.4.

BSD

Ao 2013:
13.3.5.

IBM

Ao 2013: JFS
13.3.6.

btrfs

.
13.3.7.

Comparativa: Ext, NTFS, etc

filesystem overview
Cuadro 2: Comparativa
File System
MINIX
Extfs
Ext2
Ext3
Ext4
UFS
FFS
FAT
NTFS

13.4.

kernel
si
no
si
no
Linux
2.6.28
no
nn
j
j

Bytes
2
2
4
4
8
8
si

Lineas Futuras

http://lwn.net/Articles/548089/
cambios para el kernel 3.9

13.5.

EXT: Linux File System Evolution

13.5.1.

Referencias Basicas

wikipedia
developer ext3 stat art
Mingming Cao, Theodore Y. Tso, Badari Pulavarty, Suparna Bhattacharya, Avantika Mathur
13.5.2.

Introduction

Unix File System (ufs) ext ext2 ext3 ext4

Kernel
27 / 94

UFS
Unix File System
Berkeley File system : Fast File System FFS
Hoy en da es el sistema de Solaris
Metadata Structure
Minix utiliza una versin simplificada de ufs
BootBlock - SuperBlock - InodeBitMap - ZoneBitMap - InodeTable - Data
13.5.3.

EXT

EXT
http://www.ibm.com/developerworks/linux/library/l-anatomy-ext4/
Remy Card, April 1992
Linux kernel 0.96c
2GB
VFS
13.5.4.

EXT2

EXT2
http://e2fsprogs.sourceforge.net/ext2intro.html
Remy Card, Enero 1993
Standard:
extended supported file systems of 4TB in size evoluciona hasta 32TB
Layout: BootSector-BlockGroup1-BlockGroup2 Each block group contains a redundant copy of crucial filesystem control informations (superblock and the filesystem
descriptors) and also contains a part of the filesystem (a block bitmap, an inode bitmap, a piece of the inode table, and
data blocks)
BlockGroup Layout: SuperBlock- FSDespcriptors- BlockBitMap - InodeBitMap - InodeTable - DataBlocks
13.5.5.

EXT3

EXT3
Stephen Tweedie, noviembre 2001
Maintainer: Theodore Tso
journaling
13.5.6.

EXT4

EXT4
http://www.ibm.com/developerworks/linux/library/l-anatomy-ext4/
1 ExaByte
Theodore Tso, Diciembre 2008
Kernel 2.6.28

Kernel
28 / 94

Copia el concepto extent del sistema JFS de IBM: the extent approach to block management
improvements in timestamps: en resolucin pasando de segundos a nanosegundos y en rango hasta 500 aos.
escalabilidad:
file system volumes, file sizes, and subdirectory limits
Extents: agrupa bloques de forma contigua permitiendo referencias extents en lugar de bloques individuales
perfomance
file level preallocation
delay allocation
multiblock allocation
reliability
checksum
online degramentation

13.6.

EXT: Caractersticas Generales

developer ext3 stat art

13.7.

EXT4: Introduction

La estructura del sistema de ficheros se organiza entre el nivel fsico y los niveles abstractos a distintos niveles.
El nivel VFS se estructura de forma muy parecida al Sistema de Ficheros especfico Extendido EXT4, por lo que estudir EXT4
significa estudiar VFS.
Para comprender la informacin que manipula el VFS o EXT4 podemos hacerlo va las estructuras de datos en C donde se explica
el significado de cada campo o va algn libro que describa est misma informacin sin detallar que es parte de una estructrura
de datos en C. Por lo que interesa tener un libro, tener las estructuras de VFS y tener la referencia de EXT4.
El mejor mtodo de aprendizaje es estudiar la evolucin de los sistema de ficheros en linux.
ufs ext ext2 ext3 ext4
13.7.1.

Referencias

13.8.

EXT4: Caractersticas Principales: High Level

13.9.

EXT4: Caractersticas Principales: Low Level

13.9.1.

Layout Disk

Tanenbaum
MBR-Partition Table-Partition1-Partition2-. . . -PartitionN
13.9.2.

Layout Partition

Tanenbaum
Boot_Block - Superblock - Free_space_manager - I_nodes -

Kernel
29 / 94

13.9.3.

Layout File System

13.9.4.

Layout SuperBlock

13.9.5.

Layout Inode

13.9.6.

Directory Indexing

Distintas estructuras de datos (algoritmos de bsqueda etc) se han utilizado para organizar el rbol jerrquico de directorios
del FS.
list linking : ext2,ext3
Htree
ext3, ext4
Hash Tree
ms fcil de implementar que Btree
phillips
State of the Art: Where we are with the Ext3 filesystem
forensics fairbanks

13.10.

Architecture (Capas, Multinivel)

http://docs.huihoo.com/linux/kernel/a1/#Toc_3_3
Figure 3.3: Virtual File System in Context

Kernel
30 / 94

13.10.1.

Introduction

Al igual que otros subsistema del kernel el gestor de archivos del Sistema Operativo abstrae todo lo fsico para facilitar la tarea
del administrador de sistemas. La abstraccin es jerrquica por niveles, siendo las capas superiores las ms abstractas y ms
prximas a las tareas del administrador.
The virtual file system is designed to present a consistent view of data as stored on hardware devices. Almost all hardware devices
in a computer are represented using a generic device driver interface. The virtual file system goes further, and allows the system
administrator to mount any of a set of logical file systems on any physical device. Logical file systems promote compatibility
with other operating system standards, and permit developers to implement file systems with different policies. The virtual file
system abstracts the details of both physical device and logical file system, and allows user processes to access files using a
common interface, without necessarily knowing what physical or logical system the file resides on.
In addition to traditional file-system goals, the virtual file system is also responsible for loading new executable programs. This
responsibility is accomplished by the logical file system module, and this allows Linux to support several executable formats.
13.10.2.

Estructura top-down del subsistema VFS del kernel.

Capas:
system call (open,close,etc ) virtual file system (VFS) logical file systems (ext4,ext3,vfat,etc) device driver (kernel
module) physical device(hdd, cd, usb, etc)

Kernel
31 / 94

System Call system independent interface (VFS: vnode, etc) logical FS Device Independent interfaz (operaciones
con bloques o character) Device Driver (comandos de la controladora) HW (controladora, puerto, periferico)
System Call
Es la interfaz del administrador para pedir al kernel la realizacin de una tarea de gestin de ficheros. Ejemplo: escribir en
un fichero, crear un fichero, eliminar un fichero, etc
Capa VFS: Virtual File Switch
es level root de la estructura lgica del sistema de ficheros. El level superior.
Implementa un modelo comn de gestin de ficheros independientemente del Sistema de Ficheros Lgico encargado de
gestior el disco duro.
Conmuta entre los distintos tipos especficos de ficheros: ext4, ntfs, fat, etc
Logical File System
Es el sistema de ficheros especfico con el que ha sido formateado el disco duro. Depende del sistema operativo.
Se encarga de organizar y acceder a los ficheros mediante una interfaz. Convierte operaciones de fichero en operaciones de
bloque.
Ejemplos: Ext4 en Linux, NTFS en Windows
Device Independent Interfaz
Operaciones a nivel de dispositivo independientemente del tipo especfico de dispositivo usb,hdd,CD, etc
Es el Device File de tipo bloque o carcter: sobre estos dispositivos se realizan operaciones de tipo bloque o carcter, por
eso es un fichero especial diferente de los ficheros regulares.
Device Driver
Traslada las operaciones de bloque a comandos de la controlador i/o especfica del driver de la unidad de almacenamiento
masivo
Ejemplo: write() sys_write() logical fs write METHOD device
write() es la llamada al sistema realizada por el usuario
sys_write() analiza el descriptor de fichero para saber a que tipo sistema lgico de ficheros hace referencia y por lo tanto
selecciona la funcin de escritura.
se ejecuta la funcin o mtodo de escritura especifica del FS llamando al device driver.
13.10.3.

Kernel Modules (Device Driver)

There is one device driver module for each supported hardware controller. Since there are a large number of incompatible
hardware devices, there are a large number of device drivers. The most common extension of a Linux system is the addition of a
new device driver.
The Device Independent Interface module (API de bloques y caracteres) provides a consistent view of all devices. Ver DRIVERS
(Device File)
There is one logical file system module for each supported file system.
The system independent interface (VFS) presents a hardware and logical-file-system independent view of the hardware resources.
This module presents all resources using either a block-oriented or character-oriented device file interface.
Finally, the system call interface provides controlled access to the file system for user processes. The virtual file system exports
only specific functionality to user processes.

Kernel
32 / 94

13.10.4.

Data Representation

All files are represented using i-nodes. Each i-node structure contains location information for specifying where on the physical
device the file blocks are. In addition, the i-node stores pointers to routines in the logical file system module and device driver
that will perform required read and write operations. By storing function pointers in this fashion, logical file systems and device
drivers can register themselves with the kernel without having the kernel depend on any specific module.
13.10.5.

Data Flow, Control Flow, and Dependencies

One specific device driver is por ejemplo a ramdisk; this device allocates an area of main memory and treats it as a persistentstorage device. This device driver uses the memory manager to accomplish its tasks, and thus there is a dependency, control flow,
and data flow between the file system device drivers and the memory manager.
One of the specific logical file systems that is supported is the network file system NFS (as a client only). This file system accesses
files on another machine as if they were part of the local machine. To accomplish this, one of the logical file system modules
uses the network subsystem to complete its tasks. This introduces a dependency, control flow, and data flow between the two
subsystems.
As mentioned in memory section, the memory manager uses the virtual file system to accomplish memory swapping and memorymapped I/O. Also, the virtual file system uses the process scheduler to disable processes while waiting for hardware requests to
complete, and resume them once the request has been completed. Finally, the system call interface allows user processes to call
in to the virtual file system to store or retrieve data. Unlike the previous subsystems, there is no mechanism for users to register
for implicit invocation, so there is no control flow from the virtual file system towards user processes (resuming processes is not
considered control flow).

13.11.

File Systems Objects (abstracciones)

Los objetos de los sistemas de ficheros son distintas estructuras de datos que almacenan informacin abstracta de la estructura
y organizacin del sistema de ficheros. Cada tipo de objeto o estructura de datos se implementa como un rea de memoria en el
espacio de kernel de la memoria RAM.
Objects
file object
directory object
directory entry object
inodes object
superblock object
caches
page cache:
 conceptos hw cache (cache de la DRAM), memory cache (allocation memory slab), disk cache (cache en DRAM del
HDD)
 Con Page Cache nos referimos a Disk Cache.
 Page es un agrupamiento de bloques.
 copia temporalmente en DRAM las peticiones (R/W) entre el sistema de ficheros y la unidad fsica HDD.
 Si los datos ms probables de leer o escribir estn en RAM, el acceso es ms rpido que acceder al disco duro.
 Un algoritmo para decidir que info guardo temporalmente es la LRU (Least Recent Used), el usado recientemente.
 En la Page cache hay pginas de datos y pginas de control de distintos ficheros
 A las pginas de control se les llama buffer cache.
 sincronizar el buffer cache es hacer un flush del buffer copiando su contenido en el disco duro y posteriormente vaciar
el buffer.
inode cache:
dentry cache:

Kernel
33 / 94

 cache the most-recently used directory.


Flujo de operaciones top down.
process file descriptor global setting dentry inode Device

13.12.

File Descriptor

Los ficheros son abiertos y utilizados por los procesos.


A cada fichero abierto se le asocia un nmero: el file descriptor.
El nmero asignado apunta a otro objeto : el inode (una estructura de datos que describe las propiedades del fichero)

13.13.

File Object

VFS file represents an open file (keeps state for the open file such as the write offset, and so on).

13.14.

Directory Object

Los ficheros se agrupan en directorios o carpetas


Un directorio es un fichero que contiene informacin de los nombres de los ficheros y su inode asociado.

13.15.

Path

El anidamiento de directorios o carpetas da lugar a las rutas cuyos componentes son los dentry

13.16.

dentry

A dentry (short for "directory entry") is what the Linux kernel uses to keep track of the hierarchy of files in directories. Each
dentry maps an inode number to a file name and a parent directory.
translate between file names and file inodes. The dentry also maintains relationships between directories and files for traversing
file systems

13.17.

Node

Se separan el concepto de datos del fichero y el de informacin descriptiva del fichero.


File system node: es la estructura lgica de datos que describe al fichero y que apunta a los bloques donde estn fisicamente
los datos.
Se le llam inode: index-node.
El inode es un fichero pero no de datos sino de metadatos.
Todos los ficheros son un inode
Un Device File (/dev/sda3) tambin es un inode y a este inode se le puede llamar Device Node.

Kernel
34 / 94

13.18.

Superblock

Toda la informacin (files, directory, inodes, dentry) es controlada por la informacin del superbloque, que es un metadato del
todo el sistema de ficheros. Por ejemplo, cuantos directorios hay, cuantos bloques libres, etc
Es un objeto de la capa superior VFS.
man dumpe2fs

13.19.

Tipos de FS

Referencia
/usr/src/linux-3.4.4/Documentation/filesystems/
man fs
listado de sistemas de ficheros soportados o registrados: gedit /proc/filesystems
nodev
nodev
nodev
nodev
nodev
nodev
nodev
nodev
nodev
nodev
nodev
nodev
nodev
nodev

nodev
nodev
nodev
nodev
nodev
nodev
nodev
nodev

sysfs
rootfs
bdev
proc
cgroup
cpuset
tmpfs
devtmpfs
debugfs
securityfs
sockfs
pipefs
anon_inodefs
devpts
ext3
ext4
ramfs
hugetlbfs
ecryptfs
fuseblk
fuse
fusectl
pstore
mqueue
btrfs
binfmt_misc
vfat

Logical FS soportados
ext3
ext4
fuseblk
btrfs
vfat
nodev:
son pseudosistemas ya que no hay un dispositivo fsico asociado a l, son virtuales.
se pueden implementar en RAM
procfs: el kernel genera este sistema de ficheros como interfaz user-kernel con info sobre procesos

Kernel
35 / 94

sysfs : el kernel genera este sistema de ficheros como interfaz user-kernel con info sobre procesos
debugfs
configfs
etc

13.20.

Root File System level: VFS

VFS layer
The VFS keeps track of:
the currently-supported file systems
cat /proc/filesystems

13.21.

Root File System

Es el Primer Sistema de Ficheros que se genera : Se genera durante el arranque.


Su estructura es en ARBOL. Unicamente hay UN rbol cuya raz es el ROOT
Sobre este rbol jerrquico se integran (montan) el resto de sistema de ficheros (otras particiones, el usb, el CD, etc).
Por lo tanto tenemos un sistema de ficheros root de donde cuelgan el resto de sistema de ficheros
Ver jerarqua del sistema de ficheros
http://wiki.debian.org/ReadonlyRoot
http://www.tldp.org/LDP/sag/html/root-fs.html
The root filesystem is the filesystem that is contained on the same partition on which the root directory is located, and it is
the filesystem on which all the other filesystems are mounted (i.e., logically attached to the system) as the system is booted
up (i.e., started up).
Los otros sistemas de ficheros pueden estar en otras particiones.
The contents will include the root directory together with a minimal set of subdirectories and files including /boot, /dev,
/etc, /bin, /sbin and sometimes /tmp (for temporary files)
NO ESTA el directorio /home ni el /usr ni /proc ni /var. Es decir, son los ficheros necesarios para que arranque el sistema
de una forma estable: it contains very critical files and a small
S est /dev
The FHS allows mounting all underneath /bin, /lib, /sbin and /usr read-only. But you can extend this much more by using
different filesystems for some trees and take care for special files.
Locations that must be writable are /etc, /home, /srv, /tmp, /var. The hierarchies below /dev, /proc, /selinux and /sys are
already handled by special filesystems.
For /tmp you can use a tmpfs filesystem or its own filesystem. For /var its prefered to use its own filesystem. An example
can look like this:
Device file

Filesystem

/dev/sda1
ext2
/dev/sda2
ext3
-tmpfs
/var/local/home bind mount
/var/local/srv bind mount

Mount point
/
/var
/tmp
/home
/srv

RO/RW
RO
RW
RW
RW
RW

Kernel
36 / 94

13.21.1.

mount

mount : file systems that are currently mounted.


cat /proc/self/mounts
El sistema de ficheros linux esta organizado jerrquicamente en una UNICA estructura en rbol cuyo nodo superiror es el root
/.
Todos los sistemas de ficheros de las distintas unidades de almacenamiento deben de estar enlazadas o integradas lo MONTADAS en dicho rbol.
Unicamente se pueden montar los sistemas de ficheros que esten previamente registrados por el kernel
El registro puede estar compilado en el kernel o en un mdulo cargable en el kernel.
el comando mount recurre a las API:
File systems can be dynamically added or removed from Linux using a set of registration functions. The kernel keeps a list
of currently-supported file systems, which can be viewed from user space through the /proc file system. This virtual file also
shows the devices currently associated with the file systems. To add a new file system to Linux, register_filesystem
is called. This takes a single argument defining the reference to a file system structure (file_system_type), which defines the
name of the file system, a set of attributes, and two superblock functions. A file system can also be unregistered.
13.21.2.

CHROOT

como crear un entorno chroot

13.22.

Devices

Las capas inferiores de la gestin de ficheros gestionan los dispositivos.


Linux abstrae cualquier dispositivo como un fichero especial denominado Device File
El fichero Device File es la interfaz al hardware.
13.22.1.

Device File

Son los file system nodes interfaces con los dispositivos y que estn montados en /dev/
Es la interfaz entre el sistema de ficheros y el driver del dispositivo.
Es un fichero especial o sistema de ficheros, de tipo bloque o carcter que interfiere con el driver del dispositivo. Tiene que
traducir estructuras de tipo fichero a estructuras de tipo bloque o carcter. Ver apuntes de drivers, major-minor number, etc ..
Tipos de Device Files
Unidades de almacenamiento tipo bloque

/dev/sda
/dev/sdb
/dev/fd
/dev/sr

Especiales
/dev/null
/dev/zero
/dev/loop

Kernel
37 / 94

13.22.2.

/dev/loop

Es un dispositivo de tipo bloque virtual ya que el file node no est asociado directamente a una unidad de almacenamiento
externa como un usb, etc.
En lugar de estar asociado a una unidad fsica, se asocia a un fichero regular. Es decir, /dev/loop es la interfaz a un fichero que
emula a un dispositivo.
Como el fichero regular asociado al Device File /dev/loop est almacenado en la misma particin, se habla de loop back.
Si el device file /dev/loop est almacenado en una particin del disco duro ST9500420AS Seagate . Todos los datos que
se dirigen a la interfaz /dev/loop no van a otro dispositivo (CD, usb, hdd, etc) sino que vuelven ( LOOP BACK) al mismo
disco duro ST9500420AS Seagate. El concepto LOOP BACK tiene una segunda interpretacin y creo que es la adecuada:
se puede ver como el flujo de datos que llega a la capa /dev/loop procedente de VFS y no baja a un dispositivo fsico sino
que retorna a un fichero, es decir, retorna a la capa VFS.
Esquema

14.

Virtual Disks

concepts &
dd, formatting, qcow, loop devices

15.

File System EXERCICE

15.1.

Referencias

15.2.

Introduction

El objetivo es entender los conceptos de un sistema de ficheros desde el punto de vista prctico, es decir, desde el punto de
vista del administrador.

Kernel
38 / 94

15.3.

losetup (loop-setup)

losetup /dev/loop0 file.img


By attaching the disk image to the loopback device, we can use /dev/loop0 the same way we would use ~/myDisk.img; the
main difference is that /dev/loop0 is a whats known as a "block device". Youd have to ask someone with more experience
than Ive got what precisely this gets you, but what I do know is that the filesystem utilities work better with block devices
than they do with the flat files

15.4.

Tutorial Basico. I.

http://web2.clarkson.edu/projects/itl/honeypot/ddtutorial.txt
Crear un sistema de ficheros virtual propio. (Un sistema de ficheros virtual sera el asociado a uno real de una nica particin)
$ dd if=/dev/zero of=~/myFileSystem.img bs=1024 count=1048576
regular myFilesystem.img y lo inicializa a ceros.
1048576+0 records in
1048576+0 records out
1073741824 bytes (1.1 GB) copied, 12.2151 s, 87.9 MB/s

-> Genera el fichero

$ mke2fs -t ext4 myFileSystem.img -> CREA EL SISTEMA DE FICHEROS


mke2fs 1.42 (29-Nov-2011)
myFileSystem.img is not a block special device. -> ya que es un fichero regular -> he
formateado de forma virtual.
Proceed anyway? (y,n) y
Discarding device blocks: done
Filesystem label=
OS type: Linux
Block size=4096 (log=2)
Fragment size=4096 (log=2)
Stride=0 blocks, Stripe width=0 blocks
65536 inodes, 262144 blocks
13107 blocks (5.00 %) reserved for the super user
First data block=0
Maximum filesystem blocks=268435456
8 block groups
32768 blocks per group, 32768 fragments per group
8192 inodes per group
Superblock backups stored on blocks:
32768, 98304, 163840, 229376
Allocating group tables: done
Writing inode tables: done
Writing superblocks and filesystem accounting information: done

$ mke2fs -L FSvirtual myFileSystem.img -> asigno el Label al sistema de ficheros


$ podra haber hecho mke2fs -t ext4 -L FSvirtual myFileSystem.img
$ file myFileSystem.img -> INFORMA DEL TIPO DE FICHERO QUE ES EL FICHERO IMAGEN -> ext4 filesystem data
myFileSystem.img: Linux rev 1.0 ext4 filesystem data, UUID=c88add4c-6801-44ba-b021-52619 c03e919, volume name "FSvirtual" (extents) (large files) (huge files)

Observo que me da informacin de objetos del gestor de ficheros de VFS del kernel: inodes, superblock, etc
man mke2fs:
create an ext2/ext3/ext4 filesystem
The defaults of the parameters for the newly created filesystem, if not overridden by the options listed below, are controlled
by the /etc/mke2fs.conf configuration file. See the mke2fs.conf(5) manual page for more details.
Dispositivos virtuales o PseudoDispositivos

Kernel
39 / 94

candido@lur:~/tutoriales/dev_loop$ ls /dev/loop* -> Dispositivos virtuales


/dev/loop0 /dev/loop1 /dev/loop2 /dev/loop3 /dev/loop4 /dev/loop5 /dev/loop6
/loop7 /dev/loop-control
candido@lur:~/tutoriales/dev_loop$ losetup -f -> primer dispositivo sin utilizar
/dev/loop0

/dev -

El sistema de ficheros est sin enlazar con un dispositivo virtual y tambin est sin montar por lo que no puedo acceder a l
para ejecutar comandos como crear ficheros, carpetas, etc
asociacion sistemafichero(myfilesystem) con dispositivo virtual /dev/loopx
$ losetup -j myFileSystem.img -> informa de cual es el dispositivo enlazado al fichero imagen -> en este caso ninguno
$ losetup myFileSystem.img
loop: cant get info on device myFileSystem.img: Inappropriate ioctl for device
$ losetup /dev/loop0 myFileSystem.img -> enlace entre el dispositivo y el sistema de ficheros
$ losetup -j myFileSystem.img -> consulta qu dispositivo est asociado al sistema de ficheros
/dev/loop0: [0803]:4596853 (/home/candido/tutoriales/dev_loop/myFileSystem.img)
$ ls -l /proc/fs/ext4 -> el kernel INFORMA de los dispositivos con sistema de ficheros tipo ext4 que estn montados
$ losetup -d /dev/loop0 -> elimina el enlace

montaje del fichero(myfilesystem) en el sistema de ficheros general.


$ ls -l /proc/fs/ext4 -> informa que sistema de ficheros tipo ext4 estn montados
total 0
dr-xr-xr-x 2 root root 0 Dec 8 12:35 sda3
$ df -m -> informa de todos los sistemas de ficheros montados
Filesystem
1M-blocks
Used Available Use % Mounted on
/dev/sda3
295296 232400
47896 83 % /
udev
1909
1
1909
1 % /dev
tmpfs
769
2
768
1 % /run
none
5
0
5
0 % /run/lock
none
1921
1
1921
1 % /run/shm
cgroup
1921
0
1921
0 % /sys/fs/cgroup
/dev/mmcblk0p2
1796
1592
113 94 % /media/rootfs
/dev/mmcblk0p1
52
7
46 12 % /media/boot
$ sudo mkdir /mnt/virtual ->punto de montaje
$ sudo mount myFileSystem.img /mnt/virtual -> montaje del fichero en el sistema de ficheros general
$ ls /proc/fs/ext4 -> sistemas montados tipo ext4
loop0 sda3 -> El sistema de ficheros del dispositivo loop0 es accesible
$ umount /mnt/virtual -> desmonto lo que este montado en este punto y como hay un montado un sistema de ficheros est tambin se disocia del dispositivo virtual /dev/ loop0 quedando loop0 nuevamente libre

Al montarse el kernel genera:


 /sys/fs/ext4/loop0
 /proc/fs/ext4/loop0
INFORMACION del sistema de ficheros del dispositivo MONTADO tipo bloque /dev/loop0
$ ls -l /sys/fs/ext4/loop0
total 0
-r--r--r-- 1 root root 4096
-rw-r--r-- 1 root root 4096
-rw-r--r-- 1 root root 4096
-r--r--r-- 1 root root 4096
-rw-r--r-- 1 root root 4096
-rw-r--r-- 1 root root 4096

Dec
Dec
Dec
Dec
Dec
Dec

8
8
8
8
8
8

12:53
12:53
12:53
12:53
12:53
12:53

delayed_allocation_blocks
inode_goal
inode_readahead_blks
lifetime_write_kbytes
max_writeback_mb_bump
mb_group_prealloc

Kernel
40 / 94

-rw-r--r--rw-r--r--rw-r--r--rw-r--r--rw-r--r--r--r--r--

1
1
1
1
1
1

root
root
root
root
root
root

root
root
root
root
root
root

4096
4096
4096
4096
4096
4096

Dec
Dec
Dec
Dec
Dec
Dec

8
8
8
8
8
8

12:53
12:53
12:53
12:53
12:53
12:53

mb_max_to_scan
mb_min_to_scan
mb_order2_req
mb_stats
mb_stream_req
session_write_kbytes

Accedo al Pseudo Dispositivo /dev/loop0


$ ls -l /mnt/virtual
total 16
drwx------ 2 root root 16384 Jul 19 19:29 lost+found
$ sudo chown -R candido:candido /mnt/virtual/ -> cambio el propietario root por candido

Ahora puedo poblar el sistema de ficheros generando, moviendo, copiando ficheros en /mnt/virtual ya que realmente lo que
estamos poblando es el fichero imagen myFileSystem, es decir, estoy poblando la imagen de mi sistema de ficheros virtual.
$ cd /mnt/virtual
$ touch prueba.txt
$ echo "hola" > prueba.txt
$ ls -l /mnt/virtual
total 20
-rw-rw-r-- 1 candido candido
11 Dec
drwx------ 2 root
root
16384 Dec

8 12:58 prueba.txt
8 12:08 lost+found

Se puede asociar y montar en una misma orden con mount. Asociacion sistemafichero(myfilesystem) con dispositivo virtual
y montaje del fichero(myfilesystem) en el sistema de ficheros general.
$ sudo mkdir /mnt/virtual ->punto de montaje
$ sudo mount -o loop myFileSystem.img /mnt/virtual ---> Con la opcin -o loop realizamos la asociacin previa la montaje

$sudo mount myFileSystem.img /mnt/virtual ---> tambin se realizar la asociacin ya que el fichero myFileSystem es un sistema de ficheros.
$ $ mount | grep myFileSystem
/home/candido/tutoriales/dev_loop/myFileSystem.img on /media/borrar type ext4 (rw) ----------> NO MUESTRA EL DISPOSITIVO /dev/loop1

15.5.

Analisis de la imagen de un sistema de ficheros virtual

leer primero el man debugfs


debugfs es una herramienta para forenses http://www.cyberciti.biz/tips/linux-ext3-ext4-deleted-files-recovery-howto.html y
poder recuperar ficheros borrados.
En el primer tutorial hemos trabajado con un dispositivo virtual /dev/loop por lo que su sistema de ficheros es virtual. No hay
un disposivo real ext4.
Por otro lado tenemos asociado al dispositivo una imagen que podremos manipular, poblar, portar, etc.
Me interesa poder acceder a la informacin de la imagen del pseudodispostivo.
Es necesario montarlo? Con la utilidad debugfs no es necesario tenerlo montado
$ debugfs myFileSystem.img -> abre el sistema de ficheros y abre la consola con el
prompt debugfs:
debugfs 1.42 (29-Nov-2011)
debugs: pwd
[pwd]
INODE:
2 PATH: /
ficheros myFileSystem

--> nmero de inode y su path relativo al sistema de -

Kernel
41 / 94

[root]

INODE:

debugfs: stat .

PATH: /
--> estadstica del inode especificado

Inode: 2
Type: directory
Mode: 0755
Flags: 0x80000
inode number 2
Generation: 0
Version: 0x00000000:00000001
User: 1000
Group: 1000
Size: 4096
File ACL: 0
Directory ACL: 0
Links: 4
Blockcount: 8
Fragment: Address: 0
Number: 0
Size: 0
ctime: 0x51e988e1:81ca1804 -- Fri Jul 19 20:43:45 2013
atime: 0x51e9958a:0c2e5614 -- Fri Jul 19 21:37:46 2013
mtime: 0x51e988e1:81ca1804 -- Fri Jul 19 20:43:45 2013
crtime: 0x51e97764:00000000 -- Fri Jul 19 19:29:08 2013
Size of extra inode fields: 28
EXTENTS:
(0):73
(END)
--> entra en una nueva consola con los atajos --> h
blocks .
1

--> bloques utilizados por el fichero .

blocks

-> el file . tiene el

-->

bloques utilizados por el inode 2

ls -l
2
2
11

40755 (2)
40755 (2)
40700 (2)
perdidos

1000
1000
1000

1000
1000
1000

4096 19-Jul-2013 19:29 .


4096 19-Jul-2013 19:29 ..
16384 19-Jul-2013 19:29 lost+found

--> objetos

(END)
-------------------> en esta nueva consola teclear h para info de los atajos, q para
salir
ls -l lost+found
q

-------> quit

stat

v ---> info del inode 11

imap .
Inode 2 is part of block group 0
located at block 97, offset 0x0100

icheck 97
--> buscar el inode relacionado con un bloque determinado
Block
Inode number
97
<block not found>

stats

---> estadsticas del superbloque


----> abre una nueva consola con el nuevo prompt :
----> h -> help de la nueva consola
----> q

params
features

opciones de debugs

Kernel
42 / 94

debugfs -R stats myFileSisytem.img


debugfs -w myFileSystem.img

15.6.

--> ejecuta el comando stats de debugs


--> abre el sistema de ficheros en modo escritura

FS contenedor del fichero imagen y FS contenido en el fichero imagen

df : informa del sistema de ficheros contenedor del fichero que se argumenta


$ df -h /mnt/virtual/
Filesystem
Size Used Avail Use % Mounted on
/dev/loop0
1008M
34M 924M
4 % /mnt/virtual
$ df -h myFileSystem.img
Filesystem
Size Used Avail Use % Mounted on
/dev/sda3
289G 266G 8.4G 97 % /

15.7.

Particiones del sistema de ficheros

sudo parted
Particiones del HDD
$ sudo parted
(parted) print
Model: ATA ST9500420AS (scsi)
Disk /dev/sda: 500GB
Sector size (logical/physical): 512B/512B
Partition Table: msdos
Number
1
2
3

Start
32.3kB
105GB
110GB

End
105GB
110GB
425GB

Size
105GB
5240MB
315GB

Type
primary
primary
primary

File system
ntfs
ntfs
ext4

Flags
boot

Particiones del dispositivo /dev/loop


(parted) select /dev/loop0
Using /dev/loop0
(parted) print
Model: Loopback device (loop)
Disk /dev/loop0: 1074MB
Sector size (logical/physical): 512B/512B
Partition Table: loop
Number
1

15.8.

Start
0.00B

End
1074MB

Size
1074MB

File system
ext4

Flags

Tutorial Basico. II.

Ref: Anatomy of the linux system


copia 10000 bloques de 1k cada uno del dispositivo /dev/zero al fichero file.img
-> diezmil K son 10MB, no 10MiB
$ dd if=/dev/zero of=file.img bs=1k count=10000
10000+0 records in
10000+0 records out
10240000 bytes (10 MB) copied, 0.0355044 s, 288 MB/s

Kernel
43 / 94

se generla el fichero file.img de tipo regular


$ls -l file.img
-rw-rw-r-- 1 candido candido 10240000 Jul 19 18:22 file.img
utilizamos un pseudo dispositivo de tipo bloque cuyo file device es /dev/loop0
candido@lur:~$ ls -l /dev/loop0
brw-rw---- 1 root disk 7, 0 Jul 19 18:25 /dev/loop0
asocio, attach, al dispositivo loop0 el fichero file.img
$ losetup /dev/loop0 file.img
$ losetup /dev/loop0 file.img -> si repito el comando me dir que ya est ocupado
losetup: /dev/loop0: device is busy
$ losetup -j file.img -> busca el loopdevice asociado
/dev/loop0: [0803]:4597512 (/home/candido/file.img)
$ losetup -a -> info de all loopdevice
/dev/loop0: [0803]:4597512 (/home/candido/file.img)
$ losetup -f -> find first free loopdevice
/dev/loop1
$ losetup -d /dev/loop0 -> detach loopdevice : elimina la asociacin

15.9.

tutorial basico III: NTFS virtual disk

importante
http://lnx.cx/docs/vdg/output/Virtual-Disk-Operations.html#VDG-Concepts-Creation

dd if=/dev/zero of=candido.img bs=1M count=100 fichero de 100MB inicializado a cero


candido.img:
file candido.img : lo ve como datos
stat candido.img : lo ve como un fichero regular
File:
Size:
Device:
Access:
Access:
Modify:
Change:
Birth:

candido.img
104857600
Blocks: 204808
IO Block: 4096
regular file
803h/2051d
Inode: 5768315
Links: 1
(0664/-rw-rw-r--) Uid: ( 1000/ candido)
Gid: ( 1000/ candido)
2014-06-16 13:39:27.315674214 +0200
2014-06-16 13:39:23.095757294 +0200
2014-06-16 13:39:23.095757294 +0200
-

fdisk candido.img: no ve la tabla de particiones


Disk candido.img: 104 MB, 104857600 bytes
255 heads, 63 sectors/track, 12 cylinders, total 204800 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000

---> OJO

Disk candido.img doesnt contain a valid partition table

Necesito herramientas para manipular el disco ntfs: para generar una particin, tabla de particiones, etiqueta, etc
sudo parted candido.img mklabel msdos: Crear una tabla de particiones

Kernel
44 / 94

$ sudo parted candido.img mklabel msdos


Warning: The existing disk label on /home/candido/tutoriales/filesystem/virtualimage/ candido.img will be destroyed and all data on this disk will
be lost. Do you want to continue?
Yes/No? yes

file candido.img x86 boot sector


candido.img: x86 boot sector, code offset 0xb8

dd if=candido.img bs=512 count=1 | xxd


vuelco en hexadecimal los primeros 512 bytes, es decir, el sector 0, el sector boot.
stat candido.img
fdisk -l candido.img : ha cambiado la info de las particiones encuentra la tabla pero no hay info de la nica
particin. Hay que crearla.
Disk candido.img: 104 MB, 104857600 bytes
255 heads, 63 sectors/track, 12 cylinders, total 204800 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x000b1b59
Device Boot

Start

End

Blocks

Id

--> SE MANTIENE

System

With a loop device inserted between programs and our disk image we can view and operate on the disk image as if it were
a regular drive. When accessed through a loop device fdisk can properly determine the number of cylinders, heads, and
everything else required to create partitions.
El sistema operativo no puede realizar operaciones de bloque sobre un fichero si este no est asociado a un dispositivo de
bloque
Tenemos dos alternativas para formatear el disco:
fdisk menu
gparted gui
1 ALTERNATIVA FALLADA: Mediante fdisk menu no lo he realizado bien
* +sudo fdisk /dev/loop0+ -> m-n-p-1-primer_sector:default:2048 - last_sector:default, ->
t-1-fs_code=7 (NTFS), ->w
+sudo
partprobe /dev/loop0+
*
* +fdisk -l /dev/loop0+
* Sectores
** En total hay 204800 sectores: desde el 0 hasta el 204799
** En el primer sector (sector 0) est el MBR.
** La particin_1 comienza en el sector 2048 y finaliza en la 204799 -> 202752 sectores en
al primera particin.
** qu hay en los sectores 1-2047? Modern boot loaders (NTLDR[28], GRUB[29], etc) use this space to store additional code and data necessary to boot the system
* /dev/loop0p1 es la particin 1 del disco loop0
* 2048*512 = 1048576 bytes : offset desde el comienzo del disco hasta la primera particin
.
* +sudo losetup -o 1048576 -f /dev/loop0+ -> asocio la particin 1 de /dev/loop0 al dispositivo /dev/loop1
IMPORTANT: POR QUE?? Para formatear la primera particin y poder MONTARLA para acceder
a ella a travs del sistema de ficheros.

Kernel
45 / 94

* +sudo losetup -a+


/dev/loop0: [0803]:5768315 (/home/candido/tutoriales/filesystem/virtualimage/candido.img)
/dev/loop1: [0005]:1165 (/dev/loop0), offset 1048576
* +sudo mkfs.ntfs /dev/loop1+ -> formateo la particin 1
The partition start sector was not specified for /dev/loop1 and it could not be obtained automatically. It has been set to 0.
The number of sectors per track was not specified for /dev/loop1 and it could not be obtained automatically. It has been set to 0.
The number of heads was not specified for /dev/loop1 and it could not be obtained automatically. It has been set to 0.
Cluster size has been automatically set to 4096 bytes.
To boot from a device, Windows needs the partition start sector, the sectors per track and the number of heads to be set.
Windows will not be able to boot from this device.
Initializing device with zeroes: 100 % - Done.
Creating NTFS volume structures.
Failed to sync device /dev/loop1: Input/output error
Syncing device. FAILED
** Ojo que dice no_botable y FAILED. REPITO con opciones
* +sudo mkfs.ntfs -v -H 19 -L candido -S 50 -s 512 -p 0 /dev/loop1 202752+
** 19 cabezas, 50 sectores/track, 512 bytes/sector, primer sector= sector 0, en total
202752 sectores.
** Tengo la duda con el valor del primer sector -p 1048576
Cluster size has been automatically set to 4096 bytes.
Initializing device with zeroes: 100 % - Done.
Creating NTFS volume structures.
Creating root directory (mft record 5)
Creating $MFT (mft record 0)
Creating $MFTMirr (mft record 1)
Creating $LogFile (mft record 2)
Creating $AttrDef (mft record 4)
Creating $Bitmap (mft record 6)
Creating $Boot (mft record 7)
Creating backup boot sector.
Creating $Volume (mft record 3)
Creating $BadClus (mft record 8)
Creating $Secure (mft record 9)
Creating $UpCase (mft record 0xa)
Creating $Extend (mft record 11)
Creating system file (mft record 0xc)
Creating system file (mft record 0xd)
Creating system file (mft record 0xe)
Creating system file (mft record 0xf)
Creating $Quota (mft record 24)
Creating $ObjId (mft record 25)
Creating $Reparse (mft record 26)
Syncing root directory index record.
Syncing $Bitmap.
Syncing $MFT.
Updating $MFTMirr.
Syncing device.
Failed to sync device /dev/loop1: Input/output error
Syncing device. FAILED

CAUTION: FAILED -> me rindo


* +sudo losetup -d /dev/loop1+
* +sudo losetup -d /dev/loop0+
* +sudo mount -t ntfs-3g -o loop,offset=1048576 candido.img /mnt/mi_sistemafile/+ -> monto la particin_1

Kernel
46 / 94

* +fdisk -l /dev/loop0+ -> no es correcta la info del volcado porque deba dar info de una particin.
fdisk
-l /dev/loop0
*
Disk /dev/loop0: 104 MB, 104857600 bytes
255 heads, 63 sectors/track, 12 cylinders, total 204800 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x2052474d
This doesnt look like a partition table
Probably you selected the wrong device.
Device Boot
Start
/dev/loop0p1
?
6579571
/dev/loop0p2
? 1953251627
/dev/loop0p3
?
225735265
/dev/loop0p4
2642411520

End
1924427647
3771827541
225735274
2642463409

Blocks
958924038+
909287957+
5
25945

Id
70
43
72
0

System
DiskSecure Multi-Boot
Unknown
Unknown
Empty

Partition table entries are not in disk order

2ALTERNATIVA FUNCIONA: formatear con gparted


PARA GESTIONAR la imagen como disco virtual necesito asociar la imagen a un pseudodispostivo de BLOQUE.
Virtual Disk: losetup /dev/loop0 candido.img
sudo gparted /dev/loop0
Hago la primera particin ntfs de 50MB
Hago la segunda particin ntfs de 30MB
Dejo 25MB sin asignar
fdisk -l candido.img tabla de particiones correcta
Disk candido.img: 104 MB, 104857600 bytes
255 heads, 63 sectors/track, 12 cylinders, total 204800 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x000e673a
Device Boot
candido.img1
candido.img2

Start
2048
104448

End
104447
165887

Blocks
51200
30720

Id
7
83

System
HPFS/NTFS/exFAT
Linux

mmls candido.img
DOS Partition Table
Offset Sector: 0
Units are in 512-byte sectors

00:
01:
02:
03:
04:

Slot
Meta
----00:00
00:01
-----

Start
0000000000
0000000000
0000002048
0000104448
0000165888

End
0000000000
0000002047
0000104447
0000165887
0000204799

Length
0000000001
0000002048
0000102400
0000061440
0000038912

Description
Primary Table (#0)
Unallocated
NTFS (0x07)
Linux (0x83)
Unallocated

dd if=candido.img of=part1.dd bs=512 skip=2048 count=102400 : clono la particin primera

Kernel
47 / 94

dd if=candido.img of=part2.dd bs=512 skip=104448 count=61440 : clono la particin segunda


stat part1.dd info Blocks: 102408 por qu no salen los 102400 que he copiado? puede ser porque los bloques
son multiplos de ..
stat part2.dd info Blocks: 61440
dd if=candido.img bs=512 skip=0 count=1 | xxd volcado del sector 0
00001b0:
00001c0:
00001d0:
00001e0:
00001f0:

0000
2100
3a06
0000
0000

0000
077f
8353
0000
0000

0000
3906
090a
0000
0000

0000
0008
0098
0000
0000

3a67
0000
0100
0000
0000

0e00
0090
00f0
0000
0000

0000
0100
0000
0000
0000

0020
007f
0000
0000
55aa

........:g.....
!...9...........
:..S............
................
..............U.

Boot code address: 0x00-0x1BD


Partition Table entry #1 address: 0x1BE - 0x1CD
0020 2100 077f 3906 0008 0000 0090 0100
 el byte 4 es 07 : file system type NTFS
 bytes 8-11 : LBA starting sector address: 0008 0000 = little endian = 0x00000800 = hex a decimal = 2048
 bytes 12-15: partition size: 0090 0100 = little endian = 0x00019000 =de hex a decimal =102400
Partition Table entry #1 address: 0x1CE - 0x1DD
Partition Table entry #1 address: 0x1DE - 0x1DD
Partition Table entry #1 address: 0x1EE - 0x1FD
Magic Number address : 0x1EE - 0x1FF
55AA = little endian = 0xAA55

16.
16.1.

File System FORENSICS


Tutorial

recuperar ficheros perdidos


hal pomeranz
http://homepage.smc.edu/morgan_david/cs40/analyze-ext2.htm: prctico
http://undergraduate.csse.uwa.edu.au/units/CITS1002/fs-ext2/ext2fs_toc.html#SEC1: es ms descriptivo que prctico

16.2.

Books

file system forensic analysis, Brian Carrier: descargado, portal con herramientas
http://www.porcupine.org/forensics/forensic-discovery/: online

16.3.

Tools

The Sleuth Kit TSK: Lo referencia el libro de Brian Carrier

Kernel
48 / 94

17.

Otros Sistemas de Ficheros

17.1.

NTFS

http://www.tuxera.com/community/ntfs-3g-manual/
New Technology File System
Sistema adecuado para las particiones de gran tamao requeridas en estaciones de trabajo de alto rendimiento y servidores,
hasta 2641 clsteres.
Sistema de Windows NT
Controlador NTFS-3G
Driver de Linux que permite acceder a sistemas NTFS
NTFS-3G monta las particiones NTFS usando el mdulo de espacio de usuario FUSE
modprobe -l | grep ntfs : driver ntfs

17.2.

Fuse

fuse home
The FUSE kernel module and the FUSE library communicate via a special file descriptor which is obtained by opening
/dev/fuse
cat /proc/filesystems nodev fuse sistema de ficheros fuse
modprobe -l | grep fuse : driver fuse

17.3.

gvfs

Lo utiliza ubuntu para el driver de conexin a un smartphone gvfs-mtp


Gnome Virtual File System
facilidades con gvfs: el ms comprensible
https://en.wikipedia.org/wiki/GVFS
http://www.linuxfromscratch.org/blfs/view/svn/gnome/gvfs.html
The Gvfs package is a userspace virtual filesystem designed to work with the I/O abstractions of GLibs GIO library
https://wiki.archlinux.org/index.php/File_manager_functionality

17.4.

usb:mtp,ptp

usb
Multimedia Transfer Protocol : mtp
mtp
https://wiki.archlinux.org/index.php/MTP
Picture Transfer Protocl ptp
how to smartphone
practico con comandos en linea

Kernel
49 / 94

18.

DMA

19.

Graphics: Screen Printing (Video)

Video

20.

Networking

20.1.

Overview

20.2.

ISO Stack Layer

Ejemplo
user application: navegador firefox application level: HTTP
Transport level : TCP (fiable: sin errores y segura)
la frontera entre HTTP y TCP la establece el socket
Network Level: IP (no fiable)
Link Level: ethernet

20.3.

TCP

Capa de Abstraccin Nivel Transporte.


The essential property of TCP is that it uses IP to give you the illusion of a simple connection between the two processes on
your host and the remote machine so that you dont have to care about how and alongwhich route your data actually travels.
A TCP connection works essentially like a two-way pipe that both processes may write to and read from. Think of it as a
telephone conversation.
Port
TCP identifies the end points of such a connection by the IP addresses of the two hosts involved and the number of a port on
each host. Ports may be viewed as attachment points for network connections. An individual host may support many different
services, each distinguished by its own port number. Con la direccin IP referenciamos la tarjeta ethernet de un host y con el
port number la aplicacin o proceso (navegador http, applicacin ftp, etc)
IP code :: host
Port code :: service application
If an server application wants to offer a certain service, it attaches itself to a port and waits for clients (this is also called listening
on the port).
The same server port may be open on many different machines, but on each server machine only one process can open a port at
any one time. An important property of ports is that once a connection has been established between the client and the server,
another copy of the server (copia del proceso, del programa servicio) may attach to the server port and listen for more clients.
This property permits, for instance, several concurrent remote logins to the same host, all using the same port 513, donde cada
proceso servidor atiende a diferentes clientes a travs del mismo nmero de puerto. Si tengo en el mismo host ms de un proceso
login, cada cliente abre puertos diferentes pero todos los clientes se conectan al mismo puerto server.

Kernel
50 / 94

Socket
In Unix operatingsystems, the software performingall the tasks and protocols described above is usually part of the kernel, and
so it is in Linux. The programming interface most common in the Unix world is the Berkeley Socket Library. Its name derives
from a popular analogy that views ports as sockets and connecting to a port as plugging in. It provides the bind call to specify
a remote host, a transport protocol, and a service that a program can connect
Ver IPC-Sockets

20.4.

WIFI

http://wireless.kernel.org/en/users/Documentation: general fundamental


Ver apuntes file:////home/candido/Escritorio/estructura_de_computadores/alum_estru_compu/APUNTES/apuntes_networks/networks.html

21.
21.1.

INTEL: Interfaces Usuario-Sistema: Normativa Unix


Developer Manual

../../apuntes_intel/manual_intel.html[intel developer manual]

21.2.

API

Application Programming Interfaz


SVID: System_V_Interface_Definition
Es el API original de Unix que desarroll AT&T y que fue sustituido por POSIX despus de la "War Unix". Hay enlaces a
los manuales en wikipedia.
POSIX es un API, donde API son las interfaces en lenguajes fuente , es decir, las interfaces en cdigo fuente (normalmente C)
entre aplicaciones y el sistema operativo. Por ejemplo la funcin write(). Ver el libro Interfaces Implementation.

21.3.

ABI

Application Binary Interfaz


A diferencia de las interfaces API, la normativa de interfaz ABI son las normas entre ficheros binarios, entre mdulos objeto,
entre programas compilados y el sistema operativo. Es normas las debe de tener en cuenta un compilador, el formato del objeto
binario (ELF), un sistema operativo (kernel), etc.
Linux tiene su propio ABI, el LSB que es una extensin del ABI SYSv-X86-64
ABI relaciona un Sistema Operativo, un lenguaje de programacin y la arquitectura de un microprocesador
P.ej. UN*x/C/x86-64
ABI Fundamentals

21.4.

ISA

Instruction Set Architecture


Developer Manuales Intel

Kernel
51 / 94

22.

Compilacin kernel

22.1.

Tutoriales

22.1.1.

Excesivamente simple

http://www.linuxchix.org/content/courses/kernel_hacking/lesson0
http://www.haifux.org/lectures/88-sil/kernel-compilation.html
http://kernelnewbies.org/KernelBuild: recomendado
http://linux.yyz.us/git-howto.html#update_tree: bajar el kernel con git
22.1.2.

Completo

http://www.linux.org/threads/linux-kernel-reading-guide.5384/: detallado y actualizado


http://www.linux.org/threads/the-linux-kernel-compiling-and-installing.5208/

22.2.

Flavors

22.2.1.

PC

slackware RECOMENDADO EL MEJOR


archlinux
gentoo
ubuntu
debian
openbsd

22.3.

Versiones

linux 2.4

22.4.

Configuration

http://how-to.wikia.com/wiki/How_to_configure_the_Linux_kernel: listado de todas las opciones para 2.6 y brevement explicadas

22.5.

Debugger

http://kernel-handbook.alioth.debian.org/ch-scope.html

Kernel
52 / 94

23.

Instalacion del Kernel

23.1.

Formato del ncleo

vmlinux
VirtualMemoryLinux
archivo ejecutable que contien el nucleo del sistema operativo en formato:ELF, COFF, etc que nicamente se puede utilizar
para depurarlo, no para cargarlo en ram.
para usarlo como ncleo del sistema operativo debe ser capaz de ejecutarse e iniciar el computador. Para esto se debe agregar
un encabezado de arranque mltiple, un sector de arranque y rutinas de inicializacin.
el kernel vmlinux lleva asociado el fichero de smbolos system.map
imagen de vmlinux: bzimage
mvlinux se comprime con zlib y se genera la imagen vmlinuz o zImage
Big Compressed Image: debido al tamao grande del ncleo fue necesario el formato bzimage que permite dividir el ncleo
en regiones no contiguas de memoria.
El archivo bzImage contiene la concatenacin de

24.

bootsect.o
setup.o
misc.o
piggy.o : gzip del kernel vmlinux

Kernel Compilation Tutorial : initramfs Gentoo

https://wiki.gentoo.org/wiki/Custom_Initramfs

25.

Kernel Compilation Tutorial : LFS oficial

http://www.linuxfromscratch.org/lfs/view/development/index.html
nota
No sigo las instrucciones del libro porque hace falta instalar primero versiones especficas de las herramientas y
tambin PARCHES . Pero sera interesante leerlo para entender el proceso de instalacin. Intentar hacerlo con las
herramientas ya instaladas me imagino que dar problemas ya que por lo menos los parches no sern apropiados.
Resumiendo, tiene inters como mtodo de aprendizaje y no como mtodo prctico universal.

http://www.escomposlinux.org/lfs-es/lfs-es-SVN/chapter03/introduction.html
mkdir -p ~/tutoriales/lfs
cd tutoriales
export LFS=lfs
mkdir -v $LFS/sources
chmod -v a+wt $LFS/sources

Kernel
53 / 94

26.

Kernel Compilation Tutorial :desde cero (LFS) para Embedded

26.1.

Referencia

https://sites.google.com/site/4utils/articles/minimal_linux_system/minimal-linux-system-from-scratch
http://emsys.denayer.wenk.be/emedu/linux_from_scratch_qemu_tutorial.pdf: utiliza la librera uclibc. Recomendado. He realizado este tutorial pero todava no lo he terminado. Est copiado de:
http://free-electrons.com/doc/embedded_lfs.pdf
http://free-electrons.com/doc/embedded_lfs.odp
LFS
lfs spanish: versin 6.3
bfls qemu

26.2.

Introduccin

Queremos construir un kernel y un root file system para sistemas empotrados.


Dos alternativas
manualmente: desde Cero como LFS y freelectronics
Lo que se propone este apartado "desde cero (LFS) para Embedded". . . .sin conseguirlo
automaticamente con Buildroot , herramienta de freelectronics
Ver apuntes de Devel Tools Buildroot FUNCIONA

26.3.

Herramientas Necesarias

toolchain
uclibc
busybox
root file system
kernel menuconfig

26.4.

Compilacion del Kernel

26.4.1.

Introduccion

Para utilizar la librera uclibc no s donde tengo que instalarla, tampoco s donde instalar el toolchain. Seguir el tutorial de
freelectronics en lugar del de denayer.

Kernel
54 / 94

26.4.2.

Preface

Building linux from scratch using the qemu emulator


The following libraries are needed (use apt-get install if one is missing):

libc6-dev
gcc
make
linux-headers-386
libncurses5-dev
libuclibc-dev >
en ubuntu 12.04 no existe. http://uclibc.org/: uClibc (aka Clibc/pronounced yew-see-lib-see) is a C library for developing
embedded Linux systems.
en la web de busybox, http://www.busybox.net/:
 On Linux, Busybox releases are tested against uClibc (0.9.27 or later) and glibc (2.2 or later)
 If you require a small C library for Linux, the Busybox developers recommend uClibc
 http://busybox.net/~vda/HOWTO/i486-linux-uclibc/HOWTO.txt
 conclusin: descargo el fuente uclibc y lo compilo con make menuconfig y make.
http://www.eglibc.org/home. tengo instalado el paquete libc-dev-bin
uclibc-toolchain > http://www.uclibc.org/toolchains.html: genero el toolchain manualmente: native uClibc toolchain using
the uClibc buildroot system. Est explicado en los apartados siguientes
26.4.3.

Buildroot

Esto est realizado en Devel Tools Buildroot FUNCIONA


Buildroot is a tool that simplifies and automates the process of building a complete Linux system for an embedded system,
using cross-compilation. In order to achieve this, Buildroot is able to generate a cross-compilation toolchain, a root filesystem, a
Linux kernel image and a bootloader for your target. Buildroot can be used for any combination of these options, independently
(you can for example use an existing cross-compilation toolchain, and build only your root filesystem with Buildroot).
download buildroot candido@lur:~/git_repos/buildroot$ git pull
manual de instrucciones de buildroot
26.4.4.

Download kernel, busybox

Create workspace (e.g.: /home/user/lfs)


Download latest kernel from http://kernel.org (tested with 2.6.17 and 2.6.18)
tar -xvzf linux-2.6.32.61.tar.xz
Download Busybox from http://www.busybox.net/
tar -xvzf busybox-1.22.1.tar.bz2
26.4.5.

Download uclibc, buildroot

Esto no viene en el tutorial porque viene como requisito


Download uclibc from http://www.uclibc.org/downloads/
tar xvf uClibc-0.9.33.tar.xz
Download buildroot
cd ~/git_repos
git clone git://git.buildroot.net/buildroot

Kernel
55 / 94

26.4.6.

Create uclibc

~/tutoriales/kernel/uClibc-0.9.33 $ make menuconfig


salgo sin modificar las opciones por defecto
no existe ya ~/tutoriales/kernel
26.4.7.

Create toolchain for uclibc

cd ~/git_repos/buildroot
make menuconfig
Target Options: i386 y core2
Toolchain

type : build toolchaine


kernel headers > Manually created > 2.6.32
C Library > uclibc
uclibc version > 0.9.33
uclibc configuration > package/uclibc/uClibc-0.9.33
Compile and install uClibc utilities
version binutils 2.22

Cross compilation:NONE
make
OUTPUT candido@lur:~/git_repos/buildroot/output$ ls build host images staging target
build
buildroot-config

host-gmp-6.0.0a

host-mpc-1.0.2 -

host-m4-1.4.17

host-mpfr -

host-makedevs-undefined

linux-headers -

host-fakeroot-1.18.2
toolchain-undefined
host-gcc-final-4.7.3
uclibc-0.9.33.2
host-gcc-initial-4.7.3
_users_table.txt

build-time.log
-3.1.2
busybox-1.22.1
-2.6.32

LIBRERIA candido@lur:~$ ls /home/candido/git_repos/buildroot/output/build/uclibc-0.9.33.2/


Changelog
DEDICATION.mjn3 include lib
libubacktrace Makefile
Makerules test
COPYING.LIB
docs
INSTALL libc
libutil
Makefile.help README
TODO
COPYING.LIB.boilerplate extra
ldso
libcrypt
MAINTAINERS
Makefile.in
Rules.mak utils

libintl

libpthread

libm

libresolv

libnsl

librt

build-time.log contiene info de lo generado


host/usr
bin

i686-buildroot-linux-uclibc

include

lib

libexec

share

TOOLCHAIN ~/git_repos/buildroot/output/host/usr/i686-buildroot-linux-uclibc/bin$ ls
ar

as

cc

gcc

images/rootfs.tar
staging

ld

ld.bfd

nm

objcopy

objdump

ranlib

strip

Kernel
56 / 94

bin

lib

lib32

usr

target
bin

dev etc home lib lib32 linuxrc media mnt


THIS_IS_NOT_YOUR_ROOT_FILESYSTEM tmp usr var

opt

proc

root

run

sbin

sys

ha creado:
imagen: root file system
librera uclibc
toolchain
26.4.8.

Duda

para qu se va a utilizar la librera uclibc y el toolchain


el toolchain parece que lo ha utilizado buildroot para generar: kernel y root filesystem
26.4.9.

Create kernel

cd linux-2.6.32.61 no est hecho


make allnoconfig
make menuconfig
Executable file formats > Kernel support for ELF binaries > YES (teclear y)
File systems > Second extended fs support > YES
Device Drivers > ATA/ATAPI/MFM/RLL support > ATA/ATAPI/MFM/RLL support > YES > Enhanced IDE/MFM/RLL
disk . . . cdrom . . . tape . . . floppy support > YES > Include IDE/ATA2 DISK support > YES > Use multimode by default >
YES (en mi versin no aparece)
make
26.4.10.

Create filesystem

cd ../
dd if=/dev/zero of=rootfs.img bs=1024k count=1
mkfs.ext2 -i 1024 -F rootfs.img
26.4.11.

Create Busybox

cd busybox-1.22.1
make menuconfig
Busybox Settings >
Build Options >
Build BusyBox as a static binary >
YES
Busybox Settings >
Build Options >
Build BusyBox with a Cross Compiler >

Kernel
57 / 94

YES
Busybox Settings >
Build Options >
Cross Compiler prefix:
/usr/i386uclibclinux/
bin/i386uclibclinux
Coreutils >
cat chmod chown chroot cp cut date df du echo env false head ln ls mkdir
mknod mv printf pwd rm rmdir sleep sort stat stty sync tail test touch true tty uname
Console Utilities >
setconsole
Editors >
vi
Finding Utilities >
grep
Init Utilities >
init
Login/Password Management Utilities >
addgroup delgroup adduser deluser getty login
passwd su
Linux System Utilities >
more mount umount
Process Utilities >
free kill
Shells >
ash
Shells >
Choose your default shell >
ash

# make
sudo make install
26.4.12.

Fill filesystem

cd ..
sudo mkdir /mnt/rootfs
sudo mount -o loop rootfs.img /mnt/rootfs
rsync -a busyboxxxx/_install/* /mnt/rootfs/
sudo mkdir /mnt/rootfs/dev
sudo mkdir /mnt/rootfs/etc
sudo mkdir /mnt/rootfs/proc
sudo mkdir /mnt/rootfs/sys
sudo mkdir /mnt/rootfs/etc/init.d
sudo mknod /mnt/rootfs/dev/console c 5 1
sudo mknod /mnt/rootfs/dev/null c 1 3
Create file (/mnt/rootfs/etc/inittab)

Kernel
58 / 94

# This is run first script


::sysinit:/etc/init.d/rcS
# Start an askfirst shell on the console
::askfirst:/bin/sh
# Stuff to do when restarting the init process
::restart:/sbin/init
# Stuff to do before rebooting
::ctrlaltdel:/sbin/reboot
::shutdown:/bin/umount -a -r

Create file (/mnt/rootfs/etc/init.d/rcS)


#!/bin/sh
mount -t proc none /proc
mount -t sysfs none /sys
/bin/sh

sudo chown R root.root /mnt/rootfs


sync

26.5.

Emulate kernel and filesystem

qemu -m 32 -hda rootfs.img -kernel linuxxxx/arch/i386/boot/bzImage -append "root=/dev/hda


clock=pit"

26.6.

FUNCIONA O NO FUNCIONA

????????????????

27.

QEMU

QEMU apuntes y casos de SO


Casos de emulaciones: aqu mismo: apuntes de kernel

28.
28.1.

Kernel Compilation and QEMU Tutorial: ARM


blogs

blog
linux 3.2, armv7, versatile express platform, linaro toolchain.
blog
linux 3.9, busybox, versatile express platform, qemu from linaro, codesourcery platform

29.
29.1.

Kernel Compilation Tutorials: Embedded


General

http://retired.beyondlogic.org/uClinux/builduC.htm

Kernel
59 / 94

29.2.

Flavors

openwrt: wireles buildroot

29.3.

Platforms

i386: buildroot (kernel image, toolchain ), network_interface setting


Freescale
Linux 2.6.29.4-rt17. The target for emulation is a custom board made by ABB. This board is based on the Freescale Lite5200 evaluation board[5]. The microprocessor on board is the Freescale MPC5200B[6], a PowerPC embedded processor:
recomendado sobre todo a nivel conceptual.
sony smartphone xperia

30.

Kernel: Small, Tiny

30.1.

Referencias

30.2.

How to Build A Custom Linux Kernel For Qemu (2015 Edition)

http://mgalgs.github.io/2015/05/16/how-to-build-a-custom-linux-kernel-for-qemu-2015-edition.html
Arranca en menos de un segundo. Creo que el sistema de ficheros est en ram. No hay disco duro

31.

TEST

31.1.

Evaluacin del Kernel

Autotest Tool Testing the Untestable


https://github.com/linux-test-project/ltp/wiki
The Linux Test Project : LTP
Autotest is a framework for fully automated testing of low-level systems, including kernels and hardware.
Autotest and its predecessor, IBM Autobench
The platform on which Autotest runs is itself under test.
tasks such as kernel installation and hardware configuration must be simple,
every running test requires a physical machine no virtualization
No complex: developing new tests should be a simple, familiar process, requiring interaction with only a small subset of the
available infrastructure.
Client
C
Phyton
http://www.landley.net/kdocs/ols/2006/ols2006v1-pages-113-126.pdf

Kernel
60 / 94

32.

TODO: ME GUSTARIA

32.1.

bare metal con la bios

http://wiki.osdev.org/Detecting_Memory_%28x86%29#BIOS_Function:_INT_0x15.2C_EAX_.3D_0xE820
lo referencian en el Manula de Pure64 de Return Infinity Os bare metal : https://github.com/ReturnInfinity/Pure64/blob/master/Pure64%20Manual.md

32.2.

Juntar los tutoriales bare_metal vga color y teclado

bare_metal de devos_myos i686 con color y el de kernel-201 con teclado de Arjun Sreedharan

32.3.

baremetal-qemu-kernel(keyboard-busybox)-file system

objetivo: Cmo aadir a un kernelconkeyboard la posibilidad de interpretar unos pequeos comandos (editar un fichero)
http://elinux.org/QEMU

33.

Tutorial Boot Sector Susam Palm

http://susam.in/articles/boot-sector-code/
#
#
#
#
#
#
#
#
#

Author: Susam Pal <http://susam.in/>


To assemble and link this code, execute the following commands:as -o char.o char.s
ld --oformat binary -o char.com char.o
To write this code into the boot sector of a device, say /dev/sdb:dd if=char of=/dev/sdb
echo -ne "\x55\xaa" | dd seek=510 bs=1 of=/dev/sdb

.code16
.section .text
.globl _start
_start:
mov $0xb800, %ax #direccin de la memoria de video -> VGA
mov %ax, %ds
#inicializo el registro del segmento de datos
movb $A, 0
#en el offset cero (DS:0) cargo el byte A -> caracter a escribir
movb $0x1e, 1
#en el offset uno (DS:1) cargo el byte ox1e -> color background y foreground
idle:
jmp idle # bucle infinito

file char.com char.com: COM executable for DOS


hd char.com hex dump
Emularlo con dosemu
mv char.com ~/.dosemu/drive_c
xdosemu &
DOS C> dir
C> char.com - nada ms ejecutarse el emulador se cierra

Kernel
61 / 94

dosemu char.com -E para que no se cierre


About Execute -p
Bad command or filename - "-p"

ejecutarlo desde el boot sector de una particin


dd if=char.com of=/dev/sdb
echo -ne "\x55\xaa" | dd seek=510 bs=1 of=/dev/sdb

string.s
as -o string.o string.s
ld --oformat binary -Ttext 7c00 -Tdata 7c20 -o string string.o Ttext es el offset de la seccin
While booting, the BIOS reads the code from the first sector of the boot device into the memory at physical address
0x7c00 and jumps to that address.
objdump -bbinary -mi8086 -D string
hd string
string.com para emular con emulDOS
as -o string.o string.s
ld --oformat binary -Ttext 100 -Tdata 120 -o string.com string.o
objdump -bbinary -mi8086 -D string.com
hd string.com
cp string.con ~/.dosemu/drive_c
Ctrl-F1 : lo ejecuto desde la consola
cd ~/.dosemu/drive_c
SOLUCION
Qu tal ejecutar DOSBox: http://www.dosbox.com/

34.

Tutorial Bare Metal: osdever hello world

Cmo desarrollar un kernel simple


no lo he probado

35.

Tutorial Bare Bones: Viridis

emulacion de grub2 con qemu

Kernel
62 / 94

36.

Tutorial Bare Bones: Arjun Sreedharan

36.1.

Kernel 101

36.1.1.

intro

FUNCIONA
http://arjunsreedharan.org/post/82710718100/kernel-101-lets-write-a-kernel
simple kernel which could be loaded with the GRUB bootloader on an x86
runs in protected mode and prints a string on the screen
tools
NASM assembler
gcc
ld (GNU Linker)
grub
https://github.com/arjun024/mkernel
36.1.2.

kernel

source modules
kernel.asm: run on a processor operating in 32 bit mode. Call to kmain()
kmain.c : memory in protected mode
The memory mapped input/output for the screen starts at [0xb8000] and supports 25 lines, each line contain 80 ascii
characters
linker script link.ld
enlazar kernel.o y kmain.o
definicion de las secciones
we set the location counter to [0x100000]
After the linker places the text output section, the value of the location counter will become 0x1000000 ms the size of
the text output section.
36.1.3.

boot process

CPU 0xFFFFFFF0 address :apunta al top -16bytes del espacio de 32 bytes (4GBytes) ser una direccin de la bios
en esos 16 bytes hay una instruccin de salto incondicional a la direccin donde estn las siguientes instrucciones de la bios
Bios
a. BIOS first searches for a bootable device in the configured boot device order. It checks for a certain magic number to
determine if the device is bootable or not.
b. Once the BIOS has found a bootable device, it copies the contents of the devices first sector into RAM starting from
physical address 0x7c00. El cdigo se ha copiado ha sido el bootloader
c. El espacio de direcciones pasa de la Flash de la Bios a la RAM: jump 0x7c00 : se ejecuta el bootloader cargado
previamente en la RAM
d. The bootloader then loads the kernel at the physical address [0x100000]

Kernel
63 / 94

36.1.4.

kernel building

kernel.c
/*
* kernel.c
*/
void kmain(void)
{
const char *str = "my first kernel";
char *vidptr = (char*)0xb8000; //video mem begins here.
unsigned int i = 0;
unsigned int j = 0;
/* this loops clears the screen
* there are 25 lines each of 80 columns; each element takes 2 bytes */
while(j < 80 * 25 * 2) {
/* blank character */
vidptr[j] = ;
/* attribute-byte - light grey on black screen */
vidptr[j+1] = 0x07;
j = j + 2;
}
j = 0;
/* this loop writes the string to video memory */
while(str[j] != \0) {
/* the characters ascii */
vidptr[i] = str[j];
/* attribute-byte: give character black bg and light grey fg */
vidptr[i+1] = 0x07;
++j;
i = i + 2;
}
return;
}

GRUB will only load our kernel if it complies with the Multiboot spec.
modificamos el kernel.asm
;;kernel.asm
;nasm directive - 32 bit
bits 32
section .text
;multiboot spec
align 4
dd 0x1BADB002
;magic
dd 0x00
;flags
dd - (0x1BADB002 + 0x00) ;checksum. m+f+c should be zero
global start
extern kmain
start:
cli
mov esp, stack_space
call kmain
hlt

;kmain is defined in the c file

;block interrupts
;set stack pointer
;halt the CPU

Kernel
64 / 94

section .bss
resb 8192
stack_space:

;8KB for stack

link.ld : linker script


/*
* link.ld
*/
OUTPUT_FORMAT(elf32-i386)
ENTRY(start)
SECTIONS
{
. = 0x100000;
.text : { *(.text) }
.data : { *(.data) }
.bss : { *(.bss) }
}

generamos el objeto kernel in ELF-32 bit format.


cd ~/tutoriales/bare_metal/kernel-101/
nasm -f elf32 kernel.asm -o kasm.o
gcc -m32 -c kernel.c -o kc.o
ld -m elf_i386 -T link.ld -o kernel kasm.o kc.o
ls -l
-rw-rw-r-- 1 candido candido 608 Oct 29 14:09 kasm.o
-rw-rw-r-- 1 candido candido 1096 Oct 29 14:09 kc.o
-rwxrwxr-x 1 candido candido 5001 Oct 29 14:09 kernel
-rw-rw-r-- 1 candido candido 480 Oct 29 14:07 kernel.asm
-rw-rw-r-- 1 candido candido 704 Oct 29 14:08 kernel.c
-rw-rw-r-- 1 candido candido 161 Oct 29 14:07 link.ld

I renamed my kernel executable to kernel-101: cp kernel kernel-101


36.1.5.

Emulation

qemu-system-i386 -kernel kernel-101 FUNCIONA


36.1.6.

Building a bootable cdrom image

Booting the kernel


Building a bootable cdrom image
creamos grub.cfg
menuentry "kernel-101" {
multiboot /boot/kernel-101
}

en ~/tutoriales/bare_metal/kernel-101
mkdir -p isodir/boot
cp kernel-101 isodir/boot/kernel-101
mkdir -p isodir/boot/grub
cp grub.cfg isodir/boot/grub/grub.cfg
grub-mkrescue -o kernel-101.iso isodir

kernel-101.iso ha sido creado

Kernel
65 / 94

Resultado
candido@lur:~/tutoriales/bare_metal/kernel-101$ ls
grub.cfg isodir kasm.o kc.o kernel-101 kernel-101.iso

kernel.asm

kernel.c

link.ld

Testing your operating system (QEMU)


qemu-system-i386 -cdrom kernel-101.iso - FUNCIONA
Sera interesante ejecutar el debugger
con la librera esttica sera interesante ver como se programa y ejecuta el acceso del kernel a la tarjeta grfica y monitor
Ejecutar directamente el binario kernel
qemu-system-i386 -kernel kernel-101 - FUNCIONA
36.1.7.

Bootloader on disk

NO LO HE PROBADO: peligroso editar grub.cfg


El programa bootloader ya lo tengo grabado en el sector de mi particin de arranque
Hay que aadir el nuevo kernel
Copiar el kernel en la carpeta /boot
In your GRUB2 configuration file grub.cfg you should add an entry, something like:
menuentry kernel 101 {
set root=hd0,msdos1
multiboot /boot/kernel-101 ro
}

36.2.

Kernel 201

36.2.1.

info

FUNCIONA
http://arjunsreedharan.org/post/99370248137/kernel-201-lets-write-a-kernel-with-keyboard
Extension of the Kernel 101
Today, we will extend that kernel to include keyboard driver that can read the characters a-z and 0-9 from the keyboard
and print them on screen.
tools
https://github.com/arjun024/mkeykernel
36.2.2.

source

candido@lur:~/tutoriales/bare_metal/kernel-201$ git clone https://github.com/arjun024/mkeykernel


candido@lur:~/tutoriales/bare_metal/kernel-201/mkeykernel$ ls
binary_x86 kernel.asm kernel.c keyboard_map.h LICENSE link.ld

README.md

Kernel
66 / 94

36.2.3.

Build

Readme
nasm -f elf32 kernel.asm -o kasm.o
gcc -m32 -c kernel.c -o kc.o
ld -m elf_i386 -T link.ld -o kernel kasm.o kc.o
qemu-system-i386 -kernel kernel

FUNCIONA

37.

Tutoriales Bare Bones OsDev

http://wiki.osdev.org/Tutorials
http://wiki.osdev.org/Bare_Bones 32 bits FUNCIONA
http://wiki.osdev.org/Creating_a_64-bit_kernel
http://wiki.osdev.org/Real_mode_assembly_bare_bones
http://wiki.osdev.org/How_Do_I_Use_A_Debugger_With_My_OS debug kernel

38.

Tutorial Bare Bones: OSDev Myos: 64 bits

http://wiki.osdev.org/Creating_a_64-bit_kernel
Sin hacer

39.

Tutorial Bare Bones: OSDev MyOS: i686-elf

39.1.

Boot y kernel

FUNCIONA
http://wiki.osdev.org/Bare_Bones
Ver GCC Cross Compiler Apuntes
el sistema MyOS ha de ser para una cpu de 32 bits por lo que el target platform del cross compiler ser i686-elf donde el
i686 no puede ser x86_64 y s x86.
an operating system for x86
boot.s - kernel entry point that sets up the processor environment
kernel.c - your actual kernel routines
linker.ld - for linking the above files
booting de operating system
export PATH="$HOME/software/cross_i686-elf/bin:$PATH" acceso al cross compiler
cd ~/tutoriales/bare_metal/os_dev
copiamos boot.s

Kernel
67 / 94

# Declare constants used for creating a multiboot header.


.set ALIGN,
1<<0
# align loaded modules on page boundaries
.set MEMINFO, 1<<1
# provide memory map
.set FLAGS,
ALIGN | MEMINFO # this is the Multiboot flag field
.set MAGIC,
0x1BADB002
# magic number lets bootloader find the header
.set CHECKSUM, -(MAGIC + FLAGS) # checksum of above, to prove we are multiboot
#
#
#
#
#

Declare a header as in the Multiboot Standard. We put this into a special


section so we can force the header to be in the start of the final program.
You dont need to understand all these details as it is just magic values that
is documented in the multiboot standard. The bootloader will search for this
magic sequence and recognize us as a multiboot kernel.

.section .multiboot
.align 4
.long MAGIC
.long FLAGS
.long CHECKSUM
#
#
#
#

Currently the stack pointer register (esp) points at anything and using it may
cause massive harm. Instead, well provide our own stack. We will allocate
room for a small temporary stack by creating a symbol at the bottom of it,
then allocating 16384 bytes for it, and finally creating a symbol at the top.

.section .bootstrap_stack, "aw", @nobits


stack_bottom:
.skip 16384 # 16 KiB
stack_top:
# The linker script specifies _start as the entry point to the kernel and the
# bootloader will jump to this position once the kernel has been loaded. It
# doesnt make sense to return from this function as the bootloader is gone.
.section .text
.global _start
.type _start, @function
_start:
# Welcome to kernel mode! We now have sufficient code for the bootloader to
# load and run our operating system. It doesnt do anything interesting yet.
# Perhaps we would like to call printf("Hello, World\n"). You should now
# realize one of the profound truths about kernel mode: There is nothing
# there unless you provide it yourself. There is no printf function. There
# is no <stdio.h> header. If you want a function, you will have to code it
# yourself. And that is one of the best things about kernel development:
# you get to make the entire system yourself. You have absolute and complete
# power over the machine, there are no security restrictions, no safe
# guards, no debugging mechanisms, there is nothing but what you build.
#
#
#
#
#
#
#
#

By now, you are perhaps tired of assembly language. You realize some
things simply cannot be done in C, such as making the multiboot header in
the right section and setting up the stack. However, you would like to
write the operating system in a higher level language, such as C or C++.
To that end, the next task is preparing the processor for execution of
such code. C doesnt expect much at this point and we only need to set up
a stack. Note that the processor is not fully initialized yet and stuff
such as floating point instructions are not available yet.

# To set up a stack, we simply set the esp register to point to the top of
# our stack (as it grows downwards).
movl $stack_top, %esp

Kernel
68 / 94

# We are now ready to actually execute C code. We cannot embed that in an


# assembly file, so well create a kernel.c file in a moment. In that file,
# well create a C entry point called kernel_main and call it here.
call kernel_main
#
#
#
#
#
#

In case the function returns, well want to put the computer into an
infinite loop. To do that, we use the clear interrupt (cli) instruction
to disable interrupts, the halt instruction (hlt) to stop the CPU until
the next interrupt arrives, and jumping to the halt instruction if it ever
continues execution, just to be safe. We will create a local label rather
than real symbol and jump to there endlessly.

cli
hlt
.Lhang:
jmp .Lhang
# Set the size of the _start symbol to the current location . minus its start.
# This is useful when debugging or when you implement call tracing.
.size _start, . - _start

i686-elf-as boot.s -o boot.o


file boot.o boot.o: ELF 32-bit LSB relocatable, Intel 80386, version 1 (SYSV), not stripped
Implementing the Kernel
copiamos kernel.c
#if !defined(__cplusplus)
#include <stdbool.h> /* C doesnt have booleans by default. */
#endif
#include <stddef.h>
#include <stdint.h>
/* Check if the compiler thinks we are targeting the wrong operating system. */
#if defined(__linux__)
#error "You are not using a cross-compiler, you will most certainly run into trouble"
#endif
/* This tutorial will only work for the 32-bit ix86 targets. */
#if !defined(__i386__)
#error "This tutorial needs to be compiled with a ix86-elf compiler"
#endif
/* Hardware text mode color constants. */
enum vga_color {
COLOR_BLACK = 0,
COLOR_BLUE = 1,
COLOR_GREEN = 2,
COLOR_CYAN = 3,
COLOR_RED = 4,
COLOR_MAGENTA = 5,
COLOR_BROWN = 6,
COLOR_LIGHT_GREY = 7,
COLOR_DARK_GREY = 8,
COLOR_LIGHT_BLUE = 9,
COLOR_LIGHT_GREEN = 10,
COLOR_LIGHT_CYAN = 11,
COLOR_LIGHT_RED = 12,
COLOR_LIGHT_MAGENTA = 13,
COLOR_LIGHT_BROWN = 14,

Kernel
69 / 94

COLOR_WHITE = 15,
};
uint8_t make_color(enum vga_color fg, enum vga_color bg) {
return fg | bg << 4;
}
uint16_t make_vgaentry(char c, uint8_t color) {
uint16_t c16 = c;
uint16_t color16 = color;
return c16 | color16 << 8;
}
size_t strlen(const char* str) {
size_t ret = 0;
while ( str[ret] != 0 )
ret++;
return ret;
}
static const size_t VGA_WIDTH = 80;
static const size_t VGA_HEIGHT = 25;
size_t terminal_row;
size_t terminal_column;
uint8_t terminal_color;
uint16_t* terminal_buffer;
void terminal_initialize() {
terminal_row = 0;
terminal_column = 0;
terminal_color = make_color(COLOR_LIGHT_GREY, COLOR_BLACK);
terminal_buffer = (uint16_t*) 0xB8000;
for (size_t y = 0; y < VGA_HEIGHT; y++) {
for (size_t x = 0; x < VGA_WIDTH; x++) {
const size_t index = y * VGA_WIDTH + x;
terminal_buffer[index] = make_vgaentry( , terminal_color);
}
}
}
void terminal_setcolor(uint8_t color) {
terminal_color = color;
}
void terminal_putentryat(char c, uint8_t color, size_t x, size_t y) {
const size_t index = y * VGA_WIDTH + x;
terminal_buffer[index] = make_vgaentry(c, color);
}
void terminal_putchar(char c) {
terminal_putentryat(c, terminal_color, terminal_column, terminal_row);
if (++terminal_column == VGA_WIDTH) {
terminal_column = 0;
if (++terminal_row == VGA_HEIGHT) {
terminal_row = 0;
}
}
}
void terminal_writestring(const char* data) {
size_t datalen = strlen(data);

Kernel
70 / 94

for (size_t i = 0; i < datalen; i++)


terminal_putchar(data[i]);
}
#if defined(__cplusplus)
extern "C" /* Use C linkage for kernel_main. */
#endif
void kernel_main() {
/* Initialize terminal interface */
terminal_initialize();
/* Since there is no support for newlines in terminal_putchar
* yet, \n will produce some VGA specific character instead.
* This is normal.
*/
terminal_writestring("Hello, kernel World!\n");
}

i686-elf-gcc -c kernel.c -o kernel.o -std=gnu99 -ffreestanding -O2 -Wall -Wextra


Linking the Kernel
our own customized linker script copio link.ld
/* The bootloader will look at this image and start execution at the symbol
designated as the entry point. */
ENTRY(_start)
/* Tell where the various sections of the object files will be put in the final
kernel image. */
SECTIONS
{
/* Begin putting sections at 1 MiB, a conventional place for kernels to be
loaded at by the bootloader. */
. = 1M;
/* First put the multiboot header, as it is required to be put very early
early in the image or the bootloader wont recognize the file format.
Next well put the .text section. */
.text BLOCK(4K) : ALIGN(4K)
{
*(.multiboot)
*(.text)
}
/* Read-only data. */
.rodata BLOCK(4K) : ALIGN(4K)
{
*(.rodata)
}
/* Read-write data (initialized) */
.data BLOCK(4K) : ALIGN(4K)
{
*(.data)
}
/* Read-write data (uninitialized) and stack */
.bss BLOCK(4K) : ALIGN(4K)
{
*(COMMON)
*(.bss)
*(.bootstrap_stack)
}

Kernel
71 / 94

/* The compiler may produce other sections, by default it will put them in
a segment with the same name. Simply add stuff here as needed. */
}

i686-elf-gcc -T linker.ld -o myos.bin -ffreestanding -O2 -nostdlib boot.o kernel.o


-lgcc
The file myos.bin is now your kernel
Resultado
candido@lur:~/tutoriales/bare_metal/os_dev$ ls
boot.o boot.s
kernel.c kernel.o linker.ld

39.2.

myos.bin

Emulacion del kernel

Ejecutar directamente el binario kernel


qemu-system-i386 -kernel myos.bin - ERROR pero lo he solucionado
Error while fetching elf kernel from rom
When using the -kernel option QEMU fails with "Error while fetching elf kernel from rom" when the ELF file contains a segment with a file size of 0. This is typical for segments containing only a .bss section.
rom_copy (hw/core/loader.c) fails to load roms (elf segments in this case) with a datasize of 0 - it skips the rom because rom->data is NULL. This bug is introduced by commit d60fa42e8bae39440f997ebfe8fe328269a57d16 Save memory allocation in the elf loader and affects QEMU v1.5.0 and later.
Ill send a patch for this bug to qemu-devel.

https://searchcode.com/codesearch/view/76193342/
Puede que sea un error del propio programa QEMU; habr que compilarlo desde los fuentes con sumo cuidado de la
configuracion
solucion: reeditar el script del linker: linker.ld
/*el script oficial da error al ejecutar el kernel directamente: qemu-system-i386 - kernel myos.bin
la solucin est en editar el alineamiento de las secciones BLOCK(4K) : ALIGN(4K)
REEDITO BLOCK(2K) : ALIGN(2K) en lugar de BLOCK(4K) : ALIGN(4K)
*/
/* output format i386*/
OUTPUT_FORMAT(elf32-i386)
/* The bootloader will look at this image and start execution at the symbol
designated as the entry point. */
ENTRY(_start)
/* Tell where the various sections of the object files will be put in the final
kernel image. */
SECTIONS
{
/* Begin putting sections at 1 MiB, a conventional place for kernels to be
loaded at by the bootloader. */
. = 1M;

Kernel
72 / 94

/* First put the multiboot header, as it is required to be put very early


early in the image or the bootloader wont recognize the file format.
Next well put the .text section. */
.text BLOCK(2K) : ALIGN(2K)
{
*(.multiboot)
*(.text)
}
/* Read-only data. */
.rodata BLOCK(2K) : ALIGN(2K)
{
*(.rodata)
}
/* Read-write data (initialized) */
.data BLOCK(2K) : ALIGN(2K)
{
*(.data)
}
/* Read-write data (uninitialized) and stack */

.bss
{

BLOCK(2K) : ALIGN(2K)
*(COMMON)
*(.bss)
*(.bootstrap_stack)

/* The compiler may produce other sections, by default it will put them in
a segment with the same name. Simply add stuff here as needed. */
}

FUNCIONA: el problema deber ser el tamao de los bloques. 4K es una pgina. No s el por qu de esta limitacin

FUNCIONA: He probado el kernel con terminal_color = make_color(COLOR_LIGHT_GREY, COLOR_LIGHT_GRE


en lugar de terminal_color = make_color(COLOR_LIGHT_GREY, COLOR_BLACK);
ayuda scritps linker: significado de .bss BLOCK(4K) : ALIGN(4K)
https://sourceware.org/binutils/docs/ld/LD-Index.html
SECTIONS https://sourceware.org/binutils/docs/ld/SECTIONS.html#SECTIONS
https://sourceware.org/binutils/docs/ld/Output-Section-Name.html#Output-Section-Name
* https://sourceware.org/binutils/docs/ld/Input-Section-Wildcards.html#Input-Section- Wildcards
.bss { *(.bss) *(COMMON) } -> https://sourceware.org/binutils/docs/ld/Input-Section- Common.html#Input-Section-Common
https://sourceware.org/binutils/docs/ld/Output-Section-Description.html#Output-Section -Description -> sintaxis
https://sourceware.org/binutils/docs/ld/Output-Section-Attributes.html#Output-Section- Attributes -> atributos: address, forced output aligned
BLOCK -> address -> https://sourceware.org/binutils/docs/ld/Output-Section-Address. html#Output-Section-Address -> opcional
-> https://sourceware.org/binutils/docs/ld/Builtin-Functions.html#index- BLOCK_0028_0040var_007bexp_007d_0029-557
-> sinnimo de ALIGN
ALIGN -> https://sourceware.org/binutils/docs/ld/Forced-Output-Alignment.html#Forced- Output-Alignment

Kernel
73 / 94

Building a bootable cdrom image


creamos grub.cfg
menuentry "myos" {
multiboot /boot/myos.bin
}

39.3.

Emulacin del multiboot con grub

Emulacin del multiboot


en ~/tutoriales/bare_metal/os_dev
mkdir -p isodir
mkdir -p isodir/boot
cp myos.bin isodir/boot/myos.bin
mkdir -p isodir/boot/grub
cp grub.cfg isodir/boot/grub/grub.cfg
grub-mkrescue -o myos.iso isodir

myos.iso ha sido creado


Testing your operating system (QEMU)
qemu-system-i386 -cdrom myos.iso - FUNCIONA
Sera interesante ejecutar el debugger
con la librera esttica sera interesante ver como se programa y ejecuta el acceso del kernel a la tarjeta grfica y monitor

39.4.

Kernel Debug

http://www.linux-magazine.com/Online/Features/Qemu-and-the-Kernel
http://wiki.osdev.org/Kernel_Debugging: sigo el tutorial
Apuntes GDB Server
Compilacion con la opcin -g
cd ~/tutoriales/bare_metal/os_dev_debug
export PATH="$HOME/software/cross_i686-elf/bin:$PATH"
i686-elf-gcc -g -c kernel.c -o kernel.o -std=gnu99 -ffreestanding -O2 -Wall -Wextra
i686-elf-as -gstabs boot.s -o boot.o

i686-elf-gcc -T linker.ld -o myos.bin -ffreestanding -O2 -nostdlib boot.o kernel.o -lgc


qemu-system-i386 -kernel myos.bin
Bootable disk
cp myos.bin isodir/boot/myos.bin
cp grub.cfg isodir/boot/grub/grub.cfg
grub-mkrescue -o myos.iso isodir
qemu-system-i386 -cdrom myos.iso
ls -l
boot.o

boot.s

grub.cfg

isodir

kernel.c

kernel.o

linker.ld

myos.bin

myos.iso

Kernel
74 / 94

Dos terminales desde ~/tutoriales/bare_metal/os_dev_debug


1 terminal: qemu-system-i386 -s -S -cdrom myos.iso MENSAJE QEMU STOPPED EN UN TERMINAL EN BLANCO
will setup Qemu to listen on port 1234 and wait for a gdb connection to it
2 terminal:
gdb
(gdb) target remote localhost:1234
Remote debugging using localhost:1234
0x0000fff0 in ?? ()

(gdb) info sources


No symbol table is loaded.

Use the "file" command.

(gdb) symbol-file myos.sym Reading symbols from myos.sym. . . done.


 myos.sym lo he obtenido con objcopy --only-keep-debug myos.bin myos.sym
(gdb) info sources
Source files for which symbols have been read in:
/home/candido/tutoriales/bare_metal/os_dev_debug/boot.s
Source files for which symbols will be read in on demand:
/home/candido/software/cross_i686-elf/lib/gcc/i686-elf/4.6.3/include/stdint-gcc.h,
/home/candido/software/cross_i686-elf/lib/gcc/i686-elf/4.6.3/include/stdint.h,
/home/candido/software/cross_i686-elf/lib/gcc/i686-elf/4.6.3/include/stddef.h,
/home/candido/tutoriales/bare_metal/os_dev_debug/kernel.c

(gdb)b _start Breakpoint 1 at 0x10000c: file boot.s, line 58.


(gdb)b kernel_main Breakpoint 2 at 0x1001e0: file kernel.c, line 103.
(gdb)C-x a visualizo la ventana con el cdigo fuente
(gdb)continue
 EN EL OTRO TERMINAL SE EJECUTA HASTA EL MENU DE GRUB selecciono myos y enter
Breakpoint 1, _start () at boot.s:58
58
movl $stack_top, %esp

(gdb)s
(gdb)s
Breakpoint 2, kernel_main () at kernel.c:103

(gdb)s
Se ejecuta paso a paso hasta el final FUNCIONA

40.

Tutorial BareMetal Farid

40.1.

Introduccin

Tiene escritos dos tutoriales


bare metal hello world
freebsd assembler hello world
FreeBSD/i386 and FreeBSD/amd64 platforms

Kernel
75 / 94

40.2.

Hello World con kernel freebsd

freebsd assembler hello world


Hello, World in C
/* hello0.c -- hello, world! */
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>
const char *msg = "hello, world!\n"; //puntero constante
int main (int argc, char *argv[])
{
write(1, msg, 14);
return 0;
}

cc -static -o hello0 hello0.c: esttico para tener los smbolos de las llamada al sistema write
ktrace y kdump son propios del sistema operativo FreeBSD
Hello, World in FreeBSD/amd64 (interacciona con el kernel) Assembler: GNU ASM (GAS)
// hello_amd64.S -- hello world in GNU ASM (GAS). FreeBSD/amd64 version.
// Some constants
.equiv STDOUT, 1
.equiv RETVAL, 0
.equiv SYS_WRITE, 4
.equiv SYS_EXIT, 1

/*
/*
/*
/*

file descriptor for stdout */


argument for exit() */
WRITE syscall ID */
EXIT syscall ID */

// Data section (read-only)


.section
.rodata
msg:
.string "hello, world!\n"
len = . - msg
// Code section
.text
.global
_start
_start:
/*
* According to http://www.x86-64.org/documentation/abi.pdf
* page 124 (A.2.1), the arguments for a LINUX syscall are
* passed in the following regs:
%rdi, %rsi, %rdx, %r10, %r8 and %r9
*
* One has to issue a syscall instruction,
* which destroys %rcx.
* %rax contains the number of the syscall.
* Returing from syscall, register %rax contains the result.
*
* Note that FreeBSD/amd64 seems to follow the LINUX convention,
* unlike FreeBSD/i386 which uses the stack for its arguments.
*/
// Call
movl
movq
movl

write(STDOUT,msg,len);
$len, %edx
$msg, %rsi
$STDOUT, %edi

Kernel
76 / 94

movq
$SYS_WRITE, %rax
movq
%rcx, %r10
syscall

/* syscall destroys %rcx! */

bye:
// Call exit(0);
movl
$RETVAL, %edi
movq
$SYS_EXIT, %rax
movq
%rcx, %r10
syscall

/* syscall destroys %rcx! */

Compilacion
% as --64 -o hello_amd64.o hello_amd64.S
% ld -o hello_amd64 hello_amd64.o

linkage esttico: file hello_amd64


ktrace ./hello_amd64
% objdump --disassemble hello_amd64
objdump --full-contents hello_amd64
% objdump --section-headers hello_amd64

40.3.

Hello World Bare Metal

40.3.1.

Introduccin

Tiene el inters de que:


Programamos con las funciones de la BIOS
Programamos en modo real 16 bits utiliza modo de direccionamiento segmentado
40.3.2.

carpeta tutorial

~/tutoriales/bare_metal/farid
40.3.3.

fundamentals

http://farid.hajji.name/blog/2010/05/25/hello-world-on-the-bare-metal/
In the beginning, Man created Hardware and Firmware.
Firmware laid lurking in a Flash/ROM chip
CPU initialized itself to Real Mode, by setting its registers to well-defined values
CPU jumped to the address 0xFFFF:FFF0, which was the entry point of the Firmware. And the BIOS awoke and took
over from there, initializing the rest of the Hardware.
BIOS looked at its list of boot devices: started loading the first 512-bytes sector of the first boot device into the
RAM at address 0x0000:7C00.
having verified that the sector it loaded into RAM was valid and magic (last word of that sector contained the magic bytes
0x55 and 0xAA) the BIOS made the CPU jump (with joy) to this initial address 0xFFFF:FFF0

Kernel
77 / 94

40.3.4.

Source Code

Makefile, which contains the instructions how to build and execute our program;
make
as -o hello.o hello.S
ld -N -e start -Ttext 0x7c00 --oformat binary -o hello hello.o
biosfunc.S, which will serve as an include file and which will contain multiple convenience functions used by the main
program;
define las funciones clrscr,curshome(), puts(), putc()
/* biosfunc.S -- real-mode BIOS and convenience functions. */
.file
.code16

"biosfunc.S"

/*
* The following convenience functions are only available
* in real mode through BIOS:
*
# clear display
* void clrscr()
# move cursor home (0:0)
* void curshome()
void
puts(
%si)
# display string
*
# display char
* void putc( %al)
*
* use this libary like this:
.include biosfunc.S
*
*/
/* clrscr() -- clear dislay */
clrscr:
/*
* clrscr() clears the video buffer, using a special case in
* the BIOS function "SCROLL UP WINDOW". Note that this
* function is only available in real mode, and that some
* buggy BIOSes destroy the base pointer %bp, so we better
* temporarily save it on the stack.
*/
pushw %bp
# BIOS call below *can* destroy %BP
movb
movb
movb
movw
movw
int

$0x06,
$0x0,
$0x7,
$0x0,
$0x184f,
$0x10

popw
retw

%bp

%ah
%al
%bh
%cx
%dx

#
#
#
#
#
#

BIOS function "SCROLL UP WINDOW"


nr. of lines to scroll (00=clear window)
attr. to fill new lines at bottom
CH,CL: row,column upper left corner (00:00)
DH,DL: row,column lower right corner (24:79)
call BIOS

/* curshome() -- set cursor position to 0:0 */


curshome:
/*
* curshome() moves the cursor to position 0:0 (top:left),
* using the BIOS function "SET CURSOR POSITION". This
* function is only available in real mode.
*/
movb $0x02, %ah
# BIOS function "SET CURSOR POSITION"
movb $0x0, %bh
# page number 0

Kernel
78 / 94

movw $0x0,
int $0x10
retw

%dx

# DH=0 row, DL=0 col


# call BIOS

/* puts( %si) -- display 0-terminated string via putc() */


puts:
/*
* puts() repeatedly loads a byte from the buffer pointed
* to by %si into %al, and displays that byte by calling
* putc( %al), until a \0-byte is encountered. The buffer
* should thus be \0-terminated, like a regular C-string.
*/
lodsb
# Load next byte from %si buffer into %al
cmpb $0x0, %al
# %al == 0?
je
puts1
# Yes: end of string!
callw putc
# No: Display current char
jmp
puts
# Proceed next char
puts1: retw
/* putc( %al) -- output char %al via BIOS call int 10h, func 0Eh */
putc:
/*
* putc( %al) displays the byte %al on the default video
* buffer, using the BIOS function "TELETYPE OUTPUT".
* This function interprets some but not all control
* characters correctly, but it doesnt matter all too
* much in this simple example. This BIOS function is
* only available in real mode.
*/
movw $0x7, %bx
# BH: page 0, BL: attribute 7 (normal white)
movb $0xe, %ah
# BIOS function "TELETYPE OUTPUT"
int
$0x10
# call BIOS
retw

hello.S, which contains the assembly code for the main program.
/* hello.S -- Hello, World on bare metal, just after BIOS boot. x86 */
.file "hello.S"
/*
* A couple of constants.
*
* These cant be changed, because they are set by the
* firmware (BIOS).
*/
.set LOAD,
0x7c00
# BIOS loads and jumps here
.set MAGIC,
0xaa55
# Must be at the end of the 512-byte block
.set BLOCKSIZE, 512
# Boot block is BLOCKSIZE bytes long
/*
* The .text section contains the opcodes (code) for our
* program.
*/
.section .text
# This is a code (text) section.
.code16
# Boot code runs in 16-bit real mode
.globl start
# Entry point is public, for the linker.
start:
/*
* The processor starts in real mode and executes the first
* instruction at address $0xFFFF:FFF0. System designers
* usually map BIOS at this address, so the CPU starts running

Kernel
79 / 94

* BIOS code. The BIOS initializes RAM and other components.


* Then, it loads $BLOCKSIZE bytes from the first boot device
* in RAM, starting at address $0x0:$LOAD.
*
* If that block finishes with the $MAGIC sequence 0x55, 0xaa
* (it is reversed, because IA-32 arch is little endian), BIOS
* considers this block a valid boot block, and jumps right here.
*/
/*
* Initialize segment descriptors %ds, %es, and %ss to 0x0.
* %cs: %ip is already set by the BIOS to 0x0:$LOAD.
*/
xorw %ax, %ax
movw %ax, %es
movw %ax, %ds
movw %ax, %ss
/*
* Initialize the stack.
*
* Since the stack on x86 grows towards *lower* addresses,
* we anchor it at $LOAD. Note that we dont collide with
* the code because the stack will always remain below
* (i.e. less than) $LOAD and grows downwards from there.
*/
movw $LOAD, %sp
/*
* This is the "main" program:
*
* Clear screen, move cursor to the top:left,
* and display a friendly greetings.
*/
callw clrscr
# clear screen
callw curshome
# move cursor home - top:left
callw greeting
# display a greeting string
/*
* Thats all, folks!
*
* We could run a tight loop here, but its better to halt
* the processor. When run on bare metal, a halted processor
* consumes less power (especially useful if ran on battery).
* When run under an emulator, the emulator doesnt consume
* further CPU cycles.
*/
hlt
/* greeting() -- display a little message. */
greeting:
/*
* greeting dislays the string located at label msg,
* using the convenience function puts() defined below.
* We pass the *address* of that string (thus $msg instead
* of msg) in the %si register.
*/
movw $msg, %si
callw puts
retw
/*

Kernel
80 / 94

* Finally, include the BIOS convenience functions used above.


*/
.include "biosfunc.S"
.file
"hello.S"

# BIOS convenience functions.

/* msg: the string buffer to be displayed. */


msg:
.asciz "Hello, World!\r\n"
# must be \0-terminated!
/*
* The boot block MUST end with a MAGIC sequence.
*
* The BIOS checks this, and would refuse to boot unless
* MAGIC is there. The last two bytes of the BLOCKSIZE
* long block must contain the magic sequence 0x55, 0xaa.
* We move the assembler pointer .org there, and emit the
* word MAGIC. Note that MAGIC is set to 0xaa55, and not
* 0x55aa, because the IA-32 platform is little endian.
*/
.org BLOCKSIZE - 2
.word MAGIC

40.3.5.

Compilation

Makefile
# Makefile for baremetal utilities
PROGS
= hello
INCLIBS
= biosfunc.S
RUNTARGET = boot0
all:

$(PROGS) $(INCLIBS)
@echo $(PROGS) built.
@echo now mv SOMEPROG $(RUNTARGET)
@echo then make run, make xrun or make disassemble...

hello: hello.o
ld -N -e start -Ttext 0x7c00 --oformat binary -o hello hello.o
hello.o: hello.S $(INCLIBS)
as -o hello.o hello.S
disassemble: $(RUNTARGET)
objdump --disassemble-all --target=binary --architecture=i8086 $(RUNTARGET)
run: $(RUNTARGET)
@echo qemu will start shortly. Kill it from another console...
qemu -hda ./$(RUNTARGET) -curses
echo back from qemu
xrun: $(RUNTARGET)
qemu -hda ./$(RUNTARGET)
clean:
rm -f *.o a.out $(PROGS) $(RUNTARGET) *~

cp hello boot0 el fichero boot0 es el mdulo ejecutable que utilizan las utilidades:

Kernel
81 / 94

make xrun
make run
make disassemble
40.3.6.

Execution

1. We could copy those 512 bytes to an USB key, to a diskette etc. . . (with something like dd if=hello of=/dev/floppy bs=512
count=1), and boot real hardware.
dd if=hello of=/dev/floppy bs=512 count=1 en dev/floppy debiera estar montado el USB?
2. We could install an 8086 or 80386+ emulator like qemu or VirtualBox on the host machine, and run hello in the emulator.
Emulation
X terminal: qemu-system-x86_64 -hda ./hello o make xrun con boot0
Text console: ctrl-alt-F1 qemu-system-x86_64 -hda ./hello -curses o make run con boot0
para matar el proceso: ctrl-alt-f7 ps aux kill -s KILL pid del proceso qemu-system-x86_64
-hda ./hello -curses
killall -9 qemu-system-x86_64 from another (virtual) console
40.3.7.

Desensamblaje

Fichero objeto reubicable: objdump --disassemble --architecture=i8086 hello


hello.o:

file format elf64-x86-64

Disassembly of section .text:


0000000000000000 <start>:
0:
31 c0
2:
8e c0
4:
8e d8
6:
8e d0
8:
bc 00 7c
b:
e8 0e 00
e:
e8 1c 00
11:
e8 01 00
14:
f4

xor
mov
mov
mov
mov
call
call
call
hlt

%ax, %ax
%ax, %es
%ax, %ds
%ax, %ss
$0x7c00, %sp
1c <clrscr>
2d <curshome>
15 <greeting>

0000000000000015 <greeting>:
15:
be 00 00
18:
e8 1c 00
1b:
c3

mov
call
ret

$0x0, %si
37 <puts>

000000000000001c <clrscr>:
1c:
55
1d:
b4 06
1f:
b0 00
21:
b7 07
23:
b9 00 00
26:
ba 4f 18
29:
cd 10
2b:
5d
2c:
c3

push
mov
mov
mov
mov
mov
int
pop
ret

%bp
$0x6, %ah
$0x0, %al
$0x7, %bh
$0x0, %cx
$0x184f, %dx
$0x10
%bp

000000000000002d <curshome>:
2d:
b4 02

mov

$0x2, %ah

Kernel
82 / 94

2f:
b7 00
31:
ba 00 00
34:
cd 10
36:
c3
000000000000002d <curshome>:
2d:
b4 02
2f:
b7 00
31:
ba 00 00
34:
cd 10
36:
c3

mov
mov
int
ret

$0x0, %bh
$0x0, %dx
$0x10

mov
mov
mov
int
ret

$0x2, %ah
$0x0, %bh
$0x0, %dx
$0x10

0000000000000037 <puts>:
37:
ac
38:
3c 00
3a:
74 05
3c:
e8 03 00
3f:
eb f6

lods
cmp
je
call
jmp

%ds:( %si), %al


$0x0, %al
41 <puts1>
42 <putc>
37 <puts>

0000000000000041 <puts1>:
41:
c3

ret

0000000000000042 <putc>:
42:
bb 07 00
45:
b4 0e
47:
cd 10
49:
c3

mov
mov
int
ret

$0x7, %bx
$0xe, %ah
$0x10

dec
gs
insb
insb
outsw
sub
push
outsw
jb
and
or

%ax
( %dx), %es:( %di)
( %dx), %es:( %di)
%ds:( %si),( %dx)
$0x20, %al
%di
%ds:( %si),( %dx)
c1 <msg+0x77>
%cx, %fs:( %di)
( %bx, %si), %al

push
stos

%bp
%al, %es:( %di)

000000000000004a <msg>:
4a:
48
4b:
65
4c:
6c
4d:
6c
4e:
6f
4f:
2c 20
51:
57
52:
6f
53:
72 6c
55:
64 21 0d
58:
0a 00
...
1fe:
55
1ff:
aa

Fichero ejecutable: objdump --disassemble-all --target=binary --architecture=i8086 hello o make


disassemble con boot0
hello:

file format binary

Disassembly of section .data:


00000000 <.data>:
0:
31 c0
2:
8e c0
4:
8e d8
6:
8e d0
8:
bc 00 7c
b:
e8 0e 00
e:
e8 1c 00
11:
e8 01 00
14:
f4
15:
be 4a 7c

xor
mov
mov
mov
mov
call
call
call
hlt
mov

%ax, %ax
%ax, %es
%ax, %ds
%ax, %ss
$0x7c00, %sp
0x1c
0x2d
0x15
$0x7c4a, %si

Kernel
83 / 94

18:
1b:
1c:
1d:
1f:
21:
23:
26:
29:
2b:
2c:
2d:
2f:
31:
34:
36:
37:
38:
3a:
3c:
3f:
41:
42:
45:
47:
49:
4a:
4b:
4c:
4d:
4e:
4f:
51:
52:
53:
55:
58:
1fe:
1ff:

41.

e8 1c
c3
55
b4 06
b0 00
b7 07
b9 00
ba 4f
cd 10
5d
c3
b4 02
b7 00
ba 00
cd 10
c3
ac
3c 00
74 05
e8 03
eb f6
c3
bb 07
b4 0e
cd 10
c3
48
65
6c
6c
6f
2c 20
57
6f
72 6c
64 21
0a 00
...
55
aa

00

00
18

00

00

00

0d

call
ret
push
mov
mov
mov
mov
mov
int
pop
ret
mov
mov
mov
int
ret
lods
cmp
je
call
jmp
ret
mov
mov
int
ret
dec
gs
insb
insb
outsw
sub
push
outsw
jb
and
or

( %dx), %es:( %di)


( %dx), %es:( %di)
%ds:( %si),( %dx)
$0x20, %al
%di
%ds:( %si),( %dx)
0xc1
%cx, %fs:( %di)
( %bx, %si), %al

push
stos

%bp
%al, %es:( %di)

%bp
$0x6, %ah
$0x0, %al
$0x7, %bh
$0x0, %cx
$0x184f, %dx
$0x10
%bp

-------> BIOS

$0x2, %ah
$0x0, %bh
$0x0, %dx
$0x10
%ds:( %si), %al
$0x0, %al
0x41
0x42
0x37

-------> SEGMENTACION

$0x7, %bx
$0xe, %ah
$0x10
%ax

Tutorial Baremetal: hello world rectangle Bosch

Hello World
rectangle asm in C

42.

0x37

Tutorial Baremetal framebuffer

Real mode: memory map


grub configuration

Kernel
84 / 94

43.

Tutorial BareMetal: O.S. Development Series de Mike (Neptune)

43.1.

Tutorial

:~/tutoriales/kernel/brokenthorn_baremetal$
43.1.1.

Problemas

Ver apuntes del Emulador Bochs

43.2.

Referencia

http://www.brokenthorn.com/Resources/OSDevIndex.html

43.3.

Preface

El Objetivo es ensear los conceptos de la Arquitectura de una Computadora PC de un modo prctico: disear un sistema
BareMetal de 32 bits programando un kernel casero con los lenguajes ensamblador y C. En la narrativa habla del sistema
operativo casero Neptune que se puede pedir mandando un email.
Lenguajes de programacin
ensamblador de intel 32 bits con NASM assembler
C: I will be using Microsoft Visual C++ for developing the system. However, it is also possible to develop in other compilers
such as DJGPP, GCC
In the series, we will be creating a 32 bit operating system. Because of this, we will be using a 32 bit C compiler.
CPU
x86
ISA 32 bits
43.3.1.

C and executable formats

BIOS BootLoader (flat binary program): bios carga el bootloader que est localizado en el boot sector.
El compilador de C no soporta como salida un flat binary y por ello es necesario el lenguaje ensamblador.
El bootloader est dividido en stages y el stage1 se llame Boot Code que estar en lenguaje asm.
Se puede utilizar C para el bootloader
Opcin 1: el stage1 est en asm y carga un fichero donde estn enlazados dos mdulos objeto: un mdulo stub en asm y el
otro mdulo en C.
43.3.2.

kernel

Esta escrito en C

Kernel
85 / 94

43.3.3.

physical address space

Direcciones que pueden ser utilizadas, excluyendo las no permitidas. El espacio es diferente para las aplicaciones o para el
kernel. Por ejemplo la direccin 0 es la primera entrada de la tabla de vectores de interrupcin (IVT), que est excluida del
espacio de direcciones para las aplicaciones. Si una aplicacin intenta acceder a la direccin cero el compilador lo indicar
diciendo que se intenta violar un segmento.
En el caso del kernel puede haber direcciones del physical address space que no existan en memoria. Se puede leer o escribir
de ests direcciones sin memoria pero su resultado ser imprevisto.
43.3.4.

Dynamic Memory Allocation

43.3.5.

Inline Assembly

43.3.6.

C standard library

Como la librera standard utiliza llamadas al sistema, estas rutinas no son vlidas para la programacin de sistemas.
Ser necesario programar una librera propia.
43.3.7.

C Run Time Library (RTL)

El compilador inserta en el cdigo ejecutable llamadas a rutinas que tienen en cuenta el Entorno del Sistema, por ejemplo
servicios de interrupcin, depuracin, operaciones complejas que no puede realizar la propia CPU, etc . . . Esta rutinas forman
parte de la RTL.
Ser necesario implementar una RTL propia.
43.3.8.

Debugging

The series uses (and explains) how to use the Bochs Debugger, which is a debugger that comes with the Bochs emulator.

43.4.

Introduction

43.4.1.

Resources

asm resources: nasm


C resources: microsoft visual

43.5.

The Build Process

There are a lot of tools listed above. To better understand how they can be useful, we should take a look at the entire build process
of the OS.

Setting everything up
Use VFD to create and format a virtual floppy image to use.
Set up Bochs Emulator to boot from the floppy image.
The bootloader
Assemble the bootloader with NASM to create a flat binary program. : nasm -f bin boot2.
Use PartCopy or the DEBUG command to copy the bootloader to the bootsector of the virtu
The Kernel (And basically all other programs)
Assembly and/or compile all sources into an object format (Such as ELF or PE) that can
Copy kernel into floppy disk using Windows Explorer.
Test it!
Using Bochs emulator and debugger, using a real floppy disk, or by using MagicISO to cr

Kernel
86 / 94

43.5.1.

VFD - Virtual Floppy Drive

VFD es de Windows
43.5.2.

Floppy Image on linux

Crear una floppy image: http://www.legroom.net/2010/06/05/create-floppy-disk-images-within-linux


Dosfstools:
mkfs.vfat -v -F 12 -f 2 -n candido -C "floppy.img" 1440 - -F 12 indica FAT12, -f el nmero
de tablas y 1440 es el nmero de bloques (?de 1 K)
mkfs.vfat 3.0.12 (29 Oct 2011)
floppy.img has 2 heads and 18 sectors per track,
logical sector size is 512,
using 0xf0 media descriptor, with 2880 sectors;
file system has 2 12-bit FATs and 1 sector per cluster. ---> File Allocation Table de
12 bits -> FAT12
FAT size is 9 sectors, and provides 2847 clusters.
There is 1 reserved sector.
Root directory contains 224 slots and uses 14 sectors.
Volume ID is 82d05ae3, volume label candido
.

file floppy.img - floppy.img: DOS floppy 1440k, x86 hard disk boot sector
vuelco el contenido binario del floppy con emacs hexl-mode
00000000: eb3c 906d 6b64 6f73 6673 0000 0201 0100 .<.mkdosfs......
00000010: 02e0 0040 0bf0 0900 1200 0200 0000 0000 ...@............
00000020: 0000 0000 0000 29e3 5ad0 8263 616e 6469 ......).Z..candi
00000030: 646f 2020 2020 4641 5431 3220 2020 0e1f do
FAT12
..
00000040: be5b 7cac 22c0 740b 56b4 0ebb 0700 cd10 .[|.".t.V.......
00000050: 5eeb f032 e4cd 16cd 19eb fe54 6869 7320 ^..2.......This
00000060: 6973 206e 6f74 2061 2062 6f6f 7461 626c is not a bootabl
00000070: 6520 6469 736b 2e20 2050 6c65 6173 6520 e disk. Please
00000080: 696e 7365 7274 2061 2062 6f6f 7461 626c insert a bootabl
00000090: 6520 666c 6f70 7079 2061 6e64 0d0a 7072 e floppy and..pr
000000a0: 6573 7320 616e 7920 6b65 7920 746f 2074 ess any key to t
000000b0: 7279 2061 6761 696e 202e 2e2e 200d 0a00 ry again ... ...
000000c0: 0000 0000 0000 0000 0000 0000 0000 0000 ................
 Observo que es NOT bootable DISK
sudo mount -o loop,uid=$UID -t vfat floppy.img /mnt/floppy
Tengo montado el floppy en /dev/loop0, compruebo que el proximo loop es loop1 con losetup -f
Formatos FAT
http://technet.microsoft.com/en-us/library/cc750354.aspx: vfat es una extensin de fat
http://bochs.sourceforge.net/doc/docbook/user/loop-device-usage.html
Using Floppy images is easy, because there is no partition table:
losetup /dev/loop0 /usr/local/bochs/dlxlinux/floppya.img
pseudodispositivo

-> enlaza la imagen con el

Now you can use the image like a real floppy:


- format
: mkfs.vfat /dev/loop0
-> lo formatea
- filesystem check : fsck.vfat /dev/loop0
-> lo chequea
- mount
: mount /dev/loop0 -o loop /mnt/floppy -> lo monta para acceder
a l

Kernel
87 / 94

Before you want to restart bochs you must do this:


losetup -d /dev/loop0

-> delete loop

Dont forget to umount before.

43.5.3.

NASM

Bootloader Source Code


;*********************************************
;
Boot1.asm
;
- A Simple Bootloader
;
;
Operating Systems Development Tutorial
;*********************************************
org
0x7c00
bits
16
Start:
cli
hlt
times 510 - ($-$$) db 0
of the bytes with 0
dw 0xAA55

; We are loaded by BIOS at 0x7C00


; We are still in 16 bit Real Mode
; Clear all Interrupts
; halt the system
; We have to be 512 bytes. Clear the rest

; Boot Signiture

the first sector of the boot disk (the bootloader) is loaded at address 0x07c0:0000 (0x7c00 in real addressing mode) and control
jumps to that address.
Bootloader binary flat: nasm -f bin boot1.asm -o boot1.bin
43.5.4.

Copying the Boot Loader

The bootloader is a pure binary program that is stored in a single 512 byte sector
PartCopy - Low Level Disk Copier: formato exe para windows
Windows debugger : se puede utilizar para realizar la copia en un sector determinado.
dd if=boot1.bin of=/dev/loop0 : para ello tengo que tener creada la imagen del floppy, montarla y asociarla a un
pseudodispositivo
43.5.5.

Test del floppy

Estando la imagen montada.


file floppy.img floppy.img: DOS floppy 1440k, x86 hard disk boot sector .
Estando la imagen desmontada
file floppy.img floppy.img: x86 boot sector, code offset 0xf4
x86 boot sector : ha encontrado la firma
offset 0xf4 es en decimal 244 qu significa?
Compruebo que en el floppy est el cdigo flat del bootloader (512bytes)

Kernel
88 / 94

43.5.6.

Bochs Emulator

edito el fichero bochs.conf en mi carpeta:


http://bochs.sourceforge.net/doc/docbook/user/rom-images.html
ojo que la bios BIOS-bochs-latest ocupa 128KB y por lo tanto empieza en 0xe0000 para terminar en 0xfffff. 0xfffff es la
direccin del primer MB. ROM: System BIOS must end at 0xfffff. Si el tamao de la Bios es 128K hay que cargar la bios
en 0xfffff-0x10000=0xe0000
indico el path completo de romimage y vgaromimage
el floppy est en /dev/loop0
# ROM and VGA BIOS images --------------------------------------------romimage:
file=/usr/local/share/bochs/BIOS-bochs-latest, address=0xe0000
vgaromimage: file=/usr/local/share/bochs/VGABIOS-lgpl-latest
# boot from floppy using our disk image ------------------------------floppya: 1_44=/dev/loop0:, status=inserted

# Boot from drive A

# logging and reporting ----------------------------------------------log:


error:
info:

OSDev.log
action=report
action=report

# All errors and info logs will output to OSDev.log

bochs -f bochs.conf -q
error ya que no sale ningn mensaje en la pantalla.
43.5.7.

Error

Da el mismo resultado que si no conecto el floppy donde est el cdigo del bootloader, por lo que hay que investigar porque la bios no carga el bootloader almacenado en el diskette. Investigamos la configuracin floppya: 1_44=/dev/loop0:, status=inserted # Boot from drive A del fichero bochsrc:
Est conectado el floppy virtual a la mquina virtual o lo hemos dejado conectado al host? 1_44=/dev/loop0 especifica que
estar conectado al host. En el original de windows la configuracin es 1_44=a donde a NO ES UN dispositivo real ya que
en el original mediante la herramienta VFD se ha creado el floppy virtual a.
Al final descubro que es un problema del video ya que unas veces salen los mensajes de la bios y otros no
43.5.8.

boot2.asm

Incluye los parmtetros BPB


43.5.9.

BIOS Parameter Block(BPB) (OEM Parameter)

http://www.ntfs.com/fat-partition-sector.htm
http://www.win.tue.nl/~aeb/linux/lk/lk-7.html
The first sector (512 bytes) of a FAT filesystem is the boot sector. In Unix-like terminology this would be called the superblock. It contains some general information.
FAT12 BPB:

Kernel
89 / 94

FAT16 BPB:
FAT16
Bytes
0-2

24-25
26-27

Content
Jump to bootstrap (E.g. eb 3c 90; on i86: JMP 003E NOP.
One finds either eb xx 90, or e9 xx xx.
The position of the bootstrap varies.)
OEM name/version (E.g. "IBM 3.3", "MSDOS5.0", "MSWIN4.0".
Various format utilities leave their own name, like "CH-FOR18".
Sometimes just garbage. Microsoft recommends "MSWIN4.1".)
/* BIOS Parameter Block starts here */
Number of bytes per sector (512)
Must be one of 512, 1024, 2048, 4096.
Number of sectors per cluster (1)
Must be one of 1, 2, 4, 8, 16, 32, 64, 128.
A cluster should have at most 32768 bytes. In rare cases 65536 is OK.
Number of reserved sectors (1)
FAT12 and FAT16 use 1. FAT32 uses 32.
Number of FAT copies (2)
Number of root directory entries (224)
0 for FAT32. 512 is recommended for FAT16.
Total number of sectors in the filesystem (2880)
(in case the partition is not FAT32 and smaller than 32 MB)
Media descriptor type (f0: 1.4 MB floppy, f8: hard disk; see below)
Number of sectors per FAT (9)
0 for FAT32.
Number of sectors per track (12)
Number of heads (2, for a double-sided diskette)

11-27
28-31
32-35

0xb-0xfb
fc-1f
20-23

36
37

24
25

38

26

39-42
43-53
54-61
62-509
510-511

27-2a
2b-35
36-3d
3e-1fd
1fe-1ff

3-10

11-12
13

14-15
16
17-18
19-20
21
22-23

(as before)
Number of hidden sectors (0)
Total number of sectors in the filesystem
(in case the total was not given in bytes 19-20)
Logical Drive Number (for use with INT 13, e.g. 0 or 0x80)
Reserved (Earlier: Current Head, the track containing the Boot Re
Used by Windows NT: bit 0: need disk check; bit 1: need surface s
Extended signature (0x29)
Indicates that the three following fields are present.
Serial number of partition
Volume label or "NO NAME
"
Filesystem type (E.g. "FAT12
", "FAT16
", "FAT
", or all
Bootstrap
Signature 55 aa

Boot Binario boot1.bin propio creado para el arranque de nuestra sistema emulado.
00000000:
00000010:
00000020:
00000030:
00000040:
00000050:
00000060:

eb68
02e0
0000
4c4f
6c63
6174
c074

0000
0040
0000
5050
6f6d
696e
06b4

0000
0bf0
0000
5920
6520
6720
0ecd

0000
0900
29a3
4641
746f
5379
10eb

0000
1200
a2a1
5431
204d
7374
f5c3

0000
0200
a04d
3220
7920
656d
31c0

0201
0000
4f53
2020
4f70
2100
8ed8

0100
0000
2046
5765
6572
ac08
8ec0

.h..............
...@............
......)....MOS F
LOPPY FAT12
We
lcome to My Oper
ating System!...
.t........1.....

Kernel
90 / 94

00000070: be3e 7ce8 e8ff faf4 0000 0000 0062 6f6f


00000080: 0000 0000 0000 0000 0000 0000 0000 0000
******************************************
000001e0: 0000 0000 0000 0000 0000 0000 0000 0000
000001f0: 0000 0000 0000 0000 0000 0000 0000 55aa

.>|..........boo
................
................
..............U.

Leo la BIOS que tengo instalada en mi porttil teniendo en cuenta que el sistema de ficheros es NTFS y el dispositivo de
arranque el disco duro.
sudo dd if=/dev/mem of=bios.bin bs=65536 skip=15 count=1
emacs bios.bin hexl-mode copio los bytes de posiciones 0x00-0x3f
00000000:
00000010:
00000020:
00000030:

4177
4946
00f0
0000

6172
4524
6008
c0b4

6420
9856
18ef
0f00

5669
0200
d9da
9001

7374
0009
0000
0000

6100
0000
0000
60b1

0000
00f0
e000
0f00

0000
aa00
0f00
b001

Award Vista.....
IFE$.V..........

http://technet.microsoft.com/en-us/library/cc977221.aspx: conceptos e info buena para el fat y para el ntfs, bios parameter
BPB
http://en.wikipedia.org/wiki/FAT_BPB#BPB: info buena
http://homepage.ntlworld.com/jonathan.deboynepollard/FGA/bios-parameter-block.html:
Windows NT (a.k.a. version 8.0) BPBs : The NTFS filesystem format on Windows NT
http://www.ntfs.com/ntfs.htm: Ver tambin forensics o sistemas de ficheros. Solo est bien para el fat32

43.6.

Basic Theory and History

44.

Websofia BareMetal: Writing your own toy operating system

http://www.websofia.com/writing-your-own-toy-operating-system/
lo he probado en la carpeta de tutoriales y no me sale porque no tengo bien configurado bochs.
REPETIRLOOOOOOOOOOOOOOOOOOOOO

45.

Princeton BareMetal

46.

TUTORIAL PERSONAL PRIMER

libro de oreilly linux kernel nutshell

Kernel
91 / 94

46.1.

Descargar el source kernel

Referencia http://docs.slackware.com/howtos:slackware_admin:building_the_linux_kernel_using_git_repository
dos mtodos: el git y la descarga directa del tarball. Hacemos el git.
git clone --depth 1 git://git.kernel.org/pub/scm/linux/kernel/git/stable/linux-stable.git
git pull
git checkout v3.2.59 eligo esa versin porque es la long term que utiliza ubuntu
git log compruebo que es la versin especificada en git checkout
git tag -v v3.2.59 compruebo la firma
gpg: Signature made Sunday 18 May 2014 03:58:11 PM CEST using RSA key ID 95861109
gpg: Cant check signature: public key not found
Importo la firma segn https://www.kernel.org/category/signatures.html
gpg --recv-keys 95861109
git tag -v v3.2.59 gpg: Good signature from "Ben Hutchings (DOB: 1977-01-11)"

46.2.

Anlisis de los fuentes

ls -l /home/candido/git_repos/linux-stable/arch
x86, x86_64, arm, mips, etc
ls -l /home/candido/git_repos/linux-stable/arch/mips/kernel
ls -l /home/candido/git_repos/linux-stable/arch/boot/kernel

46.3.

preBuild

make clean
make mrproper elimina .config y otros restos.

46.4.

tools: kconfig, makefile, config.

referencia: http://oreilly.com/linux/excerpts/9780596100797/kernel-build-command-line-reference.html
Linux Kernel Build System
config symbols
opciones de compilacin para decidir cuales sern los objetos empotrados en el ncleo y cuales sern los mdulos generados.
Kconfig files
Definen los config smbolos y sus atributos. Este fichero servir al menuconfig para definir las entradas de los mens
despegables
.config file
Es el fichero de salida que contiene los valores de los parmetros definidos en Kconfig. Este fichero puede generarse
automaticamente con menuconfig, oldconfig, etc
Makefile
relacin entre los fuentes para generar la imagen del ncleo y sus mdulos.

Kernel
92 / 94

46.5.

Configuration

Referencias
README
Documentation/kbuild/kconfig.txt
Copio una configuracin que ya tengo: cp /boot/config-3.2.0-59-generic .config aunque no es la del kernel
del host ls -l /boot/config-uname -r
make oldconfig
candido@lur:~/git_repos/linux-stable$ make oldconfig
HOSTCC scripts/basic/fixdep
HOSTCC scripts/kconfig/conf.o
SHIPPED scripts/kconfig/zconf.tab.c
SHIPPED scripts/kconfig/zconf.lex.c
SHIPPED scripts/kconfig/zconf.hash.c
HOSTCC scripts/kconfig/zconf.tab.o
HOSTLD scripts/kconfig/conf
scripts/kconfig/conf --oldconfig Kconfig
.config:1021:warning: symbol value m invalid for NET_DSA
.config:2029:warning: symbol value m invalid for NET_DSA_MV88E6XXX
.config:2030:warning: symbol value m invalid for NET_DSA_MV88E6060
.config:2032:warning: symbol value m invalid for NET_DSA_MV88E6131
.config:2033:warning: symbol value m invalid for NET_DSA_MV88E6123_61_65
.config:4128:warning: symbol value m invalid for FB_VESA
*
* Restart config...
*
*
* Distributed Switch Architecture support
*
Distributed Switch Architecture support (NET_DSA) [N/y/?] (NEW) N
Support for frame buffer devices (FB) [Y/m/?] y
Quanta Optical Touch panels (HID_QUANTA) [N/m/?] (NEW) y
Quanta Optical Touch panels (HID_QUANTA) [N/m/?] (NEW) N

46.6.

Build core vmlinux image and their modules

make -j 4 - utilizo la opcin --jobs y el nmero de ncleos de mi cpu Tarda ms de 30 minutos en generar el Makefile
y compilar los fuentes.
make modules
WARNING: modpost: Found 4 section mismatch(es)
To see full details build your kernel with:
make CONFIG_DEBUG_SECTION_MISMATCH=y

sudo make modules_install ------------ NOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO


ls -l /lib/modules/3.2.59/kernel/arch/x86/kernel/cpu - instala en el file system local
Before installing the kernel, you may want to uninstall Slackware packages containing the default kernels, modules, and
source.

Kernel
93 / 94

46.7.

Anlisis del ncleo vmlinux generado y sus mdulos

$ ls -lh vmlinux : -rwxrwxr-x 1 candido candido 142M May 24 10:33 vmlinux 142MB
$ readelf -h vmlinux
ELF Header:
Magic:
7f 45 4c 46 02 01 01 00 00 00 00 00 00 00 00 00
Class:
ELF64
Data:
2s complement, little endian
Version:
1 (current)
OS/ABI:
UNIX - System V
ABI Version:
0
Type:
EXEC (Executable file)
Machine:
Advanced Micro Devices X86-64
Version:
0x1
Entry point address:
0x1000000
Start of program headers:
64 (bytes into file)
Start of section headers:
144824872 (bytes into file)
Flags:
0x0
Size of this header:
64 (bytes)
Size of program headers:
56 (bytes)
Number of program headers:
5
Size of section headers:
64 (bytes)
Number of section headers:
47
Section header string table index: 44

imagen comprimida
$ ls -l /home/candido/git_repos/linux-stable/arch/x86/boot/bzImage
-rw-rw-r-- 1 candido candido 4905968 May 24 10:33 /home/candido/git_repos/linux-stable/ arch/x86/boot/bzImage

mdulos ko
find . -name *.ko
CONTINUAR CON
http://en.wikipedia.org/wiki/Vmlinux. ver links initrd,etc
http://oss.sgi.com/LDP/HOWTO/Kernel-HOWTO/index.html
http://oss.sgi.com/LDP/HOWTO/Kernel-HOWTO/kernel_files_info.html
libro oreilly nutshell, captulo 5
manuales oficiales https://www.kernel.org/doc/Documentation/
howto
https://www.kernel.org/doc/Documentation/kbuild/modules.txt
hay que ejecutar sudo make modules y sudo make modules_install?
http://www.linux.org/threads/the-linux-kernel-compiling-and-installing.5208/
http://sopa.dis.ulpgc.es/ii-aso/portal_aso/practicas/compilar.htm

46.8.
make
make
make
make
make

Resumen de comandos
mrproper
menuconfig
dep
clean
bzImage

Kernel
94 / 94

make modules
make modules_install
cp arch/i386/boot/bzImage /boot/vmlinuz-2.4.19
cp System.map /boot

46.9.

eclipse & source code

http://wiki.eclipse.org/HowTo_use_the_CDT_to_navigate_Linux_kernel_source

46.10.

compile & debug & qemu & eclipse

http://wiki.eclipse.org/HowTo_use_the_CDT_to_navigate_Linux_kernel_source
http://www.yonch.com/tech/84-debugging-the-linux-kernel-with-qemu-and-eclipse
http://www.opensourceforu.com/2011/02/kernel-development-debugging-using-eclipse/
http://issaris.blogspot.com.es/2007/12/download-linux-kernel-sourcecode-from.html

47.

Glosario

Glosario

Potrebbero piacerti anche