csperkins.org

Advanced Systems Programming H (2020-2021)

Lecture 5: Resource Ownership and Memory Management

This lecture begins to discuss the various options available for resource ownership and memory management in modern programming languages. It discusses how running programs are arranged in memory, and outlines the need for automatic memory management. It then discusses two approaches to memory management: reference counting and region-based memory management, considering their various costs and benefits. The region-based approach used in Rust is shown to have several important benefits, in terms of efficient and deterministic memory management, but at the cost of making certain classes of program more complex to express.

Part 1: Resource Ownership and Memory Management

The first part of this lecture reviews of a process is stored in memory, and what different types of memory exist within a running process, as a prelude to the discussion of automatic memory management. It also discusses how memory-unsafe behaviour can lead to security vulnerabilities through buffer overflows attacks.

00:00:00.000 In this week’s lecture, I want to

00:00:02.950 talk about resource ownership and memory management.

 

00:00:06.000 In this first part, I’ll talk about

00:00:08.300 how a process is stored in memory,

00:00:10.600 and what memory has to be managed.

 

00:00:13.000 Then, in the following parts, I’ll start

00:00:16.010 our discussion of different approaches to memory

00:00:19.020 management, starting with reference counting and region-based

00:00:22.030 memory management, and how these interact with

00:00:25.040 resource management.

 

00:00:27.000 Let’s start by talking about memory.

 

00:00:31.000 To understand memory management, you must first

00:00:33.396 understand what memory needs to be managed.

00:00:35.792 In all modern operating systems, every process

00:00:38.288 is given a virtual address space in

00:00:40.685 which it executes. Each process thinks it’s

00:00:43.081 the only one running on the machine,

00:00:45.477 and has access to the full range

00:00:47.873 of memory addresses.

 

00:00:49.000 The underlying hardware translates these virtual addresses

00:00:51.993 into physical addresses that represent particular locations

00:00:54.986 in real memory, and makes sure that

00:00:57.979 the different processes are isolated from each

00:01:00.972 other.

 

00:01:01.500 The virtual address space that a process

00:01:04.200 sees is divided into several different parts.

 

00:01:07.000 At the bottom of memory, starting with

00:01:09.819 the lowest numbered address sits the program

00:01:12.638 text itself: the machine runs that represents

00:01:15.457 the running program. That’s immediately followed by

00:01:18.276 the static data and space for any

00:01:21.095 global variables.

 

00:01:22.000 Following this in memory is the heap:

00:01:24.700 memory allocated using malloc(), or similar mechanisms.

00:01:27.400 Following that is the memory used to

00:01:30.200 hold shared libraries and memory mapped files.

 

00:01:33.000 Then the stack space, growing down from

00:01:35.700 the top of user accessible memory.

00:01:38.014 Then, finally, the operating system kernel itself

00:01:40.814 occupies the top part of the address

00:01:43.514 space.

 

00:01:44.000 How much memory is allocated to each

00:01:46.442 of these, and what virtual addresses each

00:01:48.884 sits between, depend on whether you have

00:01:51.326 a 32-bit or a 64-bit machine,

00:01:53.419 and on what operating system you’re running.

00:01:55.860 But all the systems follow the same

00:01:58.302 basic approach.

 

00:02:02.000 The program text, data, and global variables

00:02:04.967 occupy the lowest part of the address

00:02:07.933 space. There are four parts to this.

 

00:02:11.000 The very lowest page of memory,

00:02:13.472 usually the first 4096 bytes starting at

00:02:16.356 address zero, is reserved. In languages like

00:02:19.240 C, a null pointer is represented by

00:02:22.124 address zero, so the hardware virtual memory

00:02:25.008 controller is programmed to prohibit access to

00:02:27.892 that address, and to adjacent addresses,

00:02:30.364 as a way of trapping null-pointer dereferences.

00:02:33.248 Trying to access this memory will trap

00:02:36.132 into the operating system, which will kill

00:02:39.016 the process with a segmentation violation error.

 

00:02:42.000 Following this reserved page, sits the compiled

00:02:45.139 program text. That is, the machine code

00:02:48.277 representing the program. This occupies the lowest

00:02:51.416 part of the address space, starting just

00:02:54.555 above address zero.

 

00:02:56.000 Next comes the data segment. This comprises

00:02:58.876 string literals and static global variables.

00:03:01.341 Data and global variables where the value

00:03:04.217 is known at compile time. These are

00:03:07.093 stored in the compiled binary, along with

00:03:09.970 the executable machine code, and loaded into

00:03:12.846 memory following the program text.

 

00:03:15.000 Then, space is allocated for the BSS

00:03:18.465 segment. This provides reserved space for uninitialised

00:03:21.930 global variables defined in the program.

 

00:03:25.000 The name BSS stands for “block started

00:03:27.950 by symbol”, and is a historical relic.

 

00:03:31.000 The program text and data segments are

00:03:33.713 fixed. They comprise the compiled program code

00:03:36.425 and data known at compile time.

00:03:38.750 Similarly, the size of the BSS segment

00:03:41.463 is known at compile time.

 

00:03:43.500 In older operating systems, the program and

00:03:45.950 data always start at a fixed location

00:03:48.400 at the start of the memory.

00:03:50.500 In modern systems, they’re still loaded near

00:03:52.950 the start of the memory, but the

00:03:55.400 actual starting address is randomised each time

00:03:57.850 the program runs.

 

00:03:59.000 Why is it randomised?

00:04:00.390 It’s a security measure. It makes it

00:04:02.922 harder for code executed as part of

00:04:05.355 a buffer overflow attack to call into

00:04:07.787 other parts of the program, since it

00:04:10.220 can’t know where they’ll be located in

00:04:12.653 memory.

 

00:04:16.000 As a program executes, it needs space

00:04:18.709 to hold the function parameters, return addresses,

00:04:21.417 and local variables. These are stored on

00:04:24.126 the stack.

 

00:04:25.000 The stack occupies the top of user

00:04:28.279 accessible memory, starting at a random address

00:04:31.558 for security, and grows downwards.

 

00:04:34.000 Each time a function is called,

00:04:36.164 starting with main(), the parameters to that

00:04:38.689 function, the return address, and a pointer

00:04:41.214 to the previous stack frame are pushed

00:04:43.739 onto the stack. The occupy the next

00:04:46.264 addresses below the previous top of the

00:04:48.789 stack.

 

00:04:49.250 And when the function starts to execute,

00:04:52.031 space for its local variables is similarly

00:04:54.811 allocated on the stack.

 

00:04:56.500 If that function calls other functions,

00:04:58.525 the stack grows, as the new stack

00:05:00.887 frames are created.

 

00:05:02.000 And when a function returns, the stack

00:05:04.510 shrinks and the memory it used on

00:05:07.021 the stack is automatically reclaimed.

00:05:08.814 The compiler generates the code to manage

00:05:11.424 the stack, as part of the code

00:05:13.934 it generates for each function. It knows

00:05:16.445 how the return address, parameters, and stack

00:05:18.955 pointer are represented, and how to grow

00:05:21.466 and shrink the stack.

 

00:05:23.000 And the operating system generates the stack

00:05:25.596 frame for main() when the program starts,

00:05:28.192 with a return address pointing to the

00:05:30.788 process cleanup code.

 

00:05:32.000 To the programmer, the stack is managed

00:05:35.062 automatically. Ownership of the stack memory follows

00:05:38.125 function invocation.

 

00:05:41.500 This slide shows an example of a

00:05:44.134 simple C program.

00:05:45.263 It comprises a main() function that inspects

00:05:47.997 the values given as command line arguments,

00:05:50.631 and either prints a greeting or a

00:05:53.264 usage message.

00:05:54.017 When this program starts to execute,

00:05:56.375 and main() is called, the stack contents

00:05:59.008 are as shown in the green region

00:06:01.642 on the right of the slide.

 

00:06:04.000 The stack contains the arguments to main(),

00:06:07.179 argc and argv, the address to return

