SlideShare a Scribd company logo
1 of 18
Download to read offline
printf("%s from %c to Z, in %d minutes!n",
"printf", 'A', 45);
Joรซl Porquet, PhD
UC Davis - May 15th, 2018
Copyright ยฉ 2018 Joรซl Porquet - CC BY-NC-SA 4.0 International License 1 / 18
Multi-talented printf()
101
printf("Hello world!n");
$ ./a.out
Hello world!
201
printf("%s from %c to Z, in %d minutes!n", "printf", 'A', 45);
$ ./a.out
printf from A to Z, in 45 minutes!
pow(101, 2)
int i;
printf(" %n", &i);
printf("%sbD is 033[1;31m#%d033[0m!n", "UCB", i);
2 / 18
printf(): an odyssey
Fortran I
Special statement for building formatting descriptions:
WRITE OUTPUT TAPE 6, 601, IA, IB, IC, AREA
601 FORMAT (4H A= ,I5,5H B= ,I5,5H C= ,I5,8H AREA= ,F10.2,
+ 13H SQUARE UNITS)
(Approximate) translation in C:
printf(" A= %5d B= %5d C= %5d AREA= %10.2f SQUARE UNITS", a, b, c, area);
BCPL
Printing and formatting are merged into a single statement:
WRITEF("%I2-QUEENS PROBLEM HAS %I5 SOLUTIONS*N", NUMQUEENS, COUNT)
(Approximate) translation in C:
printf("%2d-queens problem has %5d solutionsn", numqueens, count);
3 / 18
printf(): an odyssey
C
printf("Hello %s, you are %d years oldn", name, age);
Trickle-down string formatting
Unix printf
$ printf "%s, stop lying; you're not %d!n" Bob 21
Bob, stop lying; you're not 21!
$
Other languages...
awk, C++, Objective C, D, F#, G (LabVIEW), GNU MathProg, GNU Octave, Go, Haskell, J, Java
(since version 1.5) and JVM languages (Clojure, Scala), Lua (string.format), Maple, MATLAB,
Max (via the sprintf object), Mythryl, PARI/GP, Perl, PHP, Python (via % operator), R,
Red/System, Ruby, Tcl (via format command), Transact-SQL (via xp_sprintf), Vala.
4 / 18
Output
$ cowsay "I love lectures about printf!"
_______________________________
< I love lectures about printf! >
-------------------------------
 ^__^
 (oo)_______
