The Linux Kernel Primer. A Top-Down Approach for x86 and PowerPC Architectures

We now look at what memory looks like for our own program. This project consists of an exploration of a user space program that illustrates where things are placed in memory. For this project, we create a simple shared library and a user space program that uses its function. From the program, we print the location of some of the variables and compare it against the process memory mappings to determine where the variables and functions are being stored.

The first step is to create the shared library. The shared library can have a single function, which we will call from our main program. We want to print the address of a local variable from within this function. Your shared library should look like this:

----------------------------------------------------------------------------- lkpsinglefoo.c mylibfoo() { int libvar; printf("variable libvar \t location: 0x%x\n", &libvar); } -----------------------------------------------------------------------------

Compile and link singlefoo.c into a shared library:

#lkp>gcc c lkpsinglefoo.c #lkp>gcc lkpsinglefoo.o o liblkpsinglefoo.so shared lc

The shared and lc flags are linker options. The shared option requests that a shared object that can be linked with other objects be produced. The lc flag indicates that the C library be searched when linking.

These commands generate a file called liblkpsinglefoo.so. To use it, you need to copy it to /lib.

The following is the main application we will call that links in your library:

----------------------------------------------------------------------------- lkpmem.c #include <fcntl.h> int globalvar1; int globalvar2 = 3; void mylocalfoo() { int functionvar; printf("variable functionvar \t location: 0x%x\n", &functionvar); } int main() { void *localvar1 = (void *)malloc(2048) printf("variable globalvar1 \t location: 0x%x\n", &globalvar1); printf("variable globalvar2 \t location: 0x%x\n", &globalvar2); printf("variable localvar1 \t location: 0x%x\n", &localvar1); mylibfoo(); mylocalfoo(); while(1); return(0); } -----------------------------------------------------------------------------

Compile lkpmem.c as follows:

#lkp>gcc o lkpmem lkpmem.c llkplibsinglefoo

When you execute lkpmem, you get the print statements that indicate the memory locations of the various variables. The function blocks on the while(1); statement and does not return. This allows you to get the process PID and search the memory maps. To do so, use the following commands:

#lkp>./lkpmem #lkp> ps aux | grep lkpmem #lkp> cat /proc/<pid>/maps

Indicate the memory segment in which each variable is located.

Категории