00:06:10.358 to once main() completes, and the local

00:06:13.538 variables for main.

 

00:06:15.000 When execution reaches the printf() line,

00:06:17.970 shown in red, and the function is

00:06:21.435 called, a new stack frame is created.

 

00:06:25.000 This new stack frame holds the arguments

00:06:27.567 for printf(), the address to return to

00:06:30.133 once the printf() call finishes, and a

00:06:32.700 pointer to the previous stack frame.

 

00:06:35.000 The address of the previous stack frame

00:06:37.531 is stored for ease of debugging,

00:06:39.700 so stack traces can be printed and

00:06:42.231 so debuggers can trace program execution.

 

00:06:44.500 As printf() starts to execute, space is

00:06:46.724 allocated on the stack for any local

00:06:48.947 variables it uses.

 

00:06:50.000 And, if printf() itself calls any functions,

00:06:52.800 the stack will continue to grow as

00:06:55.600 needed.

 

00:06:58.000 This suggests the classic buffer overflow attack.

00:07:00.300 If the language is not type safe,

00:07:02.700 and doesn’t check array bounds, then the

00:07:05.000 call to printf() can be arranged so

00:07:07.300 that it writes past the bounds of

00:07:09.600 a local variable stored on the stack.

 

00:07:12.000 When this happens, it overwrites whatever is

00:07:14.800 stored in the next higher addresses on

00:07:17.600 the stack.

 

00:07:18.500 What would that be? Well, maybe some

00:07:21.300 other local variables, but also the pointer

00:07:24.100 to the previous stack frame, then the

00:07:26.900 return address of the function.

 

00:07:29.000 The goal is to overwrite the return

00:07:31.473 address, and some of the following memory.

00:07:33.947 The attacker tries to fill the memory

00:07:36.420 following the return address with the code

00:07:38.893 they want to execute. And to overwrite

00:07:41.367 the return address so that it points

00:07:43.840 to that code.

 

00:07:45.000 When the function then returns, rather than

00:07:47.725 return to the correct place, it returns

00:07:50.450 instead to the return address written during

00:07:53.175 the overflows, and executes the attacker’s code.

 

00:07:56.000 It’s a technique known as stack smashing.

00:07:58.983 The link to the Phrack article on

00:08:02.065 the slide is the classic explanation of

00:08:05.048 this technique.

 

00:08:06.000 Modern systems have workarounds, of course.

 

00:08:10.000 They randomise the location of the stack

00:08:12.127 each time a program runs, to make

00:08:14.254 it harder to known what value to

00:08:16.381 overwrite the return address with.

 

00:08:18.000 And they arrange for the virtual memory

00:08:20.461 hardware to mark the stack memory as

00:08:22.923 non-executable, so the system will refuse to

00:08:25.384 execute the code if the return address

00:08:27.845 is successfully overwritten.

 

00:08:29.000 These techniques help. The classic stack smashing

00:08:32.456 attack I’ve described won’t work on a

00:08:35.912 modern system.

 

00:08:37.000 But they don’t entirely solve the problem.

00:08:39.967 Newer attacks, such as return oriented programming,

00:08:42.933 can defeat the protections in some cases.

 

00:08:46.000 The real solution, of course, is to

00:08:48.545 use a language that checks array bounds,

00:08:51.091 and prevents buffer overflows in the first

00:08:53.636 place.

 

00:08:56.000 Back to memory management.

00:08:57.874 In addition to the program code and

00:09:01.253 the stack, the heap holds explicitly allocated

00:09:04.532 memory.

 

00:09:07.000 This is memory allocated by calls to

00:09:09.800 functions such as malloc() and calloc() in

00:09:12.600 C. Boxed memory in Rust. And objects

00:09:15.400 allocated using new() in Java.

 

00:09:17.500 The heap starts at a low address

00:09:20.300 in memory, following the BSS segment,

00:09:22.700 and grows upwards towards the stack.

00:09:25.100 As you might expect by now,

00:09:27.500 the exact starting address for heap allocations

00:09:30.300 is randomised for security.

 

00:09:32.000 In general, successive heap allocations will occupy

00:09:34.745 consecutive blocks in memory, although multi-threaded systems

00:09:37.489 will partition the heap so that each

00:09:40.234 thread that its own space in which

00:09:42.979 to make allocations, without needed to coordinate

00:09:45.724 with other threads.

 

00:09:47.000 And, depending on the processor, small allocations

00:09:49.888 may be rounded up in size to

00:09:52.775 align on a 32 bit or a

00:09:55.663 64 bit boundary.

 

00:09:57.000 While the stack is managed automatically as

00:09:59.396 functions are called, the challenge of memory

00:10:01.792 management is primarily about how to manage

00:10:04.188 and reclaim the heap memory.

 

00:10:06.000 This can be done manually, by calling

00:10:08.730 the free() function.

 

00:10:10.000 It can be done automatically via reference

00:10:12.542 counting or garbage collection, as we’ll discuss

00:10:15.084 next in the next lecture.

 

00:10:17.000 Or it can be done automatically,

00:10:19.286 based on regions and lifetime analysis,

00:10:21.571 as I’ll discuss in later part of

00:10:24.238 this lecture.

 

00:10:26.000 In addition to allocating heap memory,

00:10:28.724 most operating systems allow memory mapped files,

00:10:31.903 allowing data on disk to be directly

00:10:35.081 mapped into the address space.

00:10:37.351 On Unix-like systems, such mappings are created

00:10:40.630 using the mmap() system call.

 

00:10:43.000 The mmap() call returns a pointer to

00:10:45.321 a block of memory that acts as

00:10:47.642 a proxy for the file. Reading from

00:10:49.963 that memory will page into the relevant

00:10:52.284 part of the file into memory,

00:10:54.274 and return its contents. And writes to

00:10:56.595 that block of memory will eventually be

00:10:58.916 paged back out to disk by the

00:11:01.237 operating system.

 

00:11:02.000 The file is paged in and out

00:11:04.380 of memory as needed, with only the

00:11:06.760 parts of the file being accessed being

00:11:09.140 loaded. It’s an effective way of providing

00:11:11.520 random access to parts of a file.

 

00:11:14.000 Such memory mapped files generally occupy the

00:11:16.450 space between the heap and the stack.

 

00:11:19.000 Shared libraries are usually implemented using memory

00:11:21.676 mapped files, and are mapped into this

00:11:24.353 memory space too.

 

00:11:27.500 Finally, the operating system kernel resides at

00:11:30.533 the top of the address space.

00:11:33.133 Kernel memory isn’t directly accessible to user

00:11:36.267 programs, and attempts to access that memory

00:11:39.300 will result in a segmentation violation.

 

00:11:42.000 The hardware provides a special machine code

00:11:44.780 instruction, known as syscall on 64-bit Intel

00:11:47.560 processors, that switches the system to kernel

00:11:50.340 mode and executes a particular function in

00:11:53.120 kernel memory, after performing some permission checks.

 

00:11:56.000 The kernel itself can read and write

00:11:58.400 to the entire address space. The hardware

00:12:00.800 protects the operating system kernel from the

00:12:03.200 user processes, but the operating system has

00:12:05.600 to be able to control those processes

 

00:12:10.000 That concludes our discussion of how programs

00:12:12.291 are stored in memory.

00:12:13.600 In the next part, I’ll start to

00:12:15.991 talk about memory management, and the use

00:12:18.282 of reference counting as a memory management

00:12:20.573 technique.

Part 2: Automatic Memory Management and Reference Counting

The second part of the lecture introduces the concepts of automatic memory management and its use in systems programs. Then it discusses one of the simplest automatic memory management schemes: reference counting. It outlines how reference counting works, and describes its limitations, costs, and benefits.

00:00:00.000 In this part, I’ll talk about the

00:00:03.492 goals of automatic memory management. And I’ll

00:00:05.984 discuss one of the simplest automatic memory

00:00:08.476 management schemes, reference counting.

 

00:00:11.000 Automatic memory management is frequently distrusted by

