Copying in C++

We are going to talk about two special C++ methods, the copy constructor and the copy assignment operator. You will often hear about these in the context of the rule of three or the rule of five. We’re not going to cover either of these rules. Instead we’re going to focus on these two methods themselves. What are the copy constructor and assignment operator for? Why are there two different methods that seem to do the same thing? When do they get used?

The copy constructor is defined just like a normal constructor, except it takes a single argument, a constant reference to an object of that class. The copy assignment operator is defined as an overload of the = operator. Let’s define a trivial class called Bond, that has a single field, a constructor, a copy constructor and a copy assignment operator.

#include <iostream>

class Bond
{
private:
	double Rate;
public:
	Bond(double rate) : Rate(rate)
	{
                std::cout << "Constructing" << std::endl;
	}

        // copy assignment
       	Bond& operator=(const Bond& other)
	{
		std::cout << "Copy assigning" << std::endl;
		Rate = other.Rate;
		return *this;
	}

        // copy constructor
       	Bond(const Bond& other) : Rate(other.Rate)
	{
		std::cout << "Copy constructing" << std::endl;
	}
};

Suppose we run the following code:

Bond A(1.6);
Bond B(A);

You will see, “Constructing” printed to the terminal, followed by “Copy constructing”. Nothing surprising here, when we create Bond A, we use the normal constructor. However, when we create Bond B, we use the copy constructor.

Similarly, if we run the following code from a main method:

Bond A(1.6);
Bond B(1.2);
B = A;

This time we will see our “Constructing” message appear twice followed by “Copy Assigning”. That is exactly what you would expect, as we are clearly using the assignment operator to copy from the Bond A to the Bond B. Now you might think that the copy assignment method is used every time we use the = operator to copy Bond objects. However it is not! Let’s say we ran the following code from a main method:

Bond A(1.6);
Bond B = A;

You won’t see the “Copy Assigning” output, you will see the “Copy constructing” message instead! That’s because we are not copy assigning here. Copy assignment happens whenever we use the = operator to assign to a Bond object that has already been initialised. Whereas, the copy constructor is called when we copy a Bond object into a new Bond that has not been initialised yet.

In our second example, the Bond B was already initialised with the normal constructor, before we assigned to it with =, so the copy assignment method was called. however, in our third example, the Bond B did not exist yet when we used the = operator, so the copy constructor was called. This difference is easy to remember, because constructors always initialise new objects!

When you see an example like this, you might ask yourself a couple of questions. Why are we splitting hairs over these two different cases? Why do we even need two different methods, couldn’t C++ just use a single copy method here?

Well, with these kind of trivial examples, it is a little pointless to have a separate copy constructor and copy assignment operator. So let’s imagine a slightly more complex example. Suppose we have a class, Holder that has a pointer to some object on the heap. Now when copy construct we know that our Holder object is uninitialised, so we can just copy the from source to the target. Whether we do a deep or shallow copy is irrelevant here. When we do a copy assignment, the target object will have a pointer to an object on the heap. So, before we can copy from the source object, we must free this memory with a delete. Otherwise we would end up with a serious memory leak.

To consider an even more complicated example. imagine a client class that talks to a server. When we copy a client object, we may want different behaviour depending on whether the target object has already started talking to a server or not.

So, in more complicated examples, the difference between copy assignment and copy construction can be quite important. The thing that you need to remember is that copy assignment happens when the target is already initialised, copy construction when it has not been initialised yet.

Assembly Tutorial – The Data Section

So far we have only used the data section of our programs to define data and to read that data at runtime. However, we can also write to the data section! Try running the following code through the debugger:

.section .data
var:
.byte 5

.section .text

.globl _start
_start:

movq $10, var

movq $60, %rax
movq $0, %rdi
syscall

Using the techniques we learned in a previous post, you will see that the line

movq $10, var

changes the value of the byte of memory named var from 5 to 10.

If you want to define read only data in your binary, you can do so with the .rodata section. This works just like the data section. However, if you try to write to the memory here, you will get a seg-fault.