(__) )/
||----w |
|| ||
$
$ cowthink -f vader "I wish there was free pizza too..."
____________________________________
( I wish there was free pizza too... )
------------------------------------
o ,-^-.
o !oYo!
o /./=.______
## )/
||-----w||
|| ||
Cowth Vader
$
$ du /bin/* | sort -rn
20672 /bin/js52
19164 /bin/inkscape
19136 /bin/inkview
18720 /bin/node
18684 /bin/clementine
17452 /bin/mariabackup
17112 /bin/mysqld
16432 /bin/mysql_client_test_embedded
16332 /bin/mysql_embedded
16232 /bin/mysqltest_embedded
7600 /bin/gdb
...
Introspection
Booting kernel from Legacy Image at 20080000 ...
Image Name: Linux-2.6.37
Image Type: ARM Linux Kernel Image (uncompressed)
Data Size: 1256880 Bytes = 1.2 MiB
Load Address: 20008000
Entry Point: 20008000
Verifying Checksum ... OK
Loading Kernel Image ... OK
OK
Starting kernel ...
Uncompressing Linux... done, booting the kernel.
Linux version 2.6.37 (nkinar at matilda) (gcc version 4.3.5 (Buildro
ot 2011.02) ) #3 Sat Apr 2 17:28:21 CST 2011
CPU: ARM926EJ-S [41069265] revision 5 (ARMv5TEJ), cr=00053177
CPU: VIVT data cache, VIVT instruction cache
Machine: Atmel AT91SAM9RL-EK
Memory policy: ECC disabled, Data cache writeback
Clocks: CPU 200 MHz, master 100 MHz, main 12.000 MHz
Built 1 zonelists in Zone order, mobility grouping on.
Total pages: 16256
Kernel command line: console=ttyS0,115200
mtdparts=flash:10M(kernel),100M(root),-(storage) rw rootfstype=ubifs
PID hash table entries: 256 (order: -2, 1024 bytes)
Dentry cache hash table entries: 8192 (order: 3, 32768 bytes)
Inode-cache hash table entries: 4096 (order: 2, 16384 bytes)
Memory: 64MB = 64MB total
Memory: 62348k/62348k available, 3188k reserved, 0K highmem
...
Why printf()?
5 / 18
Tell me where you printf()!
Typical GNU/Linux computer
/usr/bin/date +"%Y" /usr/bin/xterm
User-space
Kernel-space
...
printf("2018n")
...
(Insanely) complex code
dealing with consoles...
Ingo Molnรกr (Linux kernel core developer): "The tty layer is one of the very few pieces of
kernel code that scares the hell out of me :-)"
6 / 18
Tell me where you printf()!
Embedded systems or when display is not available
/usr/bin/date +"%Y"
User-space
Kernel-space
...
printf("2018n")
...
Same (insanely) complex code
dealing with consoles...
Serial device (UART)
driver
HardwareSoftware
Characters are sent one by one over a serial port
7 / 18
A serial port on every board?
My own phone!
8 / 18
Playstation 4 Linux on PS4
PS4 controller
A serial port on every board?
9 / 18
How to print?
putchar(): the cornerstone
/*
* Code for IBM-PC x86: write character to COM1 serial port
* (taken from NuttX)
*/
void putchar(char ch)
{
/* Wait until the Transmitter Holding Register (THR) is empty. */
while ((inb(COM1_PORT+COM_LSR) & LSR_THRE) == 0);
/* Then output the character to the THR */
outb(ch, COM1_PORT+COM_THR);
}
10 / 18
How to print?
No formatting is simply puts()
void my_printf(char *str)
{
/* Just print all the characters until the NULL terminator */
while (*str)
putchar(*str++);
}
int main(void)
{
/* printf 101 */
my_printf("Hello world!n");
}
$ ./a.out
Hello world!
$
11 / 18
How to print?
With formatting...
Input:
Output: printf from A to Z, in 45 minutes!n
For each placeholder, need to retrieve next parameter
Depending on placeholder:
'%s': get string
'%c': get character
'%d': convert integer into characters
12 / 18
Variadic functions
Example: function prototype
#include <stdarg.h> /* Macro/function definitions for variadic functions */
#include <stdio.h>
/*
* Sum a variable number of integers
* @count: the number of integer parameters
*
* Receive @count integers, sum them up and return the result
*/
int sum_ints(int count, ...)
{
/* ??? */
}
int main(void)
{
/* sum up 3 integers: 10, 20 and 30 */
printf("Sum is %dn", sum_ints(3, 10, 20, 30));
/* sum up 5 integers: 10, 20, 30, 40, 50 */
printf("Sum is %dn", sum_ints(5, 10, 20, 30, 40, 50));
return 0;
}
13 / 18
Variadic functions
Example: function implementation
int sum_ints(int count, ...)
{
int i, sum = 0;
va_list ap;
va_start(ap, count); /* Init variable parameter list */
for (i = 0; i < count; i++) {
int n = va_arg(ap, int); /* Get next integer parameter */
sum += n;
}
va_end(ap); /* Clean up parameter list */
return sum;
}
14 / 18
printf(): a simple implementation
Let's code...
15 / 18
printf("Tell me more!n");
Complex family of functions
Call graph from musl (a lightweight libc implementation):
vfprintf() in various C standard libraries:
glibc: ~2400 SLOC
uclibc: ~2000 SLOC
musl: ~700 SLOC
16 / 18
#include <stdio.h>
int main(void)
{
char name[256];
fgets(name, 256, stdin);
printf("Your name is: ");
printf(name);
return 0;
}
#include <stdio.h>
int main(void)
{
char name[256];
fgets(name, 256, stdin);
printf("Your name is: ");
printf("%s", name);
return 0;
}
$ ./a.out
%s%s%s%s%s
Your name is: %s%s%s%s%s
$ ./a.out
%s%s%s%s%s
Segmentation fault (core dumped)
$ ./a.out
%08x.%08x.%08x.%08x.%08x.%08x
Your name is: 00000020.00000000.00000000.0000
0003.f7fbc4c0.78383025
printf("Tell me more!n");
Security vulnerability: Uncontrolled format string
17 / 18
printf("Thanks!");
scanf("%s", question);
18 / 18

More Related Content

What's hot