00:00:14.345 systems programmers.

00:00:15.301 There’s a general belief that it has

00:00:18.747 high overheads. That it’s slow, CPU hungry,

00:00:22.092 and wastes memory. And that the use

00:00:25.437 of automatic memory management introduces unpredictability into

00:00:28.783 the timing of time sensitive operations.

 

00:00:31.750 And to some extent this belief is

00:00:33.631 true.

 

00:00:34.000 There are many different types of automatic

00:00:36.913 memory management. And some of them do

00:00:39.826 have high CPU costs. Some of them

00:00:42.739 do waste memory. And some do introduce

00:00:45.652 unpredictability into timing.

 

00:00:47.000 Equally, though, there are very real problems

00:00:49.858 due to manual memory management.

 

00:00:52.000 Managing memory manually has unpredictable overheads.

00:00:56.500 As a programmer you known when you

00:00:58.788 call malloc() and free(), but you have

00:01:01.076 no idea how long those calls will

00:01:03.363 take to execute. And they can be

00:01:05.651 quite processor intensive, and can take unpredictable

00:01:07.939 amounts of time, in some cases.

 

00:01:10.000 And there are the numerous, and well

00:01:12.913 known, problems due to memory leaks,

00:01:15.410 memory corruption, buffer overflows, use-after-free bugs,

00:01:17.906 and iterator invalidation, all of which are

00:01:20.819 due to manual memory management.

 

00:01:23.000 Systems programmers have focussed on the problems

00:01:25.940 of moving to automatic memory management,

00:01:28.460 discounting the problems of the status quo.

 

00:01:31.500 Furthermore, we’re starting to see automatic memory

00:01:34.367 management techniques that solve some of the

00:01:37.233 problems with older approaches. New garbage collection

00:01:40.100 algorithms have lower overheads and are more

00:01:42.967 predictable. And systems have gotten faster,

00:01:45.424 making the overheads of existing algorithms more

00:01:48.290 acceptable.

 

00:01:48.800 And different approaches, such as region-based memory

00:01:52.483 management, are starting to see widespread use,

00:01:56.165 and offer more predictability and stronger compile-time

00:01:59.848 behaviour guarantees.

 

00:02:01.000 For many systems programs, it may be

00:02:03.625 time to reconsider the cost-benefit tradeoff for

00:02:06.250 automatic memory management, to see if the

00:02:08.875 balance has shifted.

 

00:02:11.500 Systems programs traditionally used a mix of

00:02:15.233 manual and automatic memory management.

 

00:02:18.000 The memory used for the stack is

00:02:20.991 managed automatically.

00:02:21.845 In the sample code on the slide,

00:02:24.936 for example, the memory for the local

00:02:27.927 variable, di, in the saveDataForKey() function is

00:02:30.918 automatically allocated when the function is called,

00:02:33.909 and automatically freed when the function returns.

 

00:02:37.000 This is so common that we don’t

00:02:39.482 even think about it.

 

00:02:41.000 Stack-based memory management, in this form,

00:02:43.483 works extremely well for languages like C

00:02:46.381 and C++ that support complex value types.

00:02:49.278 That is, for languages that can put

00:02:52.175 structs on the stack and pass them

00:02:55.072 by value.

 

00:02:56.000 It works less well for languages like

00:02:58.513 Java, where objects are heap allocated.

00:03:00.667 In Java, the variable, di, would be

00:03:03.180 a reference to a heap allocated object,

00:03:05.693 which would need to be garbage collected.

00:03:08.207 Only the reference to that object would

00:03:10.720 be stored on the stack. While,

00:03:12.874 in C and C++, the entire object

00:03:15.387 can be efficiently managed on the stack.

 

00:03:18.000 The stack in C and C++ is

00:03:20.950 an example of successful automatic memory management.

 

00:03:24.000 The heap, on the other hand,

00:03:26.250 is generally managed manually. Allocation is by

00:03:28.875 a call to malloc(). Deallocation, if the

00:03:31.500 programmer remembers to do so, is by

00:03:34.125 an explicit call to free().

 

00:03:38.000 It would be good to have an

00:03:40.531 effective and automatic way of managing the

00:03:43.062 heap. Something that’s as simple, efficient,

00:03:45.231 and effective as managing the stack.

 

00:03:47.500 The goal of automatic memory management is

00:03:49.632 to manage the heap. To find memory

00:03:51.764 that’s no longer in use, and make

00:03:53.895 that space available for reuse. To look

00:03:56.027 for objects that are no longer referenced

00:03:58.159 by the running program, and to free

00:04:00.291 their memory.

 

00:04:01.000 And to do so efficiently and automatically.

 

00:04:05.000 And to do so safely. It’s better

00:04:07.347 to waste memory, and to keep an

00:04:09.694 object alive when it shouldn’t be,

00:04:11.706 than to deallocate the memory used by

00:04:14.053 an object that’s potentially still in use.

 

00:04:16.500 There are three approaches to automatically managing

00:04:19.922 the heap.

 

00:04:21.000 The first is reference counting, that I’ll

00:04:23.541 discuss in a minute.

00:04:24.993 The second is region-based lifetime tracking,

00:04:27.270 that I’ll discuss in the next part

00:04:29.811 of this lecture.

 

00:04:31.000 And the third is to use garbage

00:04:33.500 collection, that I’ll discuss in lecture 6.

 

00:04:37.500 The first of the automatic memory management

00:04:40.364 techniques is reference counting.

 

00:04:43.500 Reference counting is simple and easy to

00:04:46.288 understand.

00:04:47.436 When allocating memory for an object,

00:04:49.926 the allocation contains additional space for a

00:04:52.714 reference count that’s stored along with the

00:04:55.502 object.

 

00:04:55.250 That is, every object has a hidden

00:04:58.106 extra field, large enough to hold an

00:05:00.963 integer value, that’s stored alongside the object

00:05:03.819 and managed by the runtime system,

00:05:06.268 invisibly to the programmer.

 

00:05:08.000 This extra field containS a reference count.

00:05:10.409 It counts how many other objects have

00:05:12.819 a pointer, a reference, to this object.

00:05:15.228 When a heap allocated object is created,

00:05:17.737 the reference count is set to one,

00:05:20.147 and a reference to the object is

00:05:22.556 returned.

 

00:05:23.000 When a new reference, a new pointer,

00:05:25.530 to the object is made, then the

00:05:28.059 reference count is increased by one.

00:05:30.227 When a reference is removed or changed,

00:05:32.757 so that it no longer points to

00:05:35.286 the object, then the reference count is

00:05:37.816 decreased by one.

 

00:05:39.000 If the reference count reaches zero,

00:05:41.054 then there are no references left that

00:05:43.450 point to the object, and it may

00:05:45.846 be reclaimed, and it’s memory deallocated.

 

00:05:48.000 If an object that contains references to

00:05:50.931 other objects is reclaimed, this removes a

00:05:53.862 reference to those objects. Doing so potentially

00:05:56.794 causes their reference counts to go to

00:05:59.725 zero, triggering further reclamation.

 

00:06:01.500 The reference counts are maintained automatically.

00:06:04.093 In a compiled language with reference counting,

00:06:07.119 such as the Objective C runtime used

00:06:10.144 in iPhones, then the compiler generates the

00:06:13.169 code to manage references and reclaim objects

00:06:16.195 when pointers are manipulated. In an interpreted

00:06:19.220 language with reference counting, such as Python

00:06:22.246 or Ruby, the interpreter updates the references

00:06:25.271 and reclaims the objects.

 

00:06:29.000 The key benefit of reference counting is

00:06:31.858 that it’s predictable and understandable.

 

00:06:34.000 It’s easy to explain how reference counting

00:06:37.413 works.

 

00:06:38.000 It’s easy to understand when memory is

00:06:40.415 reclaimed, and what actions in a program

00:06:42.830 might trigger memory to be reclaimed.

 

00:06:45.000 It’s easy to understand what is the

00:06:47.275 overhead and what is the cost.