Assembly Tutorial – Advanced debugging Techniques

We have already seen the basics of debugging assembly code with GDB. We covered assembling our code with debug symbols, setting break points, stepping through the code as it executes and inspecting the contents of registers. Now it is time to learn some more advanced techniques!

Command Line Arguments

Sometimes when we run an executable we pass in command line arguments. We can also do this when debugging with GDB. There are two ways to do this. We can put the command line arguments after the run command r. So if echo_input was the name of a binary, and we wanted to debug it with the command line arguments “Hello World” we would, load it into GDB as normal, and then start execution with

r Hello World

Alternatively we can load the executable with our command line arguments directly by using the --args option. So, in our example we would execute:

gdb --args ./echo_input Hello World

This is very useful when debugging the code in our previous posts covering command line arguments!

Inspecting Memory

We know how to read the data stored in registers, but when we’re debugging we often want to read values stored in memory. Suppose, for example, we have a register that we are using as a pointer. We can use the info registers command to see what memory address is stored in the register. To see what data is stored in that memory address we can use the x command.

The x command prints out the value at a given memory address. We provide a suffix to specify how much memory to read and how to display it.

Let’s have a look at an example. Suppose we have defined a byte in our data section with value 12, and that we have moved the address of this byte into the register rax. In GDB we use the command

info registers rax

to read this value from rax. Let’s say that the output of this command is

rdi            0x40200b            4202507

So the address of the our data is 4202507, or 0x40200b in hex. We can read the value stored at this memory address with the command

x/bd 0x40200b

The output of this will be 0x40200b: 12, that is, the address followed by the value 12, as we would expect.

The suffix bd tells gdb to read a byte (b) of memory and display the result as a decimal (d). We can display value as hexadecimal with x, octal with o, binary with t and unsigned decimal with u. We can specify the size to read as a byte with b, 2 bytes with h, 4 bytes with w and 8 bytes with g.

Let’s say we have defined a short in our data section named numShort that has value 256. This will take up more than one byte, it will appear in memory as the byte 00000000 followed by 000000001. So the command x/bt will read the first byte, 00000000, and the command x/ht will read two bytes giving 0000000100000000.

We can also output more than one value at once, by adding a multiplier to the suffix. So if we apply the command x/2bt to the memory address referenced by the name numShort our output will be:

0x40200c:	00000000	00000001

We can also read and output character values. Suppose we have declared a string in our data section with the value “outputFile”. If we inspect the address of this memory with x/bx, we will get 0x6f. If you look this value up in an ascii table, you will see this is the hex value of the character ‘o’. This is, or course, the first character of our string.

To output these values as characters directly we use the c suffix like so:

x/bc 4202496

the output will be: 111 'o'. That is the decimal ascii value of the character ‘o’ and the character ‘o’. We can even read multiple values at once. For example the command

x/5bc 4202496

will output:

111 'o'	117 'u'	116 't'	112 'p'	117 'u' 

that is, we have read five characters starting at the memory address 4202496. Of course reading individual characters like this would be a little tedious, and we can just read entire strings out of memory. The command:

x/s 4202496

will output the entire string: "outputFile".

The x command doesn’t work just on the data section, we can use it to inspect any memory address! For example we can check the values in our buffers defined in the .bss section with x.

Our instructions are also stored in memory, and we can read those with x as well. The register rip is the instruction pointer and contains the address of the next instruction that will be executed. So, we can get that address in GDB with the command:

info registers rip

If we use x/i on the returned address we will see something like:

=> 0x401000 <_start>:	mov    $0x32,%rax

Once we specify a particular size and format, when we execute x without a suffix, it will use the same size and format. The default is to read 4 bytes and display in hexadecimal.

In our example we read the memory addresses from registers. However, we can also use the names of memory addresses directly with the & operator. For example:

x/s &filename

will print the content of the memory address named filename. This works for buffers defined in the .bss section and for data declared in the .data section. We can also use arithmetic expressions when specifying the memory address to inspect. For example to read the byte that is located 3 bytes pas the memory address 0x40200b we would use the command