Bytes in the Machine: Inside the CPython interpreter
Bytes in the Machine: Inside the CPython interpreterBytes in the Machine: Inside the CPython interpreter
Bytes in the Machine: Inside the CPython interpreterakaptur
ย 
Allison Kaptur: Bytes in the Machine: Inside the CPython interpreter, PyGotha...
Allison Kaptur: Bytes in the Machine: Inside the CPython interpreter, PyGotha...Allison Kaptur: Bytes in the Machine: Inside the CPython interpreter, PyGotha...
Allison Kaptur: Bytes in the Machine: Inside the CPython interpreter, PyGotha...akaptur
ย 
เน‚เธ›เธฃเนเธเธฃเธกเธขเนˆเธญเธขเนเธฅเธฐเธŸเธฑเธ‡เธŠเธฑเธ™เธเนŒเธกเธฒเธ•เธฃเธเธฒเธ™
เน‚เธ›เธฃเนเธเธฃเธกเธขเนˆเธญเธขเนเธฅเธฐเธŸเธฑเธ‡เธŠเธฑเธ™เธเนŒเธกเธฒเธ•เธฃเธเธฒเธ™เน‚เธ›เธฃเนเธเธฃเธกเธขเนˆเธญเธขเนเธฅเธฐเธŸเธฑเธ‡เธŠเธฑเธ™เธเนŒเธกเธฒเธ•เธฃเธเธฒเธ™
เน‚เธ›เธฃเนเธเธฃเธกเธขเนˆเธญเธขเนเธฅเธฐเธŸเธฑเธ‡เธŠเธฑเธ™เธเนŒเธกเธฒเธ•เธฃเธเธฒเธ™knang
ย 
About Go
About GoAbout Go
About GoJongmin Kim
ย 
Diving into byte code optimization in python
Diving into byte code optimization in python Diving into byte code optimization in python
Diving into byte code optimization in python Chetan Giridhar
ย 
How the stack works(1)
How the stack works(1)How the stack works(1)
How the stack works(1)keithrozario
ย 
ๆˆ‘ๅœจ่ฑ†็“ฃไฝฟ็”จEmacs
ๆˆ‘ๅœจ่ฑ†็“ฃไฝฟ็”จEmacsๆˆ‘ๅœจ่ฑ†็“ฃไฝฟ็”จEmacs
ๆˆ‘ๅœจ่ฑ†็“ฃไฝฟ็”จEmacs่‘ฃ ไผŸๆ˜Ž
ย 
C่จ€่ชž้™็š„่งฃๆžใƒ„ใƒผใƒซใจ Ruby 1.9 trunk
C่จ€่ชž้™็š„่งฃๆžใƒ„ใƒผใƒซใจ Ruby 1.9 trunkC่จ€่ชž้™็š„่งฃๆžใƒ„ใƒผใƒซใจ Ruby 1.9 trunk
C่จ€่ชž้™็š„่งฃๆžใƒ„ใƒผใƒซใจ Ruby 1.9 trunkikegami__
ย 
All I know about rsc.io/c2go
All I know about rsc.io/c2goAll I know about rsc.io/c2go
All I know about rsc.io/c2goMoriyoshi Koizumi
ย 
Fizzbuzzalooza
FizzbuzzaloozaFizzbuzzalooza
FizzbuzzaloozaKevlin Henney
ย 
FizzBuzz Trek
FizzBuzz TrekFizzBuzz Trek
FizzBuzz TrekKevlin Henney
ย 
[CB20] Reflex: you give me a parser, I give you a token generator by Paolo Mo...
[CB20] Reflex: you give me a parser, I give you a token generator by Paolo Mo...[CB20] Reflex: you give me a parser, I give you a token generator by Paolo Mo...
[CB20] Reflex: you give me a parser, I give you a token generator by Paolo Mo...CODE BLUE
ย 
Torchbearersnotebook.blogspot.com program to create a list in python and valu...
Torchbearersnotebook.blogspot.com program to create a list in python and valu...Torchbearersnotebook.blogspot.com program to create a list in python and valu...
Torchbearersnotebook.blogspot.com program to create a list in python and valu...SAKSHISINGH486
ย 
Duralexsedregex
DuralexsedregexDuralexsedregex
DuralexsedregexWairton Abreu
ย 
Robustness Analysis of Adaptive Chinese Input Methods @ WTIM2011
Robustness Analysis of Adaptive Chinese Input Methods @ WTIM2011Robustness Analysis of Adaptive Chinese Input Methods @ WTIM2011
Robustness Analysis of Adaptive Chinese Input Methods @ WTIM2011Mike Tian-Jian Jiang
ย 
Computer Architecture and Organization lab with matlab
Computer Architecture and Organization lab with matlabComputer Architecture and Organization lab with matlab
Computer Architecture and Organization lab with matlabShankar Gangaju
ย 

What's hot (20)