00:06:49.225 It’s one additional integer per object;

00:06:51.175 an increment of a reference count when

00:06:53.450 taking a pointer to an object;

00:06:55.400 and a decrement of a reference count,

00:06:57.675 an if statement, and a potential call

00:06:59.950 to free() when removing a reference.

 

00:07:02.000 The behaviour is intuitive to programmers –

00:07:04.638 and that counts for a lot.

 

00:07:07.000 Reference counting is also incremental. Memory is

00:07:09.561 reclaimed in small bursts, and the costs

00:07:12.122 that occur are an occasional small overhead

00:07:14.683 on pointer operations. There are few long

00:07:17.244 bursts of memory management activity, and it’s

00:07:19.805 clear what might trigger such bursts.

 

00:07:24.000 Reference counting also has some costs.

00:07:28.000 Cyclic data structures can be produced that

00:07:30.414 contain mutual references. That is, a set

00:07:32.829 of objects can reference each other in

00:07:35.243 a loop, such that the objects are

00:07:37.657 all reachable from some other object,

00:07:39.727 so the reference count never reaches zero,

00:07:42.141 but not from the rest of the

00:07:44.555 program.

 

00:07:45.000 This can lead to a disconnected set

00:07:47.212 of objects, unreachable from the rest of

00:07:49.424 the code, that aren’t reclaimed because they

00:07:51.636 have non-zero reference counts.

 

00:07:53.000 That is, it can leak memory.

 

00:07:56.500 The programmer needs to notice, and explicitly

00:07:59.053 set one of the references to null,

00:08:01.606 to break the cycle before removing the

00:08:04.159 last other pointer to the objects.

00:08:06.347 Only then will the objects be reclaimed.

 

00:08:09.000 Reference counting stores a reference count alongside

00:08:11.543 each object, as an additional hidden field.

00:08:14.087 If the objects can be accessed concurrently,

00:08:16.630 it may also need a mutex for

00:08:19.173 each object.

 

00:08:20.000 This uses additional memory. And can be

00:08:22.581 quite a high overhead if the objects

00:08:25.163 are small.

 

00:08:26.000 And the processor cost of updating the

00:08:28.154 references can be moderately high, if the

00:08:30.308 program manipulates pointers a lot, of if

00:08:32.462 the objects don’t live long.

 

00:08:36.000 Despite these limitations, reference counting is widely

00:08:39.500 used.

 

00:08:40.000 It’s common in scripting languages, such as

00:08:42.665 Python or Ruby, where the overhead of

00:08:45.331 using an interpreted language far outweighs the

00:08:47.996 overhead of using reference counting.

 

00:08:50.000 It’s also used for some aspects of

00:08:53.811 systems programming.

 

00:08:55.000 Applications for the iPhone and Mac are

00:08:57.739 typically written in the Objective C language.

00:09:00.478 This is an object oriented extension to

00:09:03.217 C that uses reference counting to manage

00:09:05.957 the memory allocated to objects. And it’s

00:09:08.696 actually highly optimised and reasonably high performance.

00:09:11.435 Reference counting has always been fast enough

00:09:14.174 for user interface code and much application

00:09:16.913 logic. It’s not used for low-level,

00:09:19.261 in-kernel, code, where performance is critical,

00:09:21.609 though.

 

00:09:23.000 That concludes our discussion of reference counting.

00:09:25.705 It’s a simple, and reasonably effective automatic

00:09:28.411 memory management scheme, that’s quite widely used.

00:09:31.116 In the next part, I’ll move on

00:09:33.922 to discuss an alternative known as region-based

00:09:36.627 memory management.

Part 3: Region-based Memory Management

The third part of the lecture introduces the concept of region-based memory management. It describes the concepts and rationale behind this approach, and how it builds on the way the stack is managed. And it describes the benefits and limitations of region-based approaches to memory management, such as that employed by Rust. The concept of ownership tracking is introduced.

00:00:00.000 In this part, I want to introduce

00:00:03.065 region-based memory management, and discuss how it’s

00:00:05.130 used to manage memory in Rust.

 

00:00:08.000 Region-based memory management is a new way

00:00:10.800 of managing memory that grew out of

00:00:13.600 frustrations with the alternatives.

00:00:15.200 Reference counting, as we saw in the

00:00:18.100 last part, is simple and easy to

00:00:20.900 understand, but has relatively high overhead.

00:00:23.300 It takes space to store the reference

00:00:26.100 counts, and time to update them.

00:00:28.500 And while this overhead is okay for

00:00:31.300 most applications, it’s too much for performance-critical

00:00:34.100 systems code.

 

00:00:35.000 Garbage collection, which I’ll talk about in

00:00:37.930 detail in the next lecture, has unpredictable

00:00:40.859 timing and high memory overheads.

00:00:42.952 And manual memory management is too error

00:00:45.981 prone.

 

00:00:46.500 Region-based memory management aims for the middle

00:00:49.093 ground between these.

00:00:50.205 It aims to be safe and offer

00:00:52.898 predictable timing. And it has no run-time

00:00:55.491 cost, compared to manual memory management.

00:00:57.714 But, to achieve this, it forces some

00:01:00.407 changes in the way code is written.

 

00:01:05.000 So what is region-based memory management?

00:01:07.800 Well, to understand that, let’s first recap

00:01:11.167 the way memory is managed on the

00:01:14.433 stack.

 

00:01:15.000 The slide shows a simple C program.

00:01:18.237 This comprises two functions: main() and conic_area(),

00:01:21.575 where the conic_area() function implements a mathematical

00:01:24.812 formula to calculate the surface area of

00:01:28.050 a right circular cone.

 

00:01:30.000 There’s one global static variable, holding the

00:01:33.117 value of Pi.

00:01:34.452 The main() function takes no parameters,

00:01:37.224 and hold local variables width, height,

00:01:39.895 and area.

00:01:40.786 And the conic_area() function takes two parameters,

00:01:44.002 w and h, and hold the local

00:01:47.119 variables r and a.

 

00:01:49.000 The diagram on the right shows the

00:01:51.703 memory regions owned by the program,

00:01:54.019 while the conic_area() function is executing.

00:01:56.336 We see there’s a region holding the

00:01:59.139 global variables, and sub-regions for the stack

00:02:01.842 frame for main() and for the conic_area()

00:02:04.544 functions. These nest, one within the other,

00:02:07.247 with the global region lasting for the

00:02:09.950 entire duration of the program, and the

00:02:12.653 other regions nesting within, and lasting for

00:02:15.356 part of the time.

 

00:02:17.000 The lifetime of the local variables and

00:02:20.138 function parameters matches that of the stack

00:02:23.276 frames of the functions holding them.

00:02:25.966 Memory is allocated and deallocated automatically,

00:02:28.655 efficiently, and seamlessly.

 

00:02:32.000 Essentially, there’s a hierarchy of regions corresponding

00:02:34.491 to the call stack of the program.

00:02:36.981 The lifetime of the global variables is

00:02:39.572 that of the entire program, and the

00:02:42.063 lifetime of the local variables matches the

00:02:44.553 execution time of the functions they live

00:02:47.044 within.

 

00:02:47.500 And, within each function, we see there

00:02:49.917 may be lexically scoped variables that have

00:02:52.334 a lifetime less than that of the

00:02:54.751 enclosing function.

00:02:55.442 In the code on the slide,

00:02:57.613 for example, we see that the variable

00:03:00.030 i, the index variable in the for

00:03:02.447 loop, lives only for the duration of

00:03:04.864 that for loop.

 

00:03:06.000 Each of these variables lives within a

00:03:08.561 region, scoped by the program code,

00:03:10.757 and is automatically allocated when entering that

00:03:13.318 region, and deallocated when the program leaves

00:03:15.880 the region.

00:03:16.611 This works seamlessly. So much so that

00:03:19.273 we take it for granted when writing

00:03:21.834 code.

 

00:03:25.000 There’s one limitation of this stack-based approach

00:03:27.874 to memory management.