x/bx 0x40200b + 3

The units we are counting in are the same as the units we are reading, so if we wanted to read the fifth 2 byte value after the memory address 0x40200b we would use:

x/hx 0x40200b + 5

Conditional BreakPoints and Watches

To help with the monotony of debugging we use conditional breakpoints. These are breakpoints that come with a logical condition on a register. The breakpoint will only stop execution when the condition is satisfied. Suppose our source code is in a file named, echo_input.s, and we would like to break at line 12 whenever the register rbx has value 4. We can do that with the following command:

b echo_input.s:12 if $rbx == 4

Note, we put a dollar sign $ before the name of the register. This is a little confusing, as we usually use dollar signs for constant values. We can use any of the typical binary comparison operators, ==, !=, <, >, ,<= and >= when specifying the condition. One thing that can catch you out here, is that the break point condition is evaluated before the instruction on that line executes.

We can also set watches, which are very similar to conditional breakpoints but more general. With a watch, we specify a condition on a register and code execution will halt whenever that condition is satisfied. We do not have to specify a particular line of code. To set a watch that will halt whenever the rcx is greater than 5, we use the command:

watch $rcx > 5

note, we don’t specify the file name, and we still use the dollar sign.

I have covered some pretty technical stuff in this post, I’d recommend you experiment with it all yourself to get a feel for these techniques!

Assembly Language – Command Line Parsing Part 2

So, we’ve already seen how the stack works and how we can read the name of the currently executing binary off the stack. Now it’s time to actually parse command line arguments that come after the name of the binary. Reading the arguments is a little bit more complicated because we do not know in advance how many there will be.

Luckily for us, the kernel gives us a little help. Before execution of our program begins the kernel reads all the space separated arguments after the binary name. It puts these arguments into one chunk of contiguous memory as null terminated strings. Then it puts the address of this piece of memory on the stack. Finally, it puts the number of command line arguments it saw onto the stack.

So, the first thing we do is read the number of command line arguments off the stack. Then we read the address of the start of the strings. Then we iterate over this block of memory, printing each string as we see it. We know how many arguments to expect, so when we have seen that many we quit.

OK, it’s time to look at the code!

.equ NULL, 0

.section .data
NEW_LINE: .byte 10
.section .text

.globl _start
_start:

popq %rbx

decq %rbx

cmpq $0, %rbx
je exit_with_error

popq %r13 # The name of the currently executing binary
popq %r13

movq $0, %r8   # number of nulls seen so far
movq $0, %r9   # number of characters since last null 
movq $0, %r10  # number of characters up to last null
movq $0, %r12  # number of characters seen so far

loop_start:
movq (%r13,%r12,1),%rax

incq %r9
incq %r12

cmp $NULL,%al
jne loop_start 

movq %r9, %rdx
movq %r13, %rsi
addq %r10, %rsi
movq $1, %rax
movq $1, %rdi
syscall

movq $1, %rdx
movq $NEW_LINE, %rsi
movq $1, %rax
movq $1, %rdi
syscall

addq %r9, %r10
movq $0,%r9

incq %r8
cmpq %r8,%rbx
je exit

jmp loop_start

exit:

movq $60, %rax
movq $0, %rdi
syscall

exit_with_error:
movq $60, %rax
movq $-1, %rdi
syscall

First we pop the number of command line arguments off the stack into the rbx register. We decrement this value with decq because it will include the name of the binary itself. We check that there are a non-zero number of command line arguments. Then we pop the binary name, which we won’t be using. After that we pop the memory address of the actual arguments into r13.

Next we set up four different registers as counters we will use when looping over the command line arguments. As the strings in memory are null-terminated we can keep track of them via null characters. So, the counters are: the number of nulls we have seen so far, the number of characters we have seen since the last null, the number of characters that came before the last null and the total number of characters we have seen overall.

