Reference no: EM133105147
Assignment: Implement a simplified printf function:
As mentioned before, the printf subroutine is just a subroutine like any other. To prove this, you will write your own simplified version of printf in this assignment.
Exercise:
Write a simplified printf subroutine that takes a variable amount of arguments. The first argument for your subroutine is the format string. The rest of the arguments are printed instead of the placeholders (also called format specifiers) in the format string. How those arguments are printed depends on the corresponding format specifiers. Your printf function has to support any number of format specifiers in the format string. Any format specifier after that may be printed without modification.
Unlike the real printf, your version only has to understand the format specifiers listed below. If a format specifier is not recognized, it should be printed without modification. Give your printf function a different name (e.g. my printf) to avoid confusion with the real printf function in the C library. Please note that for this exercise you are not allowed to use the printf function or any other C library function, except for the putchar function to output a single ASCII character. Your function must follow the proper x86 64 calling conventions. It must accept any num- ber of arguments (e.g., tens of arguments) like any standard printf implementation. Refer to Section 3.3.1 for details on how to pass and accept a large number of arguments.
Supported format specifiers:
%d Print a signed integer in decimal. The corresponding parameter is a 64 bit signed integer.
%u Print an unsigned integer in decimal. The corresponding parameter is a 64 bit unsigned integer.
%s Print a null terminated string. No format specifiers should be parsed in this string. The corresponding parameter is the address of first character of the string.
%% Print a percent sign. This format specifier takes no argument.
Example:
Suppose you have the following format string:
My name is %s. I think I'll get a %u for my exam. What does %r do? And %%?
Also suppose you have the additional arguments "Piet" and 10. Then your subroutine should output:
My name is Piet. I think I'll get a 10 for my exam. What does %r do? And %?
Hints
To get started you may divide the work in a number of steps. Note that these are just hints, you do not have to follow these steps to finish this assignment.
1. Write a subroutine that prints a string character by character, for example by using putchar.
2. Modify the subroutine to recognize format specifiers in the format string. Initially, you can discard the format specifiers rather than process them. Characters that are not part of a format specifier can be printed as before.
3. Implement the various format specifiers. It may help to implement %u before %d.
4. It may help to store all input argument registers on the stack at the start of your function, even if you don't end up using them.