00:03:29.105 It requires data to be allocated on

00:03:32.079 the stack.

 

00:03:33.000 In the example on this slide,

00:03:35.452 the variable tmp lives on the stack

00:03:38.312 frame for the hostname_matches() function. Space for

00:03:41.172 the variable is created when the function

00:03:44.033 starts to execute, and freed when the

00:03:46.893 function concludes.

00:03:47.710 But that’s only the memory that holds

00:03:50.671 tmp.

00:03:51.829 That is, the memory for the local

00:03:54.790 variable holding the pointer is managed automatically.

 

00:03:57.000 The heap allocated memory, the memory allocated

00:04:00.238 by the call to malloc(), is not

00:04:03.475 freed automatically.

 

00:04:04.500 When tmp goes out of scope,

00:04:06.635 the space holding the pointer is freed,

00:04:09.126 but the value it points to is

00:04:11.616 not.

00:04:12.722 The program doesn’t call free() to deallocate

00:04:15.313 that memory, and it doesn’t return the

00:04:17.803 pointer so some other function can do

00:04:20.294 so.

 

00:04:20.000 It leaks memory. The pointer is gone,

00:04:22.739 so there’s no remaining reference to the

00:04:25.478 allocated memory, so no way to free

00:04:28.217 that memory.

 

00:04:31.000 Stack-based memory management is clearly effective,

00:04:33.633 but has limited applicability. Can we extend

00:04:36.706 it to manage the heap?

 

00:04:39.000 Yes. We can arrange for the compiler

00:04:41.468 to track the lifetime of data,

00:04:43.584 and in the same way that it

00:04:46.053 inserts code to manage the stack,

00:04:48.168 it can insert code to manage heap

00:04:50.637 memory based on object lifetimes.

 

00:04:52.500 If we arrange the code so that

00:04:54.546 there’s a single clear owner of every

00:04:56.592 data value, then we can arrange it

00:04:58.638 so that if a pointer goes out

00:05:00.685 of scope, then the value it points

00:05:02.731 to is also freed.

 

00:05:04.000 This requires us to track ownership of

00:05:06.633 all data objects, but as we saw

00:05:09.267 in the last lecture, Rust does this.

 

00:05:12.000 The idea then it to define the

00:05:14.603 Box-of-T type, which is a value that’s

00:05:17.206 stored on the stack that holds a

00:05:19.809 reference to data of type T that’s

00:05:22.412 allocated on the heap.

 

00:05:24.000 Calling Box::new() allocates and populates heap memory,

00:05:26.914 and returns a pointer to that memory

00:05:29.828 that’s stored in a local variable on

00:05:32.742 the stack. The resulting local variable is

00:05:35.656 a normal variable, with lifetime matching that

00:05:38.570 of the stack frame in which it

00:05:41.484 resides.

 

00:05:42.000 And the heap allocated object has lifetime

00:05:44.638 matching that of the Box too.

 

00:05:47.000 When the local variable holding the Box

00:05:49.819 goes out of scope, its destructor is

00:05:52.638 automatically called by the compiler. The destructor

00:05:55.457 frees the heap allocated memory. This is

00:05:58.276 the basis for region based memory management

00:06:01.095 in Rust.

 

00:06:02.000 It’s highly efficient. And it safety manages

00:06:05.204 heap memory. But it loses generality,

00:06:07.950 since it ties the lifetime of heap

00:06:11.154 allocation to that of stack frames.

 

00:06:14.000 If you’ve programmed C++, this approach will

00:06:17.379 be familiar as the RAII – Resource

00:06:20.759 Acquisition Is Initialization – design pattern.

00:06:23.655 Python also does something similar in its

00:06:27.034 “with” clauses.

 

00:06:31.000 Rust takes the pattern further though.

00:06:33.564 To be effective, region-based memory management has

00:06:36.655 to not just tie object lifetimes to

00:06:39.645 stack frames, but also to track how

00:06:42.636 objects are passed between stack frames.

 

00:06:45.300 And do so in a way that

00:06:47.447 maintains the single owner invariant for every

00:06:49.593 object.

 

00:06:50.000 At every point, the compiler must know

00:06:52.854 what region of code owns each piece

00:06:55.708 of data. And as data is passed

00:06:58.562 between functions, as ownership of the data

00:07:01.415 is passed between functions, the compiler must

00:07:04.269 track that data ownership.

 

00:07:06.000 And, when the data item finally goes

00:07:08.250 go out of scope, after its ownership

00:07:10.500 has been passed between various functions,

00:07:12.429 only then should it deallocate the heap

00:07:14.679 memory.

 

00:07:17.500 As we saw in the last lecture,

00:07:20.067 Rust tracks ownership of data items as

00:07:22.633 they’re passed between functions.

00:07:24.100 The code on the slide is the

00:07:26.767 Rust equivalent of the C program we

00:07:29.333 saw earlier, to calculate the conic area.

 

00:07:32.000 If we look at the lifetimes of

00:07:34.479 the variables in the function area_of_cone(),

00:07:36.604 we see that the variable, r,

00:07:38.729 has lifetime matching that of the function’s

00:07:41.208 stack frame. It’s allocated when the function

00:07:43.688 starts to execute, and goes out of

00:07:46.167 scope and is freed when the function

00:07:48.646 finishes.

 

00:07:49.000 The variable, a, though is created within

00:07:51.800 the area_of_cone() but then returned from that

00:07:54.600 function. Ownership of the value is passed

00:07:57.400 from that function to its caller,

00:07:59.800 the main() function. And from there,

00:08:02.200 it’s passed as an argument to the

00:08:05.000 println!() macro, that consumes the value.

 

00:08:07.500 The key point is that the lifetime

00:08:10.387 of the value initially stored in the

00:08:13.275 local variable, a, in the area_of_cone() function,

00:08:16.162 outlives that function.

 

00:08:17.500 And the compiler tracks this lifetime.

00:08:19.573 It knows that the ownership has changed.

00:08:22.091 That the value has been passed out

00:08:24.509 of the function into main(), and is

00:08:26.927 later consumed by the println!() call.

 

00:08:30.500 We see that ownership of the return

00:08:33.023 value is moved to the calling function.

00:08:35.546 The value is moved into the stack

00:08:38.169 frame of the calling function, and assigned

00:08:40.692 to a local variable. And the original

00:08:43.215 value, in the called function’s stack frame,

00:08:45.738 is destroyed when that function returns.

 

00:08:48.000 If the value being moved is a

00:08:50.426 Box, what’s moved is the Box itself.

00:08:52.851 That is, the smart pointer to the

00:08:55.277 heap allocated memory is moved into the

00:08:57.702 stack frame of the caller. The value

00:09:00.128 on the heap that it references is

00:09:02.553 unchanged.

 

00:09:03.000 Similarly, if a reference is returned,

00:09:06.337 it’s the reference that’s moved. The referenced

00:09:10.231 value is unchanged.

 

00:09:12.000 Any variable not returned by a function

00:09:14.683 goes out of scope and is destroyed

00:09:17.367 when the function returns.

 

00:09:19.000 What does this mean? The destructor for

00:09:22.150 the type, the drop() method, is called.

00:09:25.300 Then the memory holding the object is

00:09:28.450 deallocated.

 

00:09:29.000 If the value going out of scope

00:09:31.154 is a Box, the destructor for the

00:09:33.308 box calls the destructor for the heap

00:09:35.462 allocated object, then frees the heap memory.

00:09:37.615 Since every object goes out of scope

00:09:39.769 eventually, when it reaches the end of

00:09:41.923 its lifetime, since ensures that all heap

00:09:44.077 memory is freed.

 

00:09:48.000 Since the Rust compiler tracks the lifetime

00:09:51.019 of every object, it can prevent common

00:09:54.037 lifetime-related errors.

 

00:09:55.000 For example, the Rust program shown on

00:09:57.495 the top of this slide is a

00:09:59.990 function that tries to return a reference

00:10:02.485 to a local variable. This isn’t possible,