movq $0, %r8   # number of nulls seen so far
movq $0, %r9   # number of characters since last null 
movq $0, %r10  # number of characters up to last null
movq $0, %r12  # number of characters seen so far

Now the loop itself begins. The first part of this loop indexes into the memory location beginning at r13 until we see a null character, incrementing r9 and r12 as we go.

loop_start:
movq (%r13,%r12,1),%rax

incq %r9
incq %r12

cmp $NULL,%al
jne loop_start 

Whenever we do see a null character we proceed to the next section. This is where we write the current string to the terminal.

movq %r9, %rdx
movq %r13, %rsi
addq %r10, %rsi
movq $1, %rax
movq $1, %rdi
syscall

movq $1, %rdx
movq $NEW_LINE, %rsi
movq $1, %rax
movq $1, %rdi
syscall

The register r9 contains the number of characters since the last null, so that is the length of the current string. The memory address of the start of this block of memory is in r13, the number of characters that we saw up to the last null are in r10, so the memory address of the start of this string is the sum of those two values. We also print a newline so make our output a little prettier.

Once we have outputted the current string, we update our other counters and check to see if we have read all the command line arguments.

addq %r9, %r10
movq $0,%r9

incq %r8
cmpq %r8,%rbx
je exit

jmp loop_start

First we update the value in r10 to contain the number of characters up to the null we have just seen by adding on the value in r9. Then we reset r9 to zero. Register r8 keeps track of the number of nulls we have seen so far, so we increment it and compare against rbx. If they are equal, we jump straight to the exit. Otherwise we jump back to the start of the loop and carry on.

So, we now know how to parse our command lines. The kernel also copies the current environment variables into memory and leaves a pointer to them on the stack. These are a little bit harder to parse, so we will ignore them for now.

Assembly Language – Arithmetic Instructions

Before we continue with command line parsing, we will have a brief diversion covering how arithmetic instructions work. We have already seen the increment and decrement instructions, incq and decq. These add one and subtract one from the value in a register. Now we will be covering more general arithmetic operations. In a previous post we saw how to use comparison instructions. Arithmetic instructions are really quite similar.

If we wish to add two quad-word values, we use the addq instruction. The syntax is:

addq X, Y

where X is the name of a register or a constant value and Y is the name of a register. So the instruction addq $17, %rax adds 17 to the value in register rax and stores the result in rax. To subtract we use the subq instruction which uses the exact same syntax.

There are two different multiplication instructions. The first, imulq, works just like the addq and subq instructions. This performs signed multiplication. However, as the result is stored in a single 64 bit register this instruction can quite easily lead to an overflow. Indeed, if we try to use constant values that are too large the assembly step will fail. For example the instruction

imulq $0x8000000, %rax 

will cause an error when you try and assemble. This is, roughly, because max positive value you can store in 32 bits is 7FFFFFFF. However, you can still move this value into a register and multiply that way.

There is another multiply syntax that allows us to multiply 64 bit numbers without overflow. This syntax uses two instruction names, mulq and imulq, but it takes a single register value. The instruction imulq performs signed multiplication and the instruction mulq performs unsigned multiplication. These instructions multiply the value in the supplied register by whatever value is in the rax register and stores the result across rdx and rax. The lower 64 bits are stored in rax and the upper 64 bits in rdx.

To perform division we use idivq and divq. As before, idivq is signed division, and divq is unsigned division. The division instructions take a single argument, the name of a register. With these instructions, the CPU takes the values in rax and rdx as a single value, rax is the lower 64 bits and rdx is the upper 64 bits. It divides this value by the value in the register supplied. The result of this division is then stored in rax and the remainder is stored in rdx.

There is also a unary negation operation negq, that negates the value in a register.

Many of these instructions will overflow. And, unlike in some higher level languages, our program will continue to execute happily with whatever values the registers now contain. To avoid this behaviour we use a special instruction: jo. This is the jump on overflow instruction. Whenever an arithmetic operation that causes an overflow occurs the CPU sets the overflow flag. The jo instruction jumps conditioned on this flag. If the flag is set, execution jumps to the address supplied.