Bytes in the Machine: Inside the CPython interpreter
Bytes in the Machine: Inside the CPython interpreterBytes in the Machine: Inside the CPython interpreter
Bytes in the Machine: Inside the CPython interpreter
ย 
Vcs23
Vcs23Vcs23
Vcs23
ย 
Miblagh (2)
Miblagh (2)Miblagh (2)
Miblagh (2)
ย 
Allison Kaptur: Bytes in the Machine: Inside the CPython interpreter, PyGotha...
Allison Kaptur: Bytes in the Machine: Inside the CPython interpreter, PyGotha...Allison Kaptur: Bytes in the Machine: Inside the CPython interpreter, PyGotha...
Allison Kaptur: Bytes in the Machine: Inside the CPython interpreter, PyGotha...
ย 
เธŸเธฑเธ‡เธเนŒเธŠเธฑเธ™ Printf&scanf
เธŸเธฑเธ‡เธเนŒเธŠเธฑเธ™ Printf&scanfเธŸเธฑเธ‡เธเนŒเธŠเธฑเธ™ Printf&scanf
เธŸเธฑเธ‡เธเนŒเธŠเธฑเธ™ Printf&scanf
ย 
เน‚เธ›เธฃเนเธเธฃเธกเธขเนˆเธญเธขเนเธฅเธฐเธŸเธฑเธ‡เธŠเธฑเธ™เธเนŒเธกเธฒเธ•เธฃเธเธฒเธ™
เน‚เธ›เธฃเนเธเธฃเธกเธขเนˆเธญเธขเนเธฅเธฐเธŸเธฑเธ‡เธŠเธฑเธ™เธเนŒเธกเธฒเธ•เธฃเธเธฒเธ™เน‚เธ›เธฃเนเธเธฃเธกเธขเนˆเธญเธขเนเธฅเธฐเธŸเธฑเธ‡เธŠเธฑเธ™เธเนŒเธกเธฒเธ•เธฃเธเธฒเธ™
เน‚เธ›เธฃเนเธเธฃเธกเธขเนˆเธญเธขเนเธฅเธฐเธŸเธฑเธ‡เธŠเธฑเธ™เธเนŒเธกเธฒเธ•เธฃเธเธฒเธ™
ย 
CLinkedList
CLinkedListCLinkedList
CLinkedList
ย 
About Go
About GoAbout Go
About Go
ย 
Diving into byte code optimization in python
Diving into byte code optimization in python Diving into byte code optimization in python
Diving into byte code optimization in python
ย 
How the stack works(1)
How the stack works(1)How the stack works(1)
How the stack works(1)
ย 
ๆˆ‘ๅœจ่ฑ†็“ฃไฝฟ็”จEmacs
ๆˆ‘ๅœจ่ฑ†็“ฃไฝฟ็”จEmacsๆˆ‘ๅœจ่ฑ†็“ฃไฝฟ็”จEmacs
ๆˆ‘ๅœจ่ฑ†็“ฃไฝฟ็”จEmacs
ย 
C่จ€่ชž้™็š„่งฃๆžใƒ„ใƒผใƒซใจ Ruby 1.9 trunk
C่จ€่ชž้™็š„่งฃๆžใƒ„ใƒผใƒซใจ Ruby 1.9 trunkC่จ€่ชž้™็š„่งฃๆžใƒ„ใƒผใƒซใจ Ruby 1.9 trunk
C่จ€่ชž้™็š„่งฃๆžใƒ„ใƒผใƒซใจ Ruby 1.9 trunk
ย 
All I know about rsc.io/c2go
All I know about rsc.io/c2goAll I know about rsc.io/c2go
All I know about rsc.io/c2go
ย 
Fizzbuzzalooza
FizzbuzzaloozaFizzbuzzalooza
Fizzbuzzalooza
ย 
FizzBuzz Trek
FizzBuzz TrekFizzBuzz Trek
FizzBuzz Trek
ย 
[CB20] Reflex: you give me a parser, I give you a token generator by Paolo Mo...
[CB20] Reflex: you give me a parser, I give you a token generator by Paolo Mo...[CB20] Reflex: you give me a parser, I give you a token generator by Paolo Mo...
[CB20] Reflex: you give me a parser, I give you a token generator by Paolo Mo...
ย 
Torchbearersnotebook.blogspot.com program to create a list in python and valu...
Torchbearersnotebook.blogspot.com program to create a list in python and valu...Torchbearersnotebook.blogspot.com program to create a list in python and valu...
Torchbearersnotebook.blogspot.com program to create a list in python and valu...
ย 
Duralexsedregex
DuralexsedregexDuralexsedregex
Duralexsedregex
ย 
Robustness Analysis of Adaptive Chinese Input Methods @ WTIM2011
Robustness Analysis of Adaptive Chinese Input Methods @ WTIM2011Robustness Analysis of Adaptive Chinese Input Methods @ WTIM2011
Robustness Analysis of Adaptive Chinese Input Methods @ WTIM2011
ย 
Computer Architecture and Organization lab with matlab
Computer Architecture and Organization lab with matlabComputer Architecture and Organization lab with matlab
Computer Architecture and Organization lab with matlab
ย 

Similar to printf("%s from %c to Z, in %d minutes!\n", "printf", 'A', 45);