00:10:04.979 since the local variable ceases to exist

00:10:07.474 once the function returns.

 

00:10:09.000 The compiler notices this, and as we

00:10:11.725 see, the code doesn’t compile. You can’t

00:10:14.450 return a reference to, that is,

00:10:16.786 borrow, a value that doesn’t exist any

00:10:19.511 more.

 

00:10:20.000 The equivalent C program, shown on the

00:10:22.772 bottom of the slide, will compile just

00:10:25.544 fine, but crash at runtime when the

00:10:28.316 returned pointer is used.

 

00:10:30.000 Good C compilers warn about this,

00:10:32.217 in simple cases like this example,

00:10:34.435 but will compile more complex variants of

00:10:37.022 the code without warnings.

 

00:10:41.000 Similarly, because the Rust compiler tracks object

00:10:43.829 lifetimes, it can prevent you from accessing

00:10:46.657 memory once it’s been freed.

00:10:48.678 The Rust code shown at the top

00:10:51.606 of the slide shows an example.

00:10:54.031 It imports and explicitly calls the drop()

00:10:56.859 function, to force the local variable,

00:10:59.284 x, to be deallocated.

 

00:11:01.000 Calling drop() manually is never explicitly needed

00:11:03.826 in Rust, but is possible, and has

00:11:06.652 the same effect as calling free() to

00:11:09.478 deallocate memory in a C program.

 

00:11:12.000 The Rust code on the slide,

00:11:14.413 that deallocates memory then tries to print

00:11:17.228 out the contents of the just-deallocated memory,

00:11:20.043 fails to compile. The compiler knows that

00:11:22.857 the drop() call consumes the object and

00:11:25.672 that its lifetime ends. It knows that

00:11:28.487 the value cannot then be accessed.

 

00:11:31.000 The equivalent C program, shown at the

00:11:33.917 bottom, will compile without warnings, but has

00:11:36.833 undefined behaviour at runtime since it accesses

00:11:39.750 previously freed memory.

 

00:11:44.000 In addition to returning ownership of data,

00:11:46.543 functions can take ownership of a value.

00:11:49.087 When a value is passed to a

00:11:51.730 function, that function takes ownership of that

00:11:54.273 value. We see this in the code

00:11:56.817 on the slide, where the consume() function

00:11:59.360 takes ownership of the local variable,

00:12:01.540 a, from the main() function, in the

00:12:04.083 form of its parameter, x.

 

00:12:06.000 And, as usual, once the consume() function

00:12:08.300 ends, the values of any data it

00:12:10.600 owns that are not returned, as destroyed.

 

00:12:13.000 We see this when we try to

00:12:15.567 compile the code. The main() function can’t

00:12:18.133 access the local variable, a, to print

00:12:20.700 its length, since it doesn’t own the

00:12:23.267 value anymore. It gave ownership to the

00:12:25.833 consume() function, and that function destroyed the

00:12:28.400 value and didn’t pass it back.

00:12:30.600 Accordingly, it’s no longer accessible in main()

00:12:33.167 and the code won’t compile.

 

00:12:37.000 That concludes this introduction to region-based memory

00:12:39.752 management.

00:12:40.895 The key insight is that if every

00:12:43.748 value has a unique owner, and the

00:12:46.500 compiler tracks ownership and the lifetime of

00:12:49.252 those values, then every value can be

00:12:52.005 automatically freed at the end of its

00:12:54.757 lifetime.

 

00:12:54.500 This is the key difference between Rust

00:12:57.008 and other programming languages. The Rust compiler

00:12:59.517 knows when a value has been consumed,

00:13:02.025 when it’s reached the end of its

00:13:04.533 lifetime, and will enforce this at compile

00:13:07.042 time.

 

00:13:07.500 Other languages either don’t track lifetimes,

00:13:10.009 like C, and potentially allow use after

00:13:12.936 free bugs, dangling references, and so on.

00:13:15.864 Or they use some form of garbage

00:13:18.791 collection, to track liveness of data at

00:13:21.718 run time. They’re either unsafe, or have

00:13:24.645 run time overhead.

 

00:13:26.000 Rust is both safe, and avoids the

00:13:29.033 run-time overheads.

 

00:13:30.000 But to achieve this, Rust restricts the

00:13:32.304 set of programs that can be expressed,

00:13:34.608 as we’ll see in the next part

00:13:36.913 of this lecture.

Part 4: Borrowing and Resource Management

The final part of the lecture discusses how region-based memory management can be extended to include resource management. It further expands on the concept of ownership tracking, introduced in the previous part of the lecture, and shows how Rust supports borrowing of data to make region-based memory management feasible. It outlines the limitations of region-based memory management and how it limits the classes of program that can be written, and discusses the trade-off this imposes. And it reviews how region-based management can be used to enforce deterministic resource clean-up.

00:00:00.000 In this final part of the lecture,

00:00:03.235 I’ll talk about how Rust extends ownership

00:00:05.471 with the idea of borrowing, and how

00:00:07.706 this can apply to management of resources

00:00:09.942 other than memory.

 

00:00:12.000 We saw in the previous part that

00:00:14.508 functions can pass ownership of data between

00:00:17.017 them. We saw how functions take ownership

00:00:19.525 of data they’re passed, and how they

00:00:22.033 can return ownership of data to their

00:00:24.542 caller.

 

00:00:25.000 We discussed how this relates to memory

00:00:27.319 management, with memory being freed when an

00:00:29.638 object goes out of scope at the

00:00:31.956 end of a function. And, we showed

00:00:34.275 how, with the aid of single ownership

00:00:36.594 rules, Rust can leverage this to provide

00:00:38.913 an automatic region-based memory management scheme.

 

00:00:41.000 This can work, but repeatedly passing and

00:00:44.259 returning ownership of data to and from

00:00:47.519 functions is inconvenient. To make this easier,

00:00:50.778 Rust augments the ownership rules with the

00:00:54.037 idea of borrowed data.

 

00:00:56.000 Functions in Rust can take references to

00:00:58.848 data as parameters. For example, in the

00:01:01.695 slide we see the function borrow() that

00:01:04.543 takes a mutable reference to a vector,

00:01:07.391 x, as its parameter, and modifies the

00:01:10.239 vector, by pushing a new element onto

00:01:13.086 the end.

 

00:01:14.000 In the main() function, we create a

00:01:16.492 vector, add some data to it,

00:01:18.628 call the borrow() function, and then print

00:01:21.120 the length of the vector.

 

00:01:23.000 Unlike the case we saw in the

00:01:25.225 last part, where the function consumed the

00:01:27.450 vector, in this case the vector is

00:01:29.675 still accessible after the call to borrow().

 

00:01:32.000 Why is this?

 

00:01:34.000 Because borrow() is passed data by reference.

 

00:01:39.000 The borrow() function is passed, takes ownership

00:01:41.940 of, a reference to the vector.

00:01:44.460 It doesn’t take ownership of the vector.

 

00:01:47.500 When the borrow() function returns, the lifetime

00:01:50.195 of the parameter x ends, and it

00:01:52.890 is reclaimed in the usual way.

00:01:55.200 The function has taken ownership of that

00:01:57.895 parameter, and hasn’t returned ownership to the

00:02:00.590 caller, so the data is freed.

 

00:02:03.000 But, what it took ownership of was

00:02:05.561 a reference to the vector, not the

00:02:08.121 vector itself. So what is freed is

00:02:10.682 the reference, not the vector. Ownership of

00:02:13.242 the vector remains with the main() function

00:02:15.803 at all times.

 

00:02:17.000 This is known as borrowing a reference.

 

00:02:21.000 It’s not shown on the slide,

00:02:22.745 but a function that takes a reference

00:02:24.782 as a parameter can return that reference

00:02:26.818 to the caller. This is safe,

00:02:28.564 because the reference had to be accessible

00:02:30.600 to the caller – otherwise, how could

00:02:32.636 it pass it to the function –

00:02:34.673 so the returned reference will also be

00:02:36.709 accessible.

 