There are also versions of the above arithmetic operations for non-quad words. However we aren’t particularly interested in them right now.

Assembly Language – Command Line Parsing part 1

We know from a previous post that when our program starts the Linux kernel will have stashed some helpful values for us on the stack. At the top of the stack we have the number of command line arguments. This value includes the name of the binary being executed. So, for example, the command line “binaryName arg1 arg2” would give 3. Next in the stack is a pointer to the name of the binary. Finally we have a pointer to the command line arguments themselves, this doesn’t include the name of the binary.

We’re going to see how to parse these arguments. First we’re going to read and display the name of the binary that is currently executing. To do this, we will need to read a value off the stack, get the length of this string by searching for the null character and then print it.

Let’s look at some code:

.equ NULL, 0

.section .data
NEW_LINE: .byte 10
.section .text

.globl _start
_start:

popq %r13

cmpq $1, %r13
jne exit_with_error

popq %r13

movq $0, %r12  # number of characters seen so far

loop_start:

movq (%r13,%r12,1),%rax

incq %r12

cmp $NULL,%al
jne loop_start 

movq %r12, %rdx
movq %r13, %rsi
movq $1, %rax
movq $1, %rdi
syscall

movq $1, %rdx
movq $NEW_LINE, %rsi
movq $1, %rax
movq $1, %rdi
syscall

exit:

movq $60, %rax
movq $0, %rdi
syscall

exit_with_error:

movq $60, %rax
movq $-1, %rdi
syscall

Firstly, I should mentions that I’ve decided to use the higher numbered registers in this example as it will make it easier to modify this code for the next post.

The very first thing we do is define a constant with equ. The constant is named NULL and has value 0. Next we define a byte in our data section named NEW_LINE with value 10. It will not surprise you to learn that 0 is the ascii code for a null character and 10 is the ascii code for a new line.

An important subtlety here is the difference between an equ constant and a value defined in the .data section. The constant values defined with equ are filled in when the assembler runs. The data section becomes part of the binary, and is copied into memory when our program is run. So we can reference a value in the .data section by it’s memory address, whereas an equ constant is really just a special name for a value.

In our text section, our first instruction is:

popq %r13

This pops the top value off the stack into the r13 register. We know that this value is the number of command line arguments. So, we check if it is equal to 1, and if not, exit with an error:

cmpq $1, %r13
jne exit_with_error

Now we pop the next value of the stack into the r13 register. This will be a pointer to the name of the currently executing binary. To get the length of this string we loop over it looking for the null character like so:

movq $0, %r12  # number of characters seen so far

loop_start:

movq (%r13,%r12,1),%rax

incq %r12

cmp $NULL,%al
jne loop_start 

To index into the string that contains the name of the binary we use index addressing mode:(%r13,%r12,1). This reads the value stored in the memory address equal to the value in r13 plus 1 times the value in r12. The r12 register is our counter that keeps track of the current character we are looking at. So as we loop we are iterating through the string.

We check to see if the current character is null with: cmp $NULL,%al. The important point here is that we are reading characters which are represented as bytes. So if we just read the null character, we would expect the lowest byte of rax to be zero. There is probably lots of junk in the higher bytes of rax that we don’t care about. We know already that the lowest byte of rax is named al, so we compare this to 0. Also we put the register second in our comparison, if we do not we will get an assembler error. This is because the size of the second operand determines the memory size we are comparing, in this case byte.

Once we find the null character we output the string to the command line as normal:

movq %r12, %rdx
movq %r13, %rsi
movq $1, %rax
movq $1, %rdi
syscall

Then we use the NEW_LINE data value we defined earlier to output a new line:

movq $1, %rdx
movq $NEW_LINE, %rsi
movq $1, %rax
movq $1, %rdi
syscall

And finally we exit with exit code 0. If you assemble, link and run this code, you should see the name of your binary file printed to the command line. In our next post we will see how to parse the command line arguments that come after the name of the binary.