9 Intermediate Memory Topics
How a Computer Views Memory
Let's review how memory within a computer works. You may also want to re-read Chapter 2. Computer Architecture.
A computer looks at memory as a long sequence of numbered storage locations. A sequence of millions of numbered storage locations. Everything is stored in these locations. Your programs are stored there, your data is stored there, everything. Each storage location looks like every other one. The locations holding your program are just like the ones holding your data. In fact, the computer has no idea which are which, except that the executable file tells it where to start executing.
These storage locations are called bytes. The computer can combine up to four of them together into a single word. Normally numeric data is operated on a word at a time. As we mentioned, instructions are also stored in this same memory. Each instruction is a different length. Most instructions take up one or two storage locations for the instruction itself, and then storage locations for the instruction's arguments. For example, the instruction:
movl data_items(,%edi,4), %ebxTakes up 7 storage locations. The first two hold the instruction, the third one tells which registers to use, and the next four hold the storage location of data_items. In memory, instructions look just like all the other numbers, and the instructions themselves can be moved into and out of registers just like numbers, because that's what they are.
This chapter is focused on the details of computer memory. To get started let's review some basic terms that we will be using in this chapter:
- Byte:
-
This is the size of a storage location. On x86 processors, a byte can hold numbers between 0 and 255.
- Word:
-
This is the size of a normal register. On x86 processors, a word is four bytes long. Most computer operations handle a word at a time.
- Address:
-
An address is a number that refers to a byte in memory. For example, the first byte on a computer has an address of 0, the second has an address of 1, and so on.1 Every piece of data on the computer not in a register has an address. The address of data which spans several bytes is the same as the address of its first byte.
Normally, we don't ever type the numeric address of anything, but we let the assembler do it for us. When we use labels in code, the symbol used in the label will be equivalent to the address it is labelling. The assembler will then replace that symbol with its address wherever you use it in your program. For example, say you have the following code:
Now, any time in the program that
my_datais used, it will be replaced by the address of the first value of the.longdirective.
.section .data
my_data:
.long 2, 3, 4- Pointer:
-
A pointer is a register or memory word whose value is an address. In our programs we use
%ebpas a pointer to the current stack frame. All base pointer addressing involves pointers. Programming uses a lot of pointers, so it's an important concept to grasp.
The Memory Layout of a Linux Program
When your program is loaded into memory, each .section is loaded into its own region of memory. All of the code and data declared in each section is brought together, even if they were separated in your source code.
The actual instructions (the .text section) are loaded at the address 0x08048000 (numbers starting with 0x are in hexadecimal, which will be discussed in Chapter 10. Counting Like a Computer ).2 The .data section is loaded immediately after that, followed by the .bss section.
The last byte that can be addressed on Linux is location 0xbfffffff. Linux starts the stack here and grows it downward toward the other sections. Between them is a huge gap. The initial layout of the stack is as follows: At the bottom of the stack (the bottom of the stack is the top address of memory - see Chapter 4. All About Functions), there is a word of memory that is zero. After that comes the null-terminated name of the program using ASCII characters. After the program name comes the program's environment variables (these are not important to us in this book). Then come the program's command-line arguments. These are the values that the user typed in on the command line to run this program. When we run as, for example, we give it several arguments - as, sourcefile.s, -o, and objectfile.o. After these, we have the number of arguments that were used. When the program begins, this is where the stack pointer, %esp, is pointing. Further pushes on the stack move %esp down in memory. For example, the instruction:
pushl %eaxis equivalent to
movl %eax, (%esp)
subl $4, %espLikewise, the instruction:
popl %eaxis the same as
movl (%esp), %eax
addl $4, %espYour program's data region starts at the bottom of memory and goes up. The stack starts at the top of memory, and moves downward with each push. This middle part between the stack and your program's data sections is inaccessible memory - you are not allowed to access it until you tell the kernel that you need it.3 If you try, you will get an error (the error message is usually "segmentation fault"). The same will happen if you try to access data before the beginning of your program, 0x08048000. The last accessible memory address to your program is called the system break (also called the current break or just the break).
Every Memory Address is a Lie
So, why does the computer not allow you to access memory in the break area? To answer this question, we will have to delve into the depths of how your computer really handles memory.
You may have wondered, since every program gets loaded into the same place in memory, don't they step on each other, or overwrite each other? It would seem so. However, as a program writer, you only access virtual memory.
Physical memory refers to the actual RAM chips inside your computer and what they contain. It's usually between 16 and 512 Megabytes on modern computers. If we talk about a physical memory address, we are talking about where exactly on these chips a piece of memory is located. Virtual memory is the way your program thinks about memory. Before loading your program, Linux finds an empty physical memory space large enough to fit your program, and then tells the processor to pretend that this memory is actually at the address 0x0804800 to load your program into. Confused yet? Let me explain further.
Each program gets its own sandbox to play in. Every program running on your computer thinks that it was loaded at memory address 0x0804800, and that its stack starts at 0xbffffff. When Linux loads a program, it finds a section of unused memory, and then tells the processor to use that section of memory as the address 0x0804800 for this program. The address that a program believes it uses is called the virtual address, while the actual address on the chips that it refers to is called the physical address. The process of assigning virtual addresses to physical addresses is called mapping.
Earlier we talked about the inaccessible memory between the .bss and the stack, but we didn't talk about why it was there. The reason is that this region of virtual memory addresses hasn't been mapped onto physical memory addresses. The mapping process takes up considerable time and space, so if every possible virtual address of every possible program were mapped, you would not have enough physical memory to even run one program. So, the break is the beginning of the area that contains unmapped memory. With the stack, however, Linux will automatically map in memory that is accessed from stack pushes.
Let's explain these complex concepts using the Linux tools and dynamic practices. The program 009-01-memory-layout.s helps with this:
# Assemble with `as --32` and `ld -m elf_i386`.
#
.include "006-01-linux.s" # Linux Definitions.
# PURPOSE:
# Represent the memory layout.
#
.section .data
name:
.ascii "Leo\0"
age:
.int 31
id:
.long 89485
.section .bss
.lcomm comment, 128
.lcomm author, 3
.equ items, 5
.section .text
.globl _start
_start:
movl $SYS_BRK, %eax
movl $0, %ebx
int $LINUX_SYSCALL # Find out the break.
call _hello
call _fine
jmp _bye
_hello:
pushl %ebp # Save old base pointer.
movl %esp, %ebp # Make ST the BP.
pushl %eax
movl $name, %eax
popl %eax
movl %ebp, %esp # Restore the ST.
popl %ebp # Restore the BP.
ret
_fine:
pushl %ebp # Save old base pointer.
movl %esp, %ebp # Make ST the BP.
subl $12, %esp # Add local space for
# variables.
# Using %ebp, needs negative numbers.
movl $age, 4(%esp) # Store at 1st space.
movl $author, -8(%ebp) # Store at 1rd space.
movl $id, 8(%esp) # Store at 2nd space.
movl $comment, -4(%ebp) # Store at 2nd space.
# Remember the rule: Positive numbers
# or operations take old stored values,
# negative numbers or operations take
# the new stored values.
pushl age # Push the age.
popl %eax # Remove the age.
addl $12, %esp # Remove local variables.
# It is not necessary since the next
# instrucition restore the %esp from
# the %ebp.
movl %ebp, %esp # Restore the ST.
popl %ebp # Restore the BP.
ret
_bye:
movl $SYS_EXIT, %eax
movl $0, %ebx
int $LINUX_SYSCALLTime to assemble and link:
as -o 009-01-memory-layout.o --32 \
--gstabs+ \
009-01-memory-layout.s
ld -o 009-01-memory-layout -m elf_i386 \
009-01-memory-layoutHow to get the beginning of the memory address (0x08048000)? Search the private headers:
objdump 009-01-memory-layout --private-headersIt shows the LOAD off 0x00000000 vaddr 0x08048000:
Program Header:
LOAD off 0x00000000 vaddr 0x08048000 paddr 0x08048000 align 2**12
filesz 0x00000094 memsz 0x00000094 flags r--
LOAD off 0x00001000 vaddr 0x08049000 paddr 0x08049000 align 2**12
filesz 0x00000022 memsz 0x00000022 flags r-x
LOAD off 0x00002000 vaddr 0x0804a000 paddr 0x0804a000 align 2**12
filesz 0x0000000c memsz 0x0000000c flags rw-
The symbols are the sections, variables, constants, labels, functions, and more. These are inside of the binary file:
objdump 009-01-memory-layout --symsSYMBOL TABLE:
08049000 l d .text 00000000 .text
0804a000 l d .data 00000000 .data
0804a010 l d .bss 00000000 .bss
0804a000 l .data 00000000 name
0804a004 l .data 00000000 age
0804a008 l .data 00000000 id
0804a010 l O .bss 00000080 comment
0804a090 l O .bss 00000003 author
00000005 l *ABS* 00000000 items
08049017 l .text 00000000 _hello
08049026 l .text 00000000 _fine
08049039 l .text 00000000 _bye
08049000 g .text 00000000 _start
Get the overall file header, it contains the start address:
objdump 009-01-memory-layout --file-headersarchitecture: i386, flags 0x00000112:
EXEC_P, HAS_SYMS, D_PAGED
start address 0x08049000
In gdb we are able to get this information, too:
gdb --args ./009-01-memory-layout 123 456
(gdb) info filesEntry point: 0x8049000
0x08049000 - 0x080490b5 is .text
0x0804a000 - 0x0804a00c is .data
0x0804a010 - 0x0804a094 is .bss
Table of the Physical Memory in the program.
As we mentioned in this and other chapters the code is going forward starting at memory 0x08048000 but the dynamic data is pushing backwards from the bottom of the memory 0xffffffff.
./009-01-memory-layout 123 456
+-------------------+ ---> 0x08048000
| Program Code |
| and Data |
| ↓ |
+-------------------+
| .text | ---> 0x08049000
| <_start> | ---> 0x08049000 movl $1, %eax
| <_start+5> | ---> 0x08049005 calll _hello <_hello>
| <_start+10> | ---> 0x0804900a pushl age <0x804a004>
| <_start+16> | ---> 0x08049010 calll _fine <_fine>
| ↓ |
+-------------------+
| .data | ---> 0x0804a000
| name | ---> 0x0804a000
| age | ---> 0x0804a004
| id | ---> 0x0804a008
| ↓ |
+-------------------+
| .bss | ---> 0x0804a010
| comment | ---> 0x0804a010
| author | ---> 0x0804a090
| ↓ |
+-------------------+ ---> 0x804b000 *** Break
| ↓ |
| |
| Unmapped Memory |
| |
| ↑ | ---> New pushes (pushl)
+-------------------+
| # of arguments | ---> 0xffffd870
+-------------------+
| Program name | ---> 0xffffd874
+-------------------+
| Arg #1 | ---> 0xffffd878
+-------------------+
| Arg #2 | ---> 0xffffd87c
+-------------------+
| ... ↑ ... |
+-------------------+
| ↑ |
| Environment |
| variables |
+-------------------+ ---> 0xffffffff
Try to upside down the previous table to read from the memory stack during the execution of the first function _hello. This is the confused part because when we try to take the values from the base pointer (%ebp) or stack pointer (%esp) we need to add or sub in the inverse way that we are thinking, the reason is here:
TIP:
Taking old variables pushed in the stack needs to use positive numbers, the new variables pushed in the stack needs to use the negative numbers. Because the positive numbers are going to the bottom of the memory 0xffffffff, means it’s going backwards.
pushl %ebp # Save old base pointer. movl %esp, %ebp # Make ST the BP. subl $12, %ebp # Reserve 3 new local variables. movl %eax, 8(%esp) # Store in the new 2nd variable. movl %eax, -4(%ebp) # Store in the new 2nd variable.
It shows how to the stack memory is decreasing when we call or push values, and decreasing when use pop or ret:
./009-01-memory-layout 123 456
+-------------------+ ---> 0xffffffff
| Environment |
| variables |
| ↓ |
+-------------------+
| Program name | ---> 0xffffd874
+-------------------+
| # of arguments | ---> 0xffffd870
| ↓ |
+-------------------+ ---> 0xffffd870 -> %esp
| |
| _start+17 | > call _hello
| ↓ | ---> 0xffffd86c -> %esp
+-------------------+
| %ebp | > pushl %ebp
| ↓ | ---> 0xffffd868 -> %esp
| | > movl %esp, %ebp
| | ---> 0xffffd868 -> %ebp %esp
+-------------------+
| %eax | > pushl %eax
| ↓ | ---> 0xffffd864 -> %esp
+-------------------+
| %eax | > popl %eax
| ↑ | ---> 0xffffd868 -> %ebp %esp
+-------------------+
| | > movl %ebp, %esp
| | ---> 0xffffd868 -> %ebp %esp
| %ebp | > popl %ebp
| ↑ | ---> 0xffffd86c -> %esp
+-------------------+
| ret | > ret
| ↑ | ---> 0xffffd870 -> %esp
| |
+-------------------+ ---> 0x804b000 *** Break
| ↓ |
| Unmapped Memory |
| ↑ |
+-------------------+
| ↑ |
| Code and Data |
+-------------------+
The memory address is decreasing when push and call is executed:
0xffffd870 -> %esp
0xffffd86c -> %esp
0xffffd868 -> %ebp %esp
0xffffd864 -> %esp
It's increasing when pop and ret is executed:
0xffffd868 -> %ebp %esp
0xffffd86c -> %esp
0xffffd870 -> %esp
Now, checks the next example with the function _fine, it adds new local variables. This example also demonstrates that using %esp or %ebp are the same because at the end it's a mark which indicate the positions, one for the base pointer and other for the stack pointer. Highly recommended to use %esp because the program is dynamic and it goes inside of the calls. We want to use the recently created spaces for these variables, %ebp is recommended when you want to take arguments of the actual function, they always be around the base pointer:
_fine:
pushl %ebp # Save old base pointer.
movl %esp, %ebp # Make ST the BP.
subl $12, %esp # Add local space for
# variables.
# Using %ebp, needs negative numbers.
movl $age, 4(%esp) # Store at 1st space.
movl $author, -8(%ebp) # Store at 1rd space.
movl $id, 8(%esp) # Store at 2nd space.
movl $comment, -4(%ebp) # Store at 2nd space.
# Remember the rule: Positive numbers
# or operations take old stored values,
# negative numbers or operations take
# the new stored values.
pushl age # Push the age.
popl %eax # Remove the age.
addl $12, %esp # Remove local variables.
# It is not necessary since the next
# instrucition restore the %esp from
# the %ebp.
movl %ebp, %esp # Restore the ST.
popl %ebp # Restore the BP.
ret./009-01-memory-layout 123 456
+-------------------+ ---> 0xffffffff
| Environment |
| variables |
| ↓ |
+-------------------+
| Program name | ---> 0xffffd874
+-------------------+
| # of arguments | ---> 0xffffd870
| ↓ |
+-------------------+ ---> 0xffffd870 -> %esp
| |
| _start+22 | > call _fine
| ↓ | ---> 0xffffd86c -> %esp
+-------------------+
| %ebp | > pushl %ebp
| ↓ | ---> 0xffffd868 -> %esp
| | > movl %esp, %ebp
| | ---> 0xffffd868 -> %ebp %esp
+-------------------+
| | > subl $12, %esp
| | ---> 0xffffd868 -> %ebp
| | ---> 0xffffd864
| | ---> 0xffffd860
| ↓ | ---> 0xffffd85c -> %esp
+-------------------+
| | > movl $age, 4(%esp)
| 0x804a004 (age) | ---> 0xffffd860
+-------------------+
| | > movl $author, -8(%ebp)
| 0x804a090 (auth) | ---> 0xffffd860
+-------------------+
| | > movl $id, 8(%esp)
| 0x804a008 (id) | ---> 0xffffd864
+-------------------+
| | > movl $comment, -4(%ebp)
| 0x804a010 (comm) | ---> 0xffffd864
+-------------------+
| %age | > pushl %age
| ↓ | ---> 0xffffd858 -> %esp
+-------------------+
| %eax | > popl %eax
| ↑ | ---> 0xffffd85c -> %esp
+-------------------+
| | > addl $12, %esp
| | ---> 0xffffd868 -> %ebp %esp
+-------------------+
| | > movl %ebp, %esp
| | ---> 0xffffd868 -> %ebp %esp
| %ebp | > popl %ebp
| ↑ | ---> 0xffffd86c -> %esp
+-------------------+
| ret | > ret
| ↑ | ---> 0xffffd870 -> %esp
| |
+-------------------+ ---> 0x804b000 *** Break
| ↓ |
| Unmapped Memory |
| ↑ |
+-------------------+
| ↑ |
| Code and Data |
+-------------------+
Flow of the stack pointer:
0xffffd870 -> %esp
0xffffd86c -> %esp
0xffffd868 -> %ebp %esp
0xffffd85c -> %esp
0xffffd858 -> %esp
0xffffd85c -> %esp
0xffffd868 -> %ebp %esp
0xffffd86c -> %esp
0xffffd870 -> %esp
Virtual Memory
Virtual memory can be mapped to more than just physical memory; it can be mapped to disk as well. Swap partitions on Linux allow Linux's virtual memory system to map memory not only to physical RAM, but also to disk blocks as well. For example, let's say you only have 16 Megabytes of physical memory. Let's also say that 8 Megabytes are being used by Linux and some basic applications, and you want to run a program that requires 20 Megabytes of memory. Can you? The answer is yes, but only if you have set up a swap partition. What happens is that after all of your remaining 8 Megabytes of physical memory have been mapped into virtual memory, Linux starts mapping parts of your application's virtual memory to disk blocks. So, if you access a "memory" location in your program, that location may not actually be in memory at all, but on disk. As the programmer you won't know the difference, though, because it is all handled behind the scenes by Linux.
Now, x86 processors cannot run instructions directly from disk, nor can they access data directly from disk. This requires the help of the operating system. When you try to access memory that is mapped to disk, the processor notices that it can't service your memory request directly. It then asks Linux to step in. Linux notices that the memory is actually on disk. Therefore, it moves some data that is currently in memory onto disk to make room, and then moves the memory being accessed from the disk back into physical memory. It then adjusts the processor's virtual-to-physical memory lookup tables so that it can find the memory in the new location. Finally, Linux returns control to the program and restarts it at the instruction which was trying to access the data in the first place. This instruction can now be completed successfully, because the memory is now in physical RAM.4
Here is an overview of the way memory accesses are handled under Linux:
The program tries to load memory from a virtual address.
The processor, using tables supplied by Linux, transforms the virtual memory address into a physical memory address on the fly.
If the processor does not have a physical address listed for the memory address, it sends a request to Linux to load it.
Linux looks at the address. If it is mapped to a disk location, it continues on to the next step. Otherwise, it terminates the program with a segmentation fault error.
If there is not enough room to load the memory from disk, Linux will move another part of the program or another program onto disk to make room.
Linux then moves the data into a free physical memory address.
Linux updates the processor's virtual-to-physical memory mapping tables to reflect the changes.
Linux restores control to the program, causing it to re-issue the instruction which caused this process to happen.
The processor can now handle the instruction using the newly-loaded memory and translation tables.
It's a lot of work for the operating system, but it gives the user and the programmer great flexibility when it comes to memory management.
Now, in order to make the process more efficient, memory is separated out into groups called pages. When running Linux on x86 processors, a page is 4096 bytes of memory. All of the memory mappings are done a page at a time. Physical memory assignment, swapping, mapping, etc. are all done to memory pages instead of individual memory addresses. What this means to you as a programmer is that whenever you are programming, you should try to keep most memory accesses within the same basic range of memory, so you will only need a page or two of memory at a time. Otherwise, Linux may have to keep moving pages on and off of disk to satisfy your memory needs. Disk access is slow, so this can really slow down your program.
Sometimes so many programs can be loaded that there is hardly enough physical memory for them. They wind up spending more time just swapping memory on and off of disk than they do actually processing it. This leads to a condition called swap death which leads to your system being unresponsive and unproductive. It's usually recoverable if you start terminating your memory-hungry programs, but it's a pain.
NOTE.
Resident Set Size: The amount of memory that your program currently has in physical memory is called its resident set size, and can be viewed by using the program
top. The resident set size is listed under the column labelled "RSS".
Getting More Memory
We now know that Linux maps all of our virtual memory into physical memory or swap. If you try to access a piece of virtual memory that hasn't been mapped yet, it triggers an error known as a segmentation fault, which will terminate your program. The program break point, if you remember, is the last valid address you can use. Now, this is all great if you know beforehand how much storage you will need. You can just add all the memory you need to your .data or .bss sections, and it will all be there. However, let's say you don't know how much memory you will need. For example, with a text editor, you don't know how long the person's file will be. You could try to find a maximum file size, and just tell the user that they can't go beyond that, but that's a waste if the file is small. Therefore Linux has a facility to move the break point to accommodate an application's memory needs.
If you need more memory, you can just tell Linux where you want the new break point to be, and Linux will map all the memory you need between the current and new break point, and then move the break point to the spot you specify. That memory is now available for your program to use. The way we tell Linux to move the break point is through the brk system call. The brk system call is call number 45 (which will be in %eax). %ebx should be loaded with the requested breakpoint. Then you call int $0x80 to signal Linux to do its work. After mapping in your memory, Linux will return the new break point in %eax. The new break point might actually be larger than what you asked for, because Linux rounds up to the nearest page. If there is not enough physical memory or swap to fulfill your request, Linux will return a zero in %eax. Also, if you call brk with a zero in %ebx, it will simply return the last usable memory address.
The problem with this method is keeping track of the memory we request. Let's say I need to move the break to have room to load a file, and then need to move a break again to load another file. Let's say I then get rid of the first file. You now have a giant gap in memory that's mapped, but that you aren't using. If you continue to move the break in this way for each file you load, you can easily run out of memory. So, what is needed is a memory manager.
A memory manager is a set of routines that takes care of the dirty work of getting your program memory for you. Most memory managers have two basic functions - allocate and deallocate.5 Whenever you need a certain amount of memory, you can simply tell allocate how much you need, and it will give you back an address to the memory. When you're done with it, you tell deallocate that you are through with it. allocate will then be able to reuse the memory. This pattern of memory management is called dynamic memory allocation. This minimizes the number of "holes" in your memory, making sure that you are making the best use of it you can. The pool of memory used by memory managers is commonly referred to as the heap.
The way memory managers work is that they keep track of where the system break is, and where the memory that you have allocated is. They mark each block of memory in the heap as being used or unused. When you request memory, the memory manager checks to see if there are any unused blocks of the appropriate size. If not, it calls the brk system call to request more memory. When you free memory it marks the block as unused so that future requests can retrieve it. In the next section we will look at building our own memory manager.
A Simple Memory Manager
Here I will show you a simple memory manager (009-02-alloc.s). It is very primitive but it shows the principles quite well. As usual, I will give you the program first for you to look through. Afterwards will follow an in-depth explanation. It looks long, but it is mostly comments.
# Assemble with `as --32` and `ld -m elf_i386`.
#
# PURPOSE:
# Program to manage memory usage - allocates
# and deallocates memory as requested.
#
# NOTES:
# The programs using these routines will ask
# for a certain size of memory. We actually
# use more than that size, but we put it at the
# beginning, before the pointer we hand back.
# We add a size field and an
# AVAILABLE/UNAVAILABLE marker. So, the memory
# looks like this.
#
###################################################
# - Available -#- Size of -#- Actual memory -#
# - Marker -#- memory -#- locations -#
###################################################
# ^--Returned pointer
# points here.
#
# The pointer we return only points to the actual
# locations requested to make it easier for the
# calling program. It also allows us to change our
# structure without the calling program having to
# change at all.
#
.section .data
# ----- GLOBAL VARIABLES ----- #
#
heap_begin: # This points to the
.long 0 # beginning of the memory
# we are managing.
current_break: # This points to one
.long 0 # location past the memory
# we are managing.
# ----- STRUCTURE INFORMATION ----- #
#
.equ HEADER_SIZE, 8 # Size of space for
# memory region
# header.
.equ HDR_AVAIL_OFFSET, 0 # Location of the
# "available" flag
# in the header.
.equ HDR_SIZE_OFFSET, 4 # Location of the
# size field in the
# header.
# ----- CONSTANTS ----- #
#
.equ UNAVAILABLE, 0 # This is the
# number we will
# use to mark space
# that has been
# given out.
.equ AVAILABLE, 1 # This is the
# number we will
# use to mark space
# that has been
# returned, and is
# available for
# giving.
.equ SYS_BRK, 45 # System call
# number for the
# break system
# call.
.equ LINUX_SYSCALL, 0x80 # Make system calls
# easier to read.
.section .text
# ----- FUNCTIONS ----- #
#
# ----- FUNCTION: _allocate_init ----- #
#
# PURPOSE:
# Call this function to initialize the
# functions (specifically, this sets heap_begin
# and current_break). This has no parameters
# and no return value.
#
.globl _allocate_init
.type _allocate_init, @function
_allocate_init:
pushl %ebp # Standard function stuff.
movl %esp, %ebp
# If the brk system call is called with 0 in %ebx,
# it returns the last valid usable address.
#
movl $SYS_BRK, %eax # Find out where the
movl $0, %ebx # break is.
int $LINUX_SYSCALL
incl %eax # %eax now has the last
# valid address, and we
# want the memory location
# after that.
# Store the current break.
movl %eax, current_break
movl %eax, heap_begin # Store the current break
# as our first address.
# This will cause the
# allocate function to get
# more memory from Linux
# the first time it is run.
movl %ebp, %esp # Exit the function.
popl %ebp
ret
# ----- END OF FUNCTION: _allocate_init ----- #
# ----- FUNCTION: allocate ----- #
#
# PURPOSE:
# This function is used to grab a section of
# memory. It checks to see if there are any
# free blocks, and, if not, it asks Linux for
# a new one.
#
# PARAMETERS:
# This function has one parameter - the size
# of the memory block we want to allocate.
#
# RETURN VALUE:
# This function returns the address of the
# allocated memory in %eax. If there is no
# memory available, it will return 0 in %eax.
#
# PROCESSING:
# Variables used:
# %ecx - hold the size of the requested
# memory (first/only parameter).
# %eax - current memory region being examined
# %ebx - current break position.
# %edx - size of current memory region.
#
# We scan through each memory region starting with
# heap_begin. We look at the size of each one, and
# if it has been allocated. If it is big enough
# for the requested size, and its available, it
# grabs that one. If it does not find a region
# large enough, it asks Linux for more memory. In
# that case, it moves current_break up.
#
.globl _allocate
.type _allocate, @function
.equ ST_MEM_SIZE, 8 # Stack position of the
# memory size to
# allocate.
_allocate:
pushl %ebp # Standard function stuff.
movl %esp, %ebp
# %ecx will hold the size
# we are looking for (which
# is the first and only
# parameter).
# ST_MEM_SIZE = 8
movl ST_MEM_SIZE(%ebp), %ecx
# %ecx <- RECORD_SIZE, 324
movl heap_begin, %eax # %eax will hold the
# current search location.
# %ebx will hold the
# current break.
movl current_break, %ebx
_alloc_loop_begin: # Here we iterate through
# each memory region.
# %eax <- heap_begin
# %ebx <- current_break
cmpl %ebx, %eax # Need more memory if these
je _move_break # are equal.
# Grab the size of this
# memory.
# HDR_SIZE_OFFSET = 4
# %eax <- heap_begin
movl HDR_SIZE_OFFSET(%eax), %edx
# %edx <- HDR_SIZE_OFFSET of heap_begin
# ~ 324
# If the space is
# unavailable, go to the
# next one.
# UNAVAILABLE = 0
# HDR_AVAIL_OFFSET = 0
# %eax <- heap_begin
cmpl $UNAVAILABLE, HDR_AVAIL_OFFSET(%eax)
je _next_location
# %ecx <- RECORD_SIZE, 324
# %edx <- HDR_SIZE_OFFSET of heap_begin
# ~ 324
cmpl %edx, %ecx # If the space is
jle _allocate_here # available, compare the
# size to the needed size.
# If its big enough, go to
# _allocate_here.
_next_location:
# The total size of the memory
# region is the sum of the size
# requested (currently stored in
# %edx), plus another 8 bytes for
# the header (4 for the
# AVAILABLE/UNAVAILABLE flag, and
# 4 for the size of the region).
# So, adding %edx and $8 to %eax
# will get the address of the next
# memory region.
#
# HEADER_SIZE = 8
# %eax <- heap_begin
addl $HEADER_SIZE, %eax
# %eax <- heap_begin + HEADER_SIZE
# %eax <- heap_begin + HEADER_SIZE
# %edx <- HDR_SIZE_OFFSET(%eax)
addl %edx, %eax
# %eax <- heap_begin + HEADER_SIZE
# + HDR_SIZE_OFFSET
# Go look at the next location.
jmp _alloc_loop_begin
_allocate_here: # If we have made it here, that
# means that the region header of
# the region to allocate is in
# %eax.
# Mark space as unavailable
# UNAVAILABLE = 0
# HDR_AVAIL_OFFSET = 0
# %eax <- heap_begin
movl $UNAVAILABLE, HDR_AVAIL_OFFSET(%eax)
# Move %eax past the header
# to the usable memory
# (since that is what we
# return).
# HEADER_SIZE = 8
# %eax <- heap_begin
addl $HEADER_SIZE, %eax
# %eax <- heap_begin + HEADER_SIZE
movl %ebp, %esp # Return from the function.
popl %ebp
ret
_move_break: # If we have made it here, that
# means that we have exhausted all
# addressable memory, and we need
# to ask for more. %ebx holds the
# current endpoint of the data,
# and %ecx holds its size.
# We need to increase %ebx to
# where we want memory to end, so
# we add space for the headers
# structure.
# HEADER_SIZE = 8
# %ebx <- current_break
addl $HEADER_SIZE, %ebx
# %ebx <- current_break + HEADER_SIZE
# ST_MEM_SIZE = 8
# HEADER_SIZE = 8
# %ecx <- ST_MEM_SIZE(%ebp) ~ 324
addl %ecx, %ebx # Add space to the break
# for the data requested.
# %ebx <- current_break + HEADER_SIZE
# + ST_MEM_SIZE(%ebp) ~ 324
# == 0x???????? + 8 + 324 = ~342
# Now its time to ask Linux
# for more memory.
# %eax <- heap_begin
pushl %eax # Save needed registers.
movl $SYS_BRK, %eax # Reset the break (%ebx has
# the requested break
# point).
int $LINUX_SYSCALL # Under normal conditions,
# this should return the
# new break in %eax, which
# will be either 0 if it
# fails, or it will be
# equal to or larger than
# we asked for. We do not
# care in this program
# where it actually sets
# the break, so as long as
# %eax is not 0, we do not
# care what it is.
cmpl $0, %eax # Check for error
je _error # conditions.
# %eax <- heap_begin
popl %eax # Restore saved registers.
# Set this memory as
# unavailable, since we are
# about to give it away.
# UNAVAILABLE = 0
# HDR_AVAIL_OFFSET = 0
# %eax <- $heap_begin
movl $UNAVAILABLE, HDR_AVAIL_OFFSET(%eax)
# Set the size of the
# memory.
# ST_MEM_SIZE = 8
# HDR_SIZE_OFFSET = 4
# %eax <- $heap_begin
# %ecx <- ST_MEM_SIZE(%ebp) ~ 324
movl %ecx, HDR_SIZE_OFFSET(%eax)
# Move %eax to the actual
# start of usable memory.
# %eax now holds the return
# value.
# %eax <- $heap_begin
# HEADER_SIZE = 8
addl $HEADER_SIZE, %eax
# %eax <- $heap_begin + HEADER_SIZE
# %ebx <- current_break + HEADER_SIZE
# + ST_MEM_SIZE(%ebp) ~ 342
movl %ebx, current_break # Save the new break.
movl %ebp, %esp # Return the function.
popl %ebp
ret
_error:
movl $0, %eax # On error, we return zero.
movl %ebp, %esp
popl %ebp
ret
# ----- END OF FUNCTION: allocate ----- #
# ----- FUNCTION: _deallocate ----- #
#
# PURPOSE:
# The purpose of this function is to give back
# a region of memory to the pool after we are
# done using it.
#
# PARAMETERS:
# The only parameter is the address of the
# memory we want to return to the memory pool.
#
# RETURN VALUE:
# There is no return value
#
# PROCESSING:
# If you remember, we actually hand the program
# the start of the memory that they can use,
# which is 8 storage locations after the actual
# start of the memory region. All we have to
# do is go back 8 locations and mark that
# memory as available, so that the allocate
# function knows it can use it.
#
.globl _deallocate
.type _deallocate, @function
.equ ST_MEMORY_SEG, 4 # Stack position of the
# memory region to free
_deallocate: # Since the function is so simple,
# we do not need any of the fancy
# function stuff.
# Get the address of the memory to
# free (normally this is 8(%ebp),
# but since we did not push %ebp or
# move %esp to %ebp, we can just
# do 4(%esp).
movl ST_MEMORY_SEG(%esp), %eax
# Get the pointer to the
# real beginning of the
# memory.
subl $HEADER_SIZE, %eax
# Mark it as available.
movl $AVAILABLE, HDR_AVAIL_OFFSET(%eax)
ret
# ----- END OF FUNCTION: _deallocate ----- #The first thing to notice is that there is no _start symbol. The reason is that this is just a set of functions. A memory manager by itself is not a full program - it doesn't do anything. It is simply a utility to be used by other programs.
To assemble the program, do the following:
as -o 009-02-alloc.o --32 \
--gstabs+ \
009-02-alloc.sOkay, now let's look at the code.
Variables and Constants
At the beginning of the program, we have two locations set up:
Remember, the section of memory being managed is commonly referred to as the heap. When we assemble the program, we have no idea where the beginning of the heap is, nor where the current break is. Therefore, we reserve space for their addresses, but just fill them with a 0 for the time being.
Next we have a set of constants to define the structure of the heap. The way this memory manager works is that before each region of memory allocated, we will have a short record describing the memory. This record has a word reserved for the available flag and a word for the region's size. The actual memory allocated immediately follows this record. The available flag is used to mark whether this region is available for allocations, or if it is currently in use. The size field lets us know both whether or not this region is big enough for an allocation request, as well as the location of the next memory region. The following constants describe this record:
This says that the header is 8 bytes total, the available flag is offset 0 bytes from the beginning, and the size field is offset 4 bytes from the beginning. If we are careful to always use these constants, then we protect ourselves from having to do too much work if we later decide to add more information to the header.
The values that we will use for our available field are either 0 for unavailable, or 1 for available. To make this easier to read, we have the following definitions:
Finally, we have our Linux system call definitions:
The _allocate_init function
Okay, this is a simple function. All it does is set up the heap_begin and current_break variables we discussed earlier. So, if you remember the discussion earlier, the current break can be found using the brk system call. So, the function starts like this:
Anyway, after int $LINUX_SYSCALL, %eax holds the last valid address. We actually want the first invalid address instead of the last valid address, so we just increment %eax. Then we move that value to the heap_begin and current_break locations. Then we leave the function. The code looks like this:
incl %eax # %eax now has the last
# valid address, and we
# want the memory location
# after that.
# Store the current break.
movl %eax, current_break
movl %eax, heap_begin # Store the current break
# as our first address.
# This will cause the
# allocate function to get
# more memory from Linux
# the first time it is run.
movl %ebp, %esp # Exit the function.
popl %ebp
retThe heap consists of the memory between heap_begin and current_break, so this says that we start off with a heap of zero bytes. Our _allocate function will then extend the heap as much as it needs to when it is called.
The _allocate function
This is the doozy function. Let's start by looking at an outline of the function:
Start at the beginning of the heap.
Check to see if we're at the end of the heap.
If we are at the end of the heap, grab the memory we need from Linux, mark it as "unavailable" and return it. If Linux won't give us any more, return a 0.
If the current memory region is marked "unavailable", go to the next one, and go back to step 2.
If the current memory region is too small to hold the requested amount of space, go back to step 2.
If the memory region is available and large enough, mark it as "unavailable" and return it.
Now, look back through the code with this in mind. Be sure to read the comments so you'll know which register holds which value.
Now that you've looked back through the code, let's examine it one line at a time. We start off like this:
_allocate:
pushl %ebp # Standard function stuff.
movl %esp, %ebp
# %ecx will hold the size
# we are looking for (which
# is the first and only
# parameter).
# ST_MEM_SIZE = 8
movl ST_MEM_SIZE(%ebp), %ecx
# %ecx <- RECORD_SIZE, 324
movl heap_begin, %eax # %eax will hold the
# current search location.
# %ebx will hold the
# current break.
movl current_break, %ebxThis part initializes all of our registers. The first two lines are standard function stuff. The next move pulls the size of the memory to allocate off of the stack. This is our only function parameter. After that, it moves the beginning heap address and the end of the heap into registers. I am now ready to do processing.
The next section is marked _alloc_loop_begin. In this loop we are going to examine memory regions until we either find an open memory region or determine that we need more memory. Our first instructions check to see if we need more memory:
%eax holds the current memory region being examined and %ebx holds the location past the end of the heap. Therefore if the next region to be examined is past the end of the heap, it means we need more memory to allocate a region of this size. Let's skip down to _move_break and see what happens there:
_move_break: # If we have made it here, that
# means that we have exhausted all
# addressable memory, and we need
# to ask for more. %ebx holds the
# current endpoint of the data,
# and %ecx holds its size.
# We need to increase %ebx to
# where we want memory to end, so
# we add space for the headers
# structure.
# HEADER_SIZE = 8
# %ebx <- current_break
addl $HEADER_SIZE, %ebx
# %ebx <- current_break + HEADER_SIZE
# ST_MEM_SIZE = 8
# HEADER_SIZE = 8
# %ecx <- ST_MEM_SIZE(%ebp) ~ 324
addl %ecx, %ebx # Add space to the break
# for the data requested.
# %ebx <- current_break + HEADER_SIZE
# + ST_MEM_SIZE(%ebp) ~ 324
# == 0x???????? + 8 + 324 = ~342
# Now its time to ask Linux
# for more memory.
# %eax <- heap_begin
pushl %eax # Save needed registers.
movl $SYS_BRK, %eax # Reset the break (%ebx has
# the requested break
# point).
int $LINUX_SYSCALL # Under normal conditions,
# this should return the
# new break in %eax, which
# will be either 0 if it
# fails, or it will be
# equal to or larger than
# we asked for. We do not
# care in this program
# where it actually sets
# the break, so as long as
# %eax is not 0, we do not
# care what it is.When we reach this point in the code, %ebx holds where we want the next region of memory to be. So, we add our header size and region size to %ebx, and that's where we want the system break to be. We then push all the registers we want to save on the stack, and call the brk system call. After that we check for errors:
If there were no errors we pop the registers back off the stack, mark the memory as unavailable, record the size of the memory, and make sure %eax points to the start of usable memory (which is after the header).
# %eax <- heap_begin
popl %eax # Restore saved registers.
# Set this memory as
# unavailable, since we are
# about to give it away.
# UNAVAILABLE = 0
# HDR_AVAIL_OFFSET = 0
# %eax <- $heap_begin
movl $UNAVAILABLE, HDR_AVAIL_OFFSET(%eax)
# Set the size of the
# memory.
# ST_MEM_SIZE = 8
# HDR_SIZE_OFFSET = 4
# %eax <- $heap_begin
# %ecx <- ST_MEM_SIZE(%ebp) ~ 324
movl %ecx, HDR_SIZE_OFFSET(%eax)
# Move %eax to the actual
# start of usable memory.
# %eax now holds the return
# value.
# %eax <- $heap_begin
# HEADER_SIZE = 8
addl $HEADER_SIZE, %eax
# %eax <- $heap_begin + HEADER_SIZEThen we store the new program break and return the pointer to the allocated memory.
The _error code just returns 0 in %eax, so we won't discuss it.
Let's go back look at the rest of the loop. What happens if the current memory being looked at isn't past the end of the heap? Well, let's look.
# Grab the size of this
# memory.
# HDR_SIZE_OFFSET = 4
# %eax <- heap_begin
movl HDR_SIZE_OFFSET(%eax), %edx
# %edx <- HDR_SIZE_OFFSET of heap_begin
# ~ 324
# If the space is
# unavailable, go to the
# next one.
# UNAVAILABLE = 0
# HDR_AVAIL_OFFSET = 0
# %eax <- heap_begin
cmpl $UNAVAILABLE, HDR_AVAIL_OFFSET(%eax)
je _next_locationThis first grabs the size of the memory region and puts it in %edx. Then it looks at the available flag to see if it is set to UNAVAILABLE. If so, that means that memory region is in use, so we'll have to skip over it. So, if the available flag is set to UNAVAILABLE, you go to the code labeled _next_location. If the available flag is set to AVAILABLE, then we keep on going.
Let's say that the space was available, and so we keep going. Then we check to see if this space is big enough to hold the requested amount of memory. The size of this region is being held in %edx, so we do this:
If the requested size is less than or equal to the current region's size, we can use this block. It doesn't matter if the current region is larger than requested, because the extra space will just be unused. So, let's jump down to _allocate_here and see what happens:
_allocate_here: # If we have made it here, that
# means that the region header of
# the region to allocate is in
# %eax.
# Mark space as unavailable
# UNAVAILABLE = 0
# HDR_AVAIL_OFFSET = 0
# %eax <- heap_begin
movl $UNAVAILABLE, HDR_AVAIL_OFFSET(%eax)
# Move %eax past the header
# to the usable memory
# (since that is what we
# return).
# HEADER_SIZE = 8
# %eax <- heap_begin
addl $HEADER_SIZE, %eax
# %eax <- heap_begin + HEADER_SIZE
movl %ebp, %esp # Return from the function.
popl %ebp
retIt marks the memory as being unavailable. Then it moves the pointer %eax past the header, and uses it as the return value for the function. Remember, the person using this function doesn't need to even know about our memory header record. They just need a pointer to usable memory.
Okay, so let's say the region wasn't big enough. What then? Well, we would then be at the code labeled _next_location. This section of code is used any time that we figure out that the current memory region won't work for allocating memory. All it does is advance %eax to the next possible memory region, and goes back to the beginning of the loop. Remember that %edx is holding the size of the current memory region, and HEADER_SIZE is the symbol for the size of the memory region's header. So this code will move us to the next memory region:
_next_location:
# The total size of the memory
# region is the sum of the size
# requested (currently stored in
# %edx), plus another 8 bytes for
# the header (4 for the
# AVAILABLE/UNAVAILABLE flag, and
# 4 for the size of the region).
# So, adding %edx and $8 to %eax
# will get the address of the next
# memory region.
#
# HEADER_SIZE = 8
# %eax <- heap_begin
addl $HEADER_SIZE, %eax
# %eax <- heap_begin + HEADER_SIZE
# %eax <- heap_begin + HEADER_SIZE
# %edx <- HDR_SIZE_OFFSET(%eax)
addl %edx, %eax
# %eax <- heap_begin + HEADER_SIZE
# + HDR_SIZE_OFFSET
# Go look at the next location.
jmp _alloc_loop_beginAnd now the function runs another loop.
Whenever you have a loop, you must make sure that it will always end. The best way to do that is to examine all of the possibilities, and make sure that all of them eventually lead to the loop ending. In our case, we have the following possibilities:
We will reach the end of the heap.
We will find a memory region that's available and large enough.
We will go to the next location.
The first two items are conditions that will cause the loop to end. The third one will keep it going. However, even if we never find an open region, we will eventually reach the end of the heap, because it is a finite size. Therefore, we know that no matter which condition is true, the loop has to eventually hit a terminating condition.
The _deallocate function
The _deallocate function is much easier than the _allocate one. That's because it doesn't have to do any searching at all. It can just mark the current memory region as AVAILABLE, and _allocate will find it next time it is called. So we have:
_deallocate: # Since the function is so simple,
# we do not need any of the fancy
# function stuff.
# Get the address of the memory to
# free (normally this is 8(%ebp),
# but since we did not push %ebp or
# move %esp to %ebp, we can just
# do 4(%esp).
movl ST_MEMORY_SEG(%esp), %eax
# Get the pointer to the
# real beginning of the
# memory.
subl $HEADER_SIZE, %eax
# Mark it as available.
movl $AVAILABLE, HDR_AVAIL_OFFSET(%eax)
retIn this function, we don't have to save %ebp or %esp since we're not changing them, nor do we have to restore them at the end. All we're doing is reading the address of the memory region from the stack, backing up to the beginning of the header, and marking the region as available. This function has no return value, so we don't care what we leave in %eax.
Performance Issues and Other Problems
Our simplistic memory manager is not really useful for anything more than an academic exercise. This section looks at the problems with such a simplistic allocator.
The biggest problem here is speed. Now, if there are only a few allocations made, then speed won't be a big issue. But think about what happens if you make a thousand allocations. On allocation number 1000, you have to search through 999 memory regions to find that you have to request more memory. As you can see, that's getting pretty slow. In addition, remember that Linux can keep pages of memory on disk instead of in memory. So, since you have to go through every piece of memory your program's memory, that means that Linux has to load every part of memory that's currently on disk to check to see if it is available. You can see how this could get really, really slow.6 This method is said to run in linear time, which means that every element you have to manage makes your program take longer. A program that runs in constant time takes the same amount of time no matter how many elements you are managing. Take the _deallocate function, for instance. It only runs 4 instructions, no matter how many elements we are managing, or where they are in memory. In fact, although our _allocate function is one of the slowest of all memory managers, the _deallocate function is one of the fastest.
Another performance problem is the number of times we're calling the brk system call. System calls take a long time. They aren't like functions, because the processor has to switch modes. Your program isn't allowed to map itself memory, but the Linux kernel is. So, the processor has to switch into kernel mode, then Linux maps the memory, and then switches back to user mode for your application to continue running. This is also called a context switch. Context switches are relatively slow on x86 processors. Generally, you should avoid calling the kernel unless you really need to.
Another problem that we have is that we aren't recording where Linux actually sets the break. Previously we mentioned that Linux might actually set the break past where we requested it. In this program, we don't even look at where Linux actually sets the break - we just assume it sets it where we requested. That's not really a bug, but it will lead to unnecessary brk system calls when we already have the memory mapped in.
Another problem we have is that if we are looking for a 5-byte region of memory, and the first open one we come to is 1000 bytes, we will simply mark the whole thing as allocated and return it. This leaves 995 bytes of unused, but allocated, memory. It would be nice in such situations to break it apart so the other 995 bytes can be used later. It would also be nice to combine consecutive free spaces when looking for large allocations.
Using our Allocator
The programs we do in this book aren't complicated enough to necessitate a memory manager. Therefore, we will just use our memory manager to allocate a buffer for one of our file reading/writing programs instead of assigning it in the .bss.
The program we will demonstrate this on is 009-02-read-records.s from Chapter 6. Reading and Writing Simple Records. This program uses a buffer named _record_buffer to handle its input/output needs. We will simply change this from being a buffer defined in .bss to being a pointer to a dynamically-allocated buffer using our memory manager. You will need to have the code from that program handy as we will only be discussing the changes in this section.
# Assemble with `as --32` and `ld -m elf_i386`.
#
.include "006-01-linux.s" # Linux Definitions.
.include "006-01-record-def.s" # Record definitions
.section .data
file_name:
.ascii "test.dat\0"
record_buffer_ptr:
.long 0
.section .bss
.lcomm record_buffer, RECORD_SIZE
.section .text
.globl _start
_start:
# ----- Main Program ----- #
#
# These are the locations on the stack where we
# will store the input and output descriptors
# (FYI - we could have used memory addresses in a
# .data section instead).
#
.equ ST_INPUT_DESCRIPTOR, -4
.equ ST_OUTPUT_DESCRIPTOR, -8
call _allocate_init
pushl $RECORD_SIZE
call _allocate
movl %eax, record_buffer_ptr
movl %esp, %ebp # Copy the stack pointer to
# %ebp.
subl $8, %esp # Allocate space to hold
# the file descriptors.
movl $SYS_OPEN, %eax # Open the file.
movl $file_name, %ebx
movl $0, %ecx # This says to open
# read-only.
movl $0666, %edx
int $LINUX_SYSCALL
# ----- Save file descriptor ----- #
#
movl %eax, ST_INPUT_DESCRIPTOR(%ebp)
# Even though it is a constant, we are saving the
# output file descriptor in a local variable so
# that if we later decide that it is not always
# going to be STDOUT, we can change it easily.
#
movl $STDOUT, ST_OUTPUT_DESCRIPTOR(%ebp)
_record_read_loop:
pushl ST_INPUT_DESCRIPTOR(%ebp)
pushl record_buffer_ptr
call _read_record
addl $8, %esp
# Returns the number of bytes read. If it is not
# the same number we requested, then it is either
# an end-of-file, or an error, so we are quitting.
#
cmpl $RECORD_SIZE, %eax
jne _finished_reading
# Otherwise, print out the first name but we must
# know the size.
#
movl record_buffer_ptr, %eax
addl $RECORD_FIRSTNAME, %eax
pushl %eax
call _count_chars
addl $4, %esp
movl %eax, %edx
movl ST_OUTPUT_DESCRIPTOR(%ebp), %ebx
movl $SYS_WRITE, %eax
movl record_buffer_ptr, %ecx
addl $RECORD_FIRSTNAME, %ecx
int $LINUX_SYSCALL
pushl ST_OUTPUT_DESCRIPTOR(%ebp)
call _write_newline
addl $4, %esp
jmp _record_read_loop
_finished_reading:
pushl record_buffer_ptr
call _deallocate
movl $SYS_EXIT, %eax
movl $0, %ebx
int $LINUX_SYSCALLThe first change we need to make is in the declaration. Currently it looks like this:
It would be a misnomer to keep the same name, since we are switching it from being an actual buffer to being a pointer to a buffer. In addition, it now only needs to be one word big (enough to hold a pointer). The new declaration will stay in the .data section and look like this:
Our next change is we need to initialize our memory manager immediately after we start our program. Therefore, right after the stack is set up, the following call needs to be added:
After that, the memory manager is ready to start servicing memory allocation requests. We need to allocate enough memory to hold these records that we are reading. Therefore, we will call _allocate to allocate this memory, and then save the pointer it returns into record_buffer_ptr. Like this:
Now, when we make the call to _read_record, it is expecting a pointer. In the old code, the pointer was the immediate-mode reference to _record_buffer. Now, record_buffer_ptr just holds the pointer rather than the buffer itself. Therefore, we must do a direct mode load to get the value in record_buffer_ptr. We need to remove this line:
And put this line in its place:
The next change comes when we are trying to find the address of the firstname field of our record. In the old code, it was $RECORD_FIRSTNAME + record_buffer. However, that only works because it is a constant offset from a constant address. In the new code, it is the offset of an address stored in record_buffer_ptr. To get that value, we will need to move the pointer into a register, and then add $RECORD_FIRSTNAME to it to get the pointer. So where we have the following code:
We need to replace it with this:
Similarly, we need to change the line that says
so that it reads like this:
Finally, one change that we need to make is to deallocate the memory once we are done with it (in this program it's not necessary, but it's a good practice anyway). To do that, we just send record_buffer_ptr to the _deallocate function right before exiting:
Now you can build your program with the following commands:
as -o 009-02-read-records.o --32 \
--gstabs+ \
009-02-read-records.s
ld -o 009-02-read-records -m elf_i386 \
006-01-count-chars.o \
006-01-read-record.o \
006-01-write-newline.o \
009-02-alloc.o \
009-02-read-records.oYou can then run your program by doing ./009-02-read-records.
The uses of dynamic memory allocation may not be apparent to you at this point, but as you go from academic exercises to real-life programs you will use it continually.
More Information
More information on memory handling in Linux and other operating systems can be found at the following locations:
More information about the memory layout of Linux programs can be found in Konstantin Boldyshev's document, Startup state of a Linux/i386 ELF binary.
A good overview of virtual memory in many different systems is available at Virtual Memory - Operating System Concepts.
Several in-depth articles on Linux's virtual memory subsystem is available at Linux Kernel Documentation Project.
Doug Lea has written up a description of his popular memory allocator at A Memory Allocator by Doug Lea.
A paper on the 4.4 BSD memory allocator is available at Malloc(3) in modern Virtual Memory environments.
Review
Know the Concepts
Describe the layout of memory when a Linux program starts.
What is the heap?
What is the current break?
Which direction does the stack grow in?
Which direction does the heap grow in?
What happens when you access unmapped memory?
How does the operating system prevent processes from writing over each other's memory?
Describe the process that occurs if a piece of memory you are using is currently residing on disk?
Why do you need an allocator?
Use the Concepts
Modify the memory manager so that it calls
_allocate_initautomatically if it hasn't been initialized.Modify the memory manager so that if the requested size of memory is smaller than the region chosen, it will break up the region into multiple parts. Be sure to take into account the size of the new header record when you do this.
Modify one of your programs that uses buffers to use the memory manager to get buffer memory rather than using the
.bss.
Going Further
Research garbage collection. What advantages and disadvantages does this have over the style of memory management used here?
Research reference counting. What advantages and disadvantages does this have over the style of memory management used here?
Change the name of the functions to
mallocandfree, and build them into a shared library. UseLD_PRELOADto force them to be used as your memory manager instead of the default one. Add somewritesystem calls to STDOUT to verify that your memory manager is being used instead of the default one.
You actually never use addresses this low, but it works for discussion.↩︎
Addresses mentioned in this chapter are not set in stone and may vary based on kernel version.↩︎
The stack can access it as it grows downward, and you can access the stack regions through %esp. However, your program's data section doesn't grow that way. The way to grow that will be explained shortly.↩︎
Note that not only can Linux have a virtual address map to a different physical address, it can also move those mappings around as needed.↩︎
The function names usually aren't
_allocateand_deallocate, but the functionality will be the same. In the C programming language, for example, they are namedmallocandfree.↩︎This is why adding more memory to your computer makes it run faster. The more memory your computer has, the less it puts on disk, so it doesn't have to always be interrupting your programs to retrieve pages off the disk.↩︎