00:02:39.000 In this example, the borrow() function changes

00:02:41.709 the contents of the vector. It pushes

00:02:44.417 a new element onto the end of

00:02:47.126 the vector.

 

00:02:48.000 And in this case, it’s safe for

00:02:49.845 it to do so.

 

00:02:51.000 But this is not always safe.

 

00:02:54.000 For example, if main() was iterating over

00:02:56.731 the contents of the vector, and passed

00:02:59.463 a mutable reference to that vector to

00:03:02.194 a function that modified it, while the

00:03:04.925 iteration was in progress, this might lead

00:03:07.657 to elements being skipped or duplicated,

00:03:09.998 or to a result to be calculated

00:03:12.729 with inconsistent data.

 

00:03:14.000 This is a problem known as iterator

00:03:16.625 invalidation.

 

00:03:19.000 To avoid iterator invalidation, and other problems,

00:03:22.179 references in Rust come in two different

00:03:25.358 types, and have restrictions on how they

00:03:28.538 can be used.

 

00:03:30.000 Rust has two different types of pointer;

00:03:32.858 two different types of reference.

 

00:03:35.000 The first is written &T, and is

00:03:38.253 a shared reference to an immutable object

00:03:41.506 of type T.

 

00:03:43.000 The second is written &mut T,

00:03:45.633 and is a unique reference to a

00:03:48.706 mutable object of type T.

 

00:03:51.000 The Rust compiler and runtime system work

00:03:53.772 together to control how references can be

00:03:56.544 used, and to track ownership of references

00:03:59.316 and the referenced values.

 

00:04:01.000 There are three fundamental rules.

 

00:04:05.000 An object of type T can be

00:04:07.848 referenced by one or more references of

00:04:10.695 type &T. Or it can be referenced

00:04:13.543 by exactly one reference of type &mut

00:04:16.391 T. But it’s not possible to have

00:04:19.239 both mutable and immutable references to the

00:04:22.086 same object.

 

00:04:23.000 If an object is defined to be

00:04:25.683 immutable, it’s not possible to take a

00:04:28.367 mutable reference to it.

 

00:04:30.000 And it an object is defined to

00:04:32.826 be mutable, then taking an immutable reference

00:04:35.652 to that object makes it immutable for

00:04:38.478 the duration of the immutable reference.

 

00:04:41.000 These restrictions complicate how pointers work in

00:04:43.911 Rust. And they limits the set of

00:04:46.821 programs its possible to write.

 

00:04:49.000 But they allow functions to safely borrow

00:04:52.450 objects, without needing to give away ownership.

 

00:04:56.000 In a Rust program, to be able

00:04:58.304 to change an object, you must either

00:05:00.608 own the object, and it not be

00:05:02.913 marked as immutable.

 

00:05:04.000 Or you must own the only &mut

00:05:07.430 reference to it.

 

00:05:09.000 These rules prevent iterator invalidation.

 

00:05:13.000 Iterators in Rust are designed to take

00:05:15.815 an immutable reference to the object over

00:05:18.630 which they iterate. This guarantees that the

00:05:21.445 object can’t change, and that no mutable

00:05:24.260 references to the object can exist.

00:05:26.672 If the object being iterated over cannot

00:05:29.487 change, the iterator cannot be invalidated.

 

00:05:32.000 The compiler checks and enforces these rules.

 

00:05:37.000 By tracking ownership, and controlling how pointers

00:05:40.622 are used, Rust turns various issues that

00:05:44.243 are run-time bugs in other languages into

00:05:47.865 compile-time errors.

 

00:05:49.000 Rust prevents use-after-free bugs by making it

00:05:52.279 impossible to return references to data that

00:05:55.558 outlive the data being referenced.

 

00:05:58.000 Rust prevents iterator invalidation, by making it

00:06:01.095 impossible to change the object being iterated

00:06:04.189 over whilst the iterator exists.

 

00:06:06.500 And Rust prevents race conditions between multiple

00:06:09.010 threads, because the rules about pointers make

00:06:11.521 it impossible for two threads to each

00:06:14.031 have a mutable reference to the same

00:06:16.541 object.

 

00:06:17.000 All these behaviours are checked at compile

00:06:21.288 time.

 

00:06:22.000 And Rust has efficient run-time behaviour.

 

00:06:25.000 The Rust compiler generates exactly the same

00:06:27.745 code to allocate and free memory as

00:06:30.489 would a correctly written C program using

00:06:33.234 malloc() and free(). The difference is that

00:06:35.979 the compiler ensures the malloc() and free()

00:06:38.724 calls are correct.

 

00:06:40.000 As a result the timing and memory

00:06:43.115 usage of Rust code as a predictable

00:06:46.230 as a correctly written C program.

 

00:06:49.000 Rust is deterministic in when memory is

00:06:51.545 both allocated and freed.

 

00:06:56.000 The region-based approach to memory management used

00:06:59.177 by Rust has some limitations though.

 

00:07:02.000 Primarily, Rust ensures correctness by limiting the

00:07:05.220 types of program that it’s possible to

00:07:08.440 write.

 

00:07:09.000 The rules about ownership and borrowing make

00:07:11.841 it impossible to express certain data structures

00:07:14.682 in safe Rust.

 

00:07:16.000 For example, it’s not possible to write

00:07:19.019 code that uses data structures that contain

00:07:22.038 reference cycles.

 

00:07:23.000 The canonical example of this is that

00:07:25.364 it’s not possible to write a doubly

00:07:27.728 linked list in safe Rust. If you

00:07:30.092 look at the example of the slide,

00:07:32.457 where you have a list containing elements

00:07:34.821 a, b, and c, you’ll see that

00:07:37.185 it’s not possible to add an element,

00:07:39.549 d, to the end.

 

00:07:41.000 You can take an immutable reference to

00:07:43.441 element c, and add it to element

00:07:45.881 d. This works, since Rust allows two

00:07:48.322 immutable references to C to exist –

00:07:50.762 one from element b and one from

00:07:53.203 element d.

 

00:07:54.000 What you can’t do, it take a

00:07:56.679 mutable reference to element c, in order

00:07:59.358 to modify it to add a reference

00:08:02.037 to element d. This is because there’s

00:08:04.715 already an immutable reference to element c,

00:08:07.394 held by element b, and you can’t

00:08:10.073 have both mutable and immutable references to

00:08:12.752 the same object.

 

00:08:14.000 The restrictions on references that prevent race

00:08:17.072 conditions, iterator invalidation, and so on,

00:08:19.706 also prevent cyclic data structures.

 

00:08:22.000 And it’s not just doubly linked lists.

00:08:25.072 They prevent any data structure that contains

00:08:28.144 a loop of pointers.

 

00:08:30.000 It’s a fundamental limitation of the way

00:08:33.253 references work in Rust. It trades expressive

00:08:36.506 power for safety.

 

00:08:38.000 The designers of Rust recognised this,

00:08:40.673 and added an escape hatch.

 

00:08:43.000 Rust also has a third type of

00:08:46.177 reference, known as a raw pointer.

 

00:08:49.000 Raw pointers work just like pointers in

00:08:51.588 C. They allow you to circumvent the

00:08:54.177 restrictions that Rust imposes on mutable and

00:08:56.765 immutable references, and make it possible to

00:08:59.353 write cyclic data structures in exactly the

00:09:01.942 same way you would do so in

00:09:04.530 C.

 

00:09:05.000 Of course, by allowing you to circumvent

00:09:07.815 these restrictions, you lose the safety guarantees

00:09:10.630 of Rust. A Rust program that uses

00:09:13.445 raw pointers is as likely to suffer

00:09:16.260 from memory safety issues, such as use

00:09:19.074 after free bugs, iterator invalidation, and race

00:09:21.889 conditions, as a C program.

 

00:09:24.000 To make this clear, Rust requires use

00:09:27.225 of raw pointers to be explicitly labelled

00:09:30.450 as unsafe. It warns the programmer,

00:09:33.214 and makes it easy to find such