Software Vulnerabilities in C and C++ (CppCon 2018)
Software Vulnerabilities in C and C++ (CppCon 2018)Software Vulnerabilities in C and C++ (CppCon 2018)
Software Vulnerabilities in C and C++ (CppCon 2018)Patricia Aas
ย 
Rust LDN 24 7 19 Oxidising the Command Line
Rust LDN 24 7 19 Oxidising the Command LineRust LDN 24 7 19 Oxidising the Command Line
Rust LDN 24 7 19 Oxidising the Command LineMatt Provost
ย 
A CTF Hackers Toolbox
A CTF Hackers ToolboxA CTF Hackers Toolbox
A CTF Hackers ToolboxStefan
ย 
Buffer Overflows
Buffer OverflowsBuffer Overflows
Buffer OverflowsSumit Kumar
ย 
C aptitude questions
C aptitude questionsC aptitude questions
C aptitude questionsSrikanth
ย 
C - aptitude3
C - aptitude3C - aptitude3
C - aptitude3Srikanth
ย 
VTU DSA Lab Manual
VTU DSA Lab ManualVTU DSA Lab Manual
VTU DSA Lab ManualAkhilaaReddy
ย 
miniLesson on the printf() function
miniLesson on the printf() functionminiLesson on the printf() function
miniLesson on the printf() functionChristine Wolfe
ย 
ExperiencesSharingOnEmbeddedSystemDevelopment_20160321
ExperiencesSharingOnEmbeddedSystemDevelopment_20160321ExperiencesSharingOnEmbeddedSystemDevelopment_20160321
ExperiencesSharingOnEmbeddedSystemDevelopment_20160321Teddy Hsiung
ย 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial javaTpoint s
ย 
Introduction to Assembly Language
Introduction to Assembly LanguageIntroduction to Assembly Language
Introduction to Assembly LanguageMotaz Saad
ย 
NetPonto - The Future Of C# - NetConf Edition
NetPonto - The Future Of C# - NetConf EditionNetPonto - The Future Of C# - NetConf Edition
NetPonto - The Future Of C# - NetConf EditionPaulo Morgado
ย 
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)Saifur Rahman
ย 
2 data and c
2 data and c2 data and c
2 data and cMomenMostafa
ย 
Tuga IT 2018 Summer Edition - The Future of C#
Tuga IT 2018 Summer Edition - The Future of C#Tuga IT 2018 Summer Edition - The Future of C#
Tuga IT 2018 Summer Edition - The Future of C#Paulo Morgado
ย 
golang_getting_started.pptx
golang_getting_started.pptxgolang_getting_started.pptx
golang_getting_started.pptxGuy Komari
ย 
Concepts of C [Module 2]
Concepts of C [Module 2]Concepts of C [Module 2]
Concepts of C [Module 2]Abhishek Sinha
ย 

Similar to printf("%s from %c to Z, in %d minutes!\n", "printf", 'A', 45); (20)

Software Vulnerabilities in C and C++ (CppCon 2018)
Software Vulnerabilities in C and C++ (CppCon 2018)Software Vulnerabilities in C and C++ (CppCon 2018)
Software Vulnerabilities in C and C++ (CppCon 2018)
ย 
Rust LDN 24 7 19 Oxidising the Command Line
Rust LDN 24 7 19 Oxidising the Command LineRust LDN 24 7 19 Oxidising the Command Line
Rust LDN 24 7 19 Oxidising the Command Line
ย 
A CTF Hackers Toolbox
A CTF Hackers ToolboxA CTF Hackers Toolbox
A CTF Hackers Toolbox
ย 
Buffer Overflows
Buffer OverflowsBuffer Overflows
Buffer Overflows
ย 
C aptitude questions
C aptitude questionsC aptitude questions
C aptitude questions
ย 
C - aptitude3
C - aptitude3C - aptitude3
C - aptitude3
ย 
Quiz 9
Quiz 9Quiz 9
Quiz 9
ย 
CompilersAndLibraries
CompilersAndLibrariesCompilersAndLibraries
CompilersAndLibraries
ย 
VTU DSA Lab Manual
VTU DSA Lab ManualVTU DSA Lab Manual
VTU DSA Lab Manual
ย 
miniLesson on the printf() function
miniLesson on the printf() functionminiLesson on the printf() function
miniLesson on the printf() function
ย 
ExperiencesSharingOnEmbeddedSystemDevelopment_20160321
ExperiencesSharingOnEmbeddedSystemDevelopment_20160321ExperiencesSharingOnEmbeddedSystemDevelopment_20160321
ExperiencesSharingOnEmbeddedSystemDevelopment_20160321
ย 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial
ย 
Introduction to Assembly Language
Introduction to Assembly LanguageIntroduction to Assembly Language
Introduction to Assembly Language
ย 
NetPonto - The Future Of C# - NetConf Edition
NetPonto - The Future Of C# - NetConf EditionNetPonto - The Future Of C# - NetConf Edition
NetPonto - The Future Of C# - NetConf Edition
ย 
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
ย 
2 data and c
2 data and c2 data and c
2 data and c
ย 
Tuga IT 2018 Summer Edition - The Future of C#
Tuga IT 2018 Summer Edition - The Future of C#Tuga IT 2018 Summer Edition - The Future of C#
Tuga IT 2018 Summer Edition - The Future of C#
ย 
golang_getting_started.pptx
golang_getting_started.pptxgolang_getting_started.pptx
golang_getting_started.pptx
ย 
Design problem
Design problemDesign problem
Design problem
ย 
Concepts of C [Module 2]
Concepts of C [Module 2]Concepts of C [Module 2]
Concepts of C [Module 2]
ย 