00:09:36.439 use.

 

00:09:37.000 There’s a second limitation of safe Rust,

00:09:39.683 which is that it can’t express shared

00:09:42.367 ownership of mutable data.

 

00:09:44.000 Shared ownership of immutable data is straight-forward.

00:09:47.300 It’s okay for many different references to

00:09:50.600 point to an object that cannot change.

 

00:09:54.000 Shared ownership of mutable data is problematic,

00:09:56.913 because it potentially open up race conditions.

00:09:59.826 This is why Rust only allows a

00:10:02.739 single mutable reference to a value to

00:10:05.652 exist at once.

 

00:10:07.000 But, occasionally, rarely, you need shared mutable

00:10:12.163 state.

 

00:10:13.000 If you do, Rust has a RefCell-of-T

00:10:15.969 type. This wraps some value of type

00:10:18.937 T, and dynamically enforces the borrowing rules.

00:10:21.906 That is, it allows callers to borrow,

00:10:24.874 or mutably borrow, the wrapped value,

00:10:27.419 and enforces at run time that there

00:10:30.387 can only me immutable borrows, or a

00:10:33.356 single mutable borrow, but not both.

 

00:10:36.000 The RefCell type provides essentially the same

00:10:38.679 guarantees as the regular Rust borrowing rules,

00:10:41.358 but enforced at run time rather than

00:10:44.037 at compile time. This means that attempts

00:10:46.715 to take, for example, several mutable references

00:10:49.394 to the wrapped object, will cause a

00:10:52.073 panic when the code executes, rather than

00:10:54.752 failing to compile.

 

00:10:56.000 The RefCell is safe, in that it

00:10:58.579 never causes undefined behaviour, but it can

00:11:01.158 cause a run time failure.

 

00:11:06.000 Possibly the biggest issue with region-based memory

00:11:09.052 management, though, is that it forces the

00:11:12.104 programmer to consider object ownership explicitly,

00:11:14.720 and early in the design.

 

00:11:17.000 To what extent this is a problem

00:11:19.908 depends, I think, on your background.

 

00:11:22.500 If you’re experienced at programming in C,

00:11:25.575 this tends to be a non-issue.

00:11:28.210 Writing correct C programs also requires careful

00:11:31.284 consideration of data ownership, to know what

00:11:34.359 functions malloc() data and what functions free()

00:11:37.433 that data. Rust essentially codifies and enforces

00:11:40.508 the rules that well-written C programs tend

00:11:43.582 to adopt anyway.

 

00:11:45.000 If you’re experience is rather in a

00:11:47.456 language like Java or Python, where the

00:11:49.912 use of a garbage collector or reference

00:11:52.368 counting hides a lot of the complexity

00:11:54.825 of memory management, then needing to start

00:11:57.281 to think about ownership is more of

00:11:59.737 a burden. In this case, programming effectively

00:12:02.193 in Rust may require a shift in

00:12:04.649 thinking.

 

00:12:07.000 That concludes our introduction to region-based memory

00:12:10.850 management.

 

00:12:11.500 This is one of the more unusual

00:12:14.300 features of Rust. It provides an efficient

00:12:17.100 and predictable way of managing memory,

00:12:19.500 and offers strong correctness guarantees that can

00:12:22.300 prevent many common bugs.

 

00:12:24.000 But it does so by constraining the

00:12:26.404 types of program that can be written,

00:12:28.809 and by making the programmer explicitly consider

00:12:31.213 data ownership.

 

00:12:32.000 It’s a trade-off that works well for

00:12:34.188 some types of problem, but less well

00:12:36.375 for others.

 

00:12:40.000 The ownership rules of Rust can also

00:12:42.858 be useful for resource management.

 

00:12:46.000 As we’ve seen, Rust tracks data ownership,

00:12:49.150 and deterministically frees heap allocated memory when

00:12:52.300 references to that memory go out of

00:12:55.450 scope.

 

00:12:56.000 Particular types can use this ownership tracking

00:12:59.279 to implement custom destructors that provide deterministic

00:13:02.558 clean-up of resources they own.

 

00:13:05.000 If a type implements the Drop trait,

00:13:07.433 then the runtime will call the drop()

00:13:09.865 method on instances of that type at

00:13:12.298 the end of their lifetime, when they

00:13:14.730 go out of scope. This allows those

00:13:17.163 instances to clean-up after themselves.

 

00:13:19.000 For example, the File class implements the

00:13:21.967 Drop trait to close the underlying file

00:13:24.933 when file objects go out of scope.

 

00:13:28.000 Python has special syntax for this,

00:13:30.438 as shown on the slide. In Rust,

00:13:33.281 much like in C++, the cleanup happens

00:13:36.125 naturally when the object goes out of

00:13:38.969 scope, without the explicit syntax.

 

00:13:43.000 Finally, as we saw in the discussion

00:13:46.468 of struct-based state machines in Lecture 4,

00:13:49.936 ownership tracking allows state transitions to be

00:13:53.405 enforced.

 

00:13:54.000 A state machine can be defined using

00:13:56.764 structs to represent the state, and to

00:13:59.528 hold any needed state variables. And state

00:14:02.292 transitions can be implemented by defining functions

00:14:05.056 on those structs that consume self,

00:14:07.426 and return a new state.

 

00:14:09.500 The slide shows an example, where methods

00:14:13.612 login() and disconnect() are implemented on an

00:14:17.725 UnauthenticatedConnection struct.

 

00:14:19.000 Note that both take self as their

00:14:22.225 first parameter, not &self. That is,

00:14:24.989 they take ownership of the struct on

00:14:28.214 which they’re implemented, rather than borrow that

00:14:31.439 struct.

 

00:14:32.000 This mean that they consume self.

00:14:34.529 They destroy the object on which they’re

00:14:37.479 called.

 

00:14:38.000 That is, they force the object representing

00:14:40.679 the state to be destroyed. And they

00:14:43.358 return ownership of a new object,

00:14:45.654 representing the new state of the system.

00:14:48.333 This forces the cleanup of any data

00:14:51.012 held by that state that’s not explicitly

00:14:53.690 copied to the new state. It enforces

00:14:56.369 a clean state transition.

 

00:14:58.000 The blog post linked talks about these

00:14:59.750 issues further, and I encourage you to

00:15:01.500 read it.

 

00:15:05.000 That concludes the first part of our

00:15:07.638 discussion of memory and resource management.

 

00:15:10.000 We’ve looked at how processes are stored

00:15:12.736 in memory. How reference counting works,

00:15:15.082 and what are its strengths and weaknesses.

00:15:17.818 And how region based memory management is

00:15:20.555 used in Rust as an alternative.

 

00:15:23.000 In the next lecture, we’ll move on

00:15:25.482 to discuss garbage collection.

Discussion

Lecture 5 focussed on resource ownership and memory management. It started by discussing how a process is laid out in memory, and what memory needs to be managed. Then, it moved on to discuss the problem of, and need for, automatic memory management in general terms, highlighting that systems programmers tend to distrust automatic memory management, yet suffer from the problems due to manual memory management.

The lecture then discussed reference counting. This is widely used in both scripting languages, such as Python or Ruby, and in the Objective-C runtime used on Apple's iPhone and Mac operating systems. It noted that reference counting is relatively easy to understand, in incremental, and is predictable, but suffers from relatively high overhead with small or short-lived objects, and cannot collect cyclic data structures.

The lecture then focussed on the region-based memory management scheme used by Rust. It noted that the language tracks ownership of data as it moves between functions, and deterministically cleans up heap allocated memory when the lifetime of an object ends. Region based memory management achieves good, predictable, performance, and provides a number of nice guarantees around absence of race conditions, use-after-free bugs, iterator invalidation, and so on. But it comes at the cost of making the type system considerably more complex, and in limiting the types of programs that can be expressed.

Discussion will focus, primarily, on how the region based memory management scheme works, and on its advantages and disadvantages. The goal is to understand whether you think the benefits outweigh the complexity introduced.