Recently uploaded

Call Now โ‰ฝ 9953056974 โ‰ผ๐Ÿ” Call Girls In New Ashok Nagar โ‰ผ๐Ÿ” Delhi door step de...
Call Now โ‰ฝ 9953056974 โ‰ผ๐Ÿ” Call Girls In New Ashok Nagar  โ‰ผ๐Ÿ” Delhi door step de...Call Now โ‰ฝ 9953056974 โ‰ผ๐Ÿ” Call Girls In New Ashok Nagar  โ‰ผ๐Ÿ” Delhi door step de...
Call Now โ‰ฝ 9953056974 โ‰ผ๐Ÿ” Call Girls In New Ashok Nagar โ‰ผ๐Ÿ” Delhi door step de...9953056974 Low Rate Call Girls In Saket, Delhi NCR
ย 
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...tanu pandey
ย 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdfKamal Acharya
ย 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlysanyuktamishra911
ย 
Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixNeometrix_Engineering_Pvt_Ltd
ย 
Minimum and Maximum Modes of microprocessor 8086
Minimum and Maximum Modes of microprocessor 8086Minimum and Maximum Modes of microprocessor 8086
Minimum and Maximum Modes of microprocessor 8086anil_gaur
ย 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Arindam Chakraborty, Ph.D., P.E. (CA, TX)
ย 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...roncy bisnoi
ย 
DC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationDC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationBhangaleSonal
ย 
Call Girls in Ramesh Nagar Delhi ๐Ÿ’ฏ Call Us ๐Ÿ”9953056974 ๐Ÿ” Escort Service
Call Girls in Ramesh Nagar Delhi ๐Ÿ’ฏ Call Us ๐Ÿ”9953056974 ๐Ÿ” Escort ServiceCall Girls in Ramesh Nagar Delhi ๐Ÿ’ฏ Call Us ๐Ÿ”9953056974 ๐Ÿ” Escort Service
Call Girls in Ramesh Nagar Delhi ๐Ÿ’ฏ Call Us ๐Ÿ”9953056974 ๐Ÿ” Escort Service9953056974 Low Rate Call Girls In Saket, Delhi NCR
ย 
2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projectssmsksolar
ย 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...SUHANI PANDEY
ย 
Top Rated Call Girls In chittoor ๐Ÿ“ฑ {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor ๐Ÿ“ฑ {7001035870} VIP Escorts chittoorTop Rated Call Girls In chittoor ๐Ÿ“ฑ {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor ๐Ÿ“ฑ {7001035870} VIP Escorts chittoordharasingh5698
ย 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXssuser89054b
ย 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performancesivaprakash250
ย 
Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptNANDHAKUMARA10
ย 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Bookingdharasingh5698
ย 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756dollysharma2066
ย 
Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfRagavanV2
ย 

Recently uploaded (20)

Call Now โ‰ฝ 9953056974 โ‰ผ๐Ÿ” Call Girls In New Ashok Nagar โ‰ผ๐Ÿ” Delhi door step de...
Call Now โ‰ฝ 9953056974 โ‰ผ๐Ÿ” Call Girls In New Ashok Nagar  โ‰ผ๐Ÿ” Delhi door step de...Call Now โ‰ฝ 9953056974 โ‰ผ๐Ÿ” Call Girls In New Ashok Nagar  โ‰ผ๐Ÿ” Delhi door step de...
Call Now โ‰ฝ 9953056974 โ‰ผ๐Ÿ” Call Girls In New Ashok Nagar โ‰ผ๐Ÿ” Delhi door step de...
ย 
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
ย 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdf
ย 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
ย 
Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
ย 
Minimum and Maximum Modes of microprocessor 8086
Minimum and Maximum Modes of microprocessor 8086Minimum and Maximum Modes of microprocessor 8086
Minimum and Maximum Modes of microprocessor 8086
ย 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
ย 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
ย 
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
ย 
DC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationDC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equation
ย 
Call Girls in Ramesh Nagar Delhi ๐Ÿ’ฏ Call Us ๐Ÿ”9953056974 ๐Ÿ” Escort Service
Call Girls in Ramesh Nagar Delhi ๐Ÿ’ฏ Call Us ๐Ÿ”9953056974 ๐Ÿ” Escort ServiceCall Girls in Ramesh Nagar Delhi ๐Ÿ’ฏ Call Us ๐Ÿ”9953056974 ๐Ÿ” Escort Service
Call Girls in Ramesh Nagar Delhi ๐Ÿ’ฏ Call Us ๐Ÿ”9953056974 ๐Ÿ” Escort Service
ย 
2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects
ย 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
ย 
Top Rated Call Girls In chittoor ๐Ÿ“ฑ {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor ๐Ÿ“ฑ {7001035870} VIP Escorts chittoorTop Rated Call Girls In chittoor ๐Ÿ“ฑ {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor ๐Ÿ“ฑ {7001035870} VIP Escorts chittoor
ย 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
ย 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
ย 
Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.ppt
ย 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
ย 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
ย 
Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdf
ย 

printf("%s from %c to Z, in %d minutes!\n", "printf", 'A', 45);

  • 1. printf("%s from %c to Z, in %d minutes!n", "printf", 'A', 45); Joรซl Porquet, PhD UC Davis - May 15th, 2018 Copyright ยฉ 2018 Joรซl Porquet - CC BY-NC-SA 4.0 International License 1 / 18
  • 2. Multi-talented printf() 101 printf("Hello world!n"); $ ./a.out Hello world! 201 printf("%s from %c to Z, in %d minutes!n", "printf", 'A', 45); $ ./a.out printf from A to Z, in 45 minutes! pow(101, 2) int i; printf(" %n", &i); printf("%sbD is 033[1;31m#%d033[0m!n", "UCB", i); 2 / 18
  • 3. printf(): an odyssey Fortran I Special statement for building formatting descriptions: WRITE OUTPUT TAPE 6, 601, IA, IB, IC, AREA 601 FORMAT (4H A= ,I5,5H B= ,I5,5H C= ,I5,8H AREA= ,F10.2, + 13H SQUARE UNITS) (Approximate) translation in C: printf(" A= %5d B= %5d C= %5d AREA= %10.2f SQUARE UNITS", a, b, c, area); BCPL Printing and formatting are merged into a single statement: WRITEF("%I2-QUEENS PROBLEM HAS %I5 SOLUTIONS*N", NUMQUEENS, COUNT) (Approximate) translation in C: printf("%2d-queens problem has %5d solutionsn", numqueens, count); 3 / 18
  • 4. printf(): an odyssey C printf("Hello %s, you are %d years oldn", name, age); Trickle-down string formatting Unix printf $ printf "%s, stop lying; you're not %d!n" Bob 21 Bob, stop lying; you're not 21! $ Other languages... awk, C++, Objective C, D, F#, G (LabVIEW), GNU MathProg, GNU Octave, Go, Haskell, J, Java (since version 1.5) and JVM languages (Clojure, Scala), Lua (string.format), Maple, MATLAB, Max (via the sprintf object), Mythryl, PARI/GP, Perl, PHP, Python (via % operator), R, Red/System, Ruby, Tcl (via format command), Transact-SQL (via xp_sprintf), Vala. 4 / 18
  • 5. Output $ cowsay "I love lectures about printf!" _______________________________ < I love lectures about printf! > ------------------------------- ^__^ (oo)_______ (__) )/ ||----w | || || $ $ cowthink -f vader "I wish there was free pizza too..." ____________________________________ ( I wish there was free pizza too... ) ------------------------------------ o ,-^-. o !oYo! o /./=.______ ## )/ ||-----w|| || || Cowth Vader $ $ du /bin/* | sort -rn 20672 /bin/js52 19164 /bin/inkscape 19136 /bin/inkview 18720 /bin/node 18684 /bin/clementine 17452 /bin/mariabackup 17112 /bin/mysqld 16432 /bin/mysql_client_test_embedded 16332 /bin/mysql_embedded 16232 /bin/mysqltest_embedded 7600 /bin/gdb ... Introspection Booting kernel from Legacy Image at 20080000 ... Image Name: Linux-2.6.37 Image Type: ARM Linux Kernel Image (uncompressed) Data Size: 1256880 Bytes = 1.2 MiB Load Address: 20008000 Entry Point: 20008000 Verifying Checksum ... OK Loading Kernel Image ... OK OK Starting kernel ... Uncompressing Linux... done, booting the kernel. Linux version 2.6.37 (nkinar at matilda) (gcc version 4.3.5 (Buildro ot 2011.02) ) #3 Sat Apr 2 17:28:21 CST 2011 CPU: ARM926EJ-S [41069265] revision 5 (ARMv5TEJ), cr=00053177 CPU: VIVT data cache, VIVT instruction cache Machine: Atmel AT91SAM9RL-EK Memory policy: ECC disabled, Data cache writeback Clocks: CPU 200 MHz, master 100 MHz, main 12.000 MHz Built 1 zonelists in Zone order, mobility grouping on. Total pages: 16256 Kernel command line: console=ttyS0,115200 mtdparts=flash:10M(kernel),100M(root),-(storage) rw rootfstype=ubifs PID hash table entries: 256 (order: -2, 1024 bytes) Dentry cache hash table entries: 8192 (order: 3, 32768 bytes) Inode-cache hash table entries: 4096 (order: 2, 16384 bytes) Memory: 64MB = 64MB total Memory: 62348k/62348k available, 3188k reserved, 0K highmem ... Why printf()? 5 / 18
  • 6. Tell me where you printf()! Typical GNU/Linux computer /usr/bin/date +"%Y" /usr/bin/xterm User-space Kernel-space ... printf("2018n") ... (Insanely) complex code dealing with consoles... Ingo Molnรกr (Linux kernel core developer): "The tty layer is one of the very few pieces of kernel code that scares the hell out of me :-)" 6 / 18
  • 7. Tell me where you printf()! Embedded systems or when display is not available /usr/bin/date +"%Y" User-space Kernel-space ... printf("2018n") ... Same (insanely) complex code dealing with consoles... Serial device (UART) driver HardwareSoftware Characters are sent one by one over a serial port 7 / 18
  • 8. A serial port on every board? My own phone! 8 / 18
  • 9. Playstation 4 Linux on PS4 PS4 controller A serial port on every board? 9 / 18
  • 10. How to print? putchar(): the cornerstone /* * Code for IBM-PC x86: write character to COM1 serial port * (taken from NuttX) */ void putchar(char ch) { /* Wait until the Transmitter Holding Register (THR) is empty. */ while ((inb(COM1_PORT+COM_LSR) & LSR_THRE) == 0); /* Then output the character to the THR */ outb(ch, COM1_PORT+COM_THR); } 10 / 18
  • 11. How to print? No formatting is simply puts() void my_printf(char *str) { /* Just print all the characters until the NULL terminator */ while (*str) putchar(*str++); } int main(void) { /* printf 101 */ my_printf("Hello world!n"); } $ ./a.out Hello world! $ 11 / 18
  • 12. How to print? With formatting... Input: Output: printf from A to Z, in 45 minutes!n For each placeholder, need to retrieve next parameter Depending on placeholder: '%s': get string '%c': get character '%d': convert integer into characters 12 / 18
  • 13. Variadic functions Example: function prototype #include <stdarg.h> /* Macro/function definitions for variadic functions */ #include <stdio.h> /* * Sum a variable number of integers * @count: the number of integer parameters * * Receive @count integers, sum them up and return the result */ int sum_ints(int count, ...) { /* ??? */ } int main(void) { /* sum up 3 integers: 10, 20 and 30 */ printf("Sum is %dn", sum_ints(3, 10, 20, 30)); /* sum up 5 integers: 10, 20, 30, 40, 50 */ printf("Sum is %dn", sum_ints(5, 10, 20, 30, 40, 50)); return 0; } 13 / 18
  • 14. Variadic functions Example: function implementation int sum_ints(int count, ...) { int i, sum = 0; va_list ap; va_start(ap, count); /* Init variable parameter list */ for (i = 0; i < count; i++) { int n = va_arg(ap, int); /* Get next integer parameter */ sum += n; } va_end(ap); /* Clean up parameter list */ return sum; } 14 / 18
  • 15. printf(): a simple implementation Let's code... 15 / 18
  • 16. printf("Tell me more!n"); Complex family of functions Call graph from musl (a lightweight libc implementation): vfprintf() in various C standard libraries: glibc: ~2400 SLOC uclibc: ~2000 SLOC musl: ~700 SLOC 16 / 18
  • 17. #include <stdio.h> int main(void) { char name[256]; fgets(name, 256, stdin); printf("Your name is: "); printf(name); return 0; } #include <stdio.h> int main(void) { char name[256]; fgets(name, 256, stdin); printf("Your name is: "); printf("%s", name); return 0; } $ ./a.out %s%s%s%s%s Your name is: %s%s%s%s%s $ ./a.out %s%s%s%s%s Segmentation fault (core dumped) $ ./a.out %08x.%08x.%08x.%08x.%08x.%08x Your name is: 00000020.00000000.00000000.0000 0003.f7fbc4c0.78383025 printf("Tell me more!n"); Security vulnerability: Uncontrolled format string 17 / 18