1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
|
title:Undefine C
keywords:c,linux,asm
# Undefined C
There is possible to run piece of code inside online c compiler like https://www.onlinegdb.com/online_c_compiler
Or run locally. With base check is done with gcc compiler. There are many small tricks around running C code
in practice that aren't covered in any generic tutorials.
## Compile
__hello_world.c__
```c
int main() {
printf("Hello world\n");
}
```
```bash
gcc hello_world.c -o hello_world
gcc -m32 hello_world.c -o hello_world_32 #for 32bit target
```
## Syntax
### Variables
Standard list of available types
#### Check type size
All types have size that are declared in bytes. Some of the types are machine dependents.
like int/long, if there is needed machine independent types then there are int32_t/uint32_t/int64_t/uint64_t
Each architecture 8bit/16bit/32bit/64bit will have different size for those types
Use __sizeof()__
Running on x86 machine
```c
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
int main() {
printf("Sizeof int %lu\n",sizeof(int));
printf("Sizeof int32_t %lu\n",sizeof(int32_t));
printf("Sizeof int64_t %lu\n",sizeof(int64_t));
printf("Sizeof long %lu\n",sizeof(long));
printf("Sizeof long long %lu\n",sizeof(long long));
}
```
Most safest/portable way is to use [u]int[8/16/32/64]_t types.
Defined macros'es to get type max and min values are
https://en.cppreference.com/w/c/types/limits
```c
#include <limits.h>
int main() {
printf("INT_MIN %d\n",INT_MIN);
printf("INT_MAX %d\n", INT_MAX);
printf("LONG_MIN %ld\n",LONG_MIN);
}
```
Example from AVR __stdint.h__
https://github.com/avrdudes/avr-libc/blob/main/include/stdint.h
Example from Libc
https://sourceware.org/git/?p=glibc.git;a=blob;f=stdlib/stdint.h
#### How to shoot the leg
When code suppose to run on 32bit and 64bit platform the size of type may vary.
Need to take in account this case.
### Functions
Function syntax, there is nothing interesting on functions
```
<RETURN_TYPE> <NAME>(<TYPE> <NAME>,..) {
<EXPR>
}
```
Write simple function
```c
int fun1() {
return -1;
}
```
Function can have multiple return statements.
Here is example whne function have 3 return values.
```c
int fun2(int i) {
if (i<0) return -1;
if (i>0) return 1;
return 0;
}
```
Get address of function
```c
printf("fun1 address %016x",&fun1);//64bit platform
```
### If statement
```c
if () ;
if () {}
```
One of the way to check error of returned functions is
```c
if ((c = getfun()) == 0) {
}
```
Most simplest and outdated way to do this is when getting input from command line
```c
#include <stdio.h>
int main() {
int c;
char ch;
while ((c = getchar()) != EOF ) {
ch = c;
printf("Typed character %c\n",c);
}
}
```
### For cycle
For loop is one that may involve some trickery, its
as simple as
```c
for (<INITIAL>;<TERMINATE CONDITION>;<AFTER CYCLE>) {
}
```
Go over values from 1 till 10
```c
int i=0;
for (i=1;i<=10;i++) {
printf("%d\n",i)
}
```
Now lets do it from 10 till 1
```c
int i=0;
for (i=10;i>0;i--) {
printf("%d\n",i)
}
```
Now lets make one liner
```c
for (i=0;i<10;i++,printf("%d\n",i));
```
Yes there is possible to write as many expressions as needed.
### Structure
Structure allows to combine types under one new type. Structure is convenient way how to combine set
of types and reuse them as one.
```c
struct struct1 {
uint8_t a;
uint16_t b;
uint32_t c;
uint64_t d;
};
```
Total intuitive size of structure would be
```c
int total_szie = sizeof(uint8_t) + sizeof(uint16_t) + sizeof(uint32_t) + sizeof(uint64_t);
int real_size = sizeof(struct1);
```
Types are placed inside structure to make fast access to them. Some instructions of CPU may require
to access aligned memory addresses to not have penalty on accessing types inside structure.
To directly mess with alignment of types use attribute
```c
__attribute__ ((aligned (8)))
```
Use attributes to pack structure and be not architecture dependent.
```c
struct struct2 {
uint8_t a;
uint16_t b;
uint32_t c;
uint64_t d;
} __attribute__((packed));
```
Now let check size of structure after it packed
```c
int new_size = sizeof(struct2);
```
Also there is possible to add aligmnet to each time in structure
```c
struct struct3 {
uint8_t a __attribute__((aligned (8)));
uint16_t b __attribute__((aligned (8)));
uint32_t c __attribute__((aligned (8)));
uint64_t d __attribute__((aligned (8)));
} __attribute__((aligned (8)));
```
Now size of structure will be 32.
All results on amd64, other arch may differ.
### How to shoot leg
Forget that struct size is not consistent.
### Recursion
Recursion is technique that could be useful to write shorter code
and deal with cycles. One thing that recursion suffer is that it consumes
stack memory and its have default limit on platform.
```c
#include <stdio.h>
#include <stdlib.h>
int fun_r(int i) {
printf("val %d\n",i);
fun_r(i+1);
return 0;
}
int main()
{
fun_r(0);
}
```
Program will fail after its reach out of stack range.
When increase the default stack limit it go more further.
Check default stack size
```
ulimit -s
```
Set stack size
```
ulimit -s 16384
```
### Macro
There is many things useful as macros. There is many tricks in macros to emit
useful parts of code.
Define values, as its enum.
```c
#define VAL_0 0
#define VAL_1 1
#define VAL_LAST VAL_1
```
Multiline macro
```c
#define INC_FUN(TYPE) TYPE inc_##TYPE(a TYPE){\
TYPE c=1\
return a + c\
}
INC_FUN(int)
INC_FUN(char)
INC_FUN(double)
INC_FUN(notype)
```
to check code expansion of macro run
```
gcc -E <SOURCE_FILE>
```
http://main.lv/writeup/c_macro_tricks.md
https://jadlevesque.github.io/PPMP-Iceberg/
### Pointers
One the C most loved feature is pointers, they allow to access addresses without any sanity check
and they dont have any lifetime, so anything is possible with those.
Pointer contains address which is interpreted according of pointer type
```c
int c;
int ptr=&c;
```
Go over array of chars
```c
#include <stdio.h>
#include <stdlib.h>
int main() {
char s[]="asd";
char *c=&s;
while (*c != 0) {
printf("NExt char %c addr %016x\n",*c,c);
c++;
}
}
```
Go over array of ints
```c
int i=0;
int arr[] = {9,7,5,3,1};
int *ptr = arr;
while (i<5) {
printf("Number value %d addr %016x\n",*ptr, ptr);
ptr++;
i++;
}
```
Pointer arithmetics like +1 will move to next address that is offset of type size.
As example below structure size is 12, and increment of pointer to that structure
increment address to sizeof structure. And yes address is pointing to not mapped memory, so it
will segfault if accessed.
```c
struct size12 {
int a,b,c;
}
int main() {
struct size12 *s=0;
s++;
printf("%016x\n",s);
s++;
printf("%016x\n",s);
}
```
Double pointers are pointers to pointers
```c
#include <stdio.h>
int main(int argc, char **argv) {
char *arg = argv[0];
printf("Program name %s\n",arg);
}
```
#### How to shoot the leg
Run pointer in while loop incrementing pointer. It will stop only when segfaults.
Dont initialize pointer and it will have random value.
### Allocate memory
From programs perspective memory allocation is adding address range to executable that can be addressed.
malloc should be accompanied with free statement, otherwise it will have memory leaks.
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char *c = malloc(16);
memset(c,0,16);
int *arr = malloc(16*sizeof(int));
memset(arr,0,16*sizeof(int));
free(c);
free(arr);
}
```
### Signed/Unsigned
Signed and unsigned variables differ just in one bit interpretation. But they have different behavior on minimal and maximal values.
```c
#include <stdio.h>
#include <limits.h>
int main()
{
int i=INT_MAX;
unsigned int u=UINT_MAX;
printf("i=%d\n",i);
printf("u=%u\n",u);
i++;
u++;
printf("i=%d\n",i);
printf("u=%u\n",u);
i=0;
u=0;
i--;
u--;
printf("i=%d\n",i);
printf("u=%u\n",u);
}
```
### Endianess
```c
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
int main() {
int arr[4] = {0x00112233,0x44556677,0x8899AABB, 0xCCDDEEFF};
printf("%08x\n",arr[0]);
printf("%08x\n",arr[1]);
printf("%08x\n",arr[2]);
printf("%08x\n",arr[3]);
FILE *f = fopen("int.hex","w+");
fprintf(f,"%08x",arr[0]);
fprintf(f,"%08x",arr[1]);
fprintf(f,"%08x",arr[2]);
fprintf(f,"%08x",arr[3]);
fclose(f);
int fd=open("int.bin",O_CREAT|O_RDWR,S_IWUSR|S_IRUSR|S_IRGRP|S_IRWXO);
write(fd,arr,sizeof(arr));
close(fd);
int i;
fd = open("int.bin2",O_CREAT|O_RDWR,S_IWUSR|S_IRUSR|S_IRGRP|S_IRWXO);
for (i=0;i<4;i++) {
uint32_t val = (arr[i]>>16) &0x0000ffff;
val += (arr[i]<<16)&0xffff0000;
write(fd,&val,sizeof(uint32_t));
}
close(fd);
}
```
While saving formated values to file you will get what you expect
```
$ cat int.hex
00112233445566778899aabbccddeeff
```
Saving just memory dump of all values, will give you different result
```
$ hexdump int.bin
0000000 2233 0011 6677 4455 aabb 8899 eeff ccdd
0000010
```
Need to swap 16bit pairs to look same as value memory dump
```
$ hexdump int.bin2
0000000 0011 2233 4455 6677 8899 aabb ccdd eeff
0000010
```
### Compiler flags
Compiler have whole list of command line arguments that you can enable for different purposes, lets look into some of them
https://gcc.gnu.org/onlinedocs/gcc/Option-Summary.html
### Static binary
### Dynamic binary
### stdin,stdout,stderr
### Styles
## Basic usage
### File manipulation with libc
### File manipulation with syscalls
## Base usage
### Kernel module
### Write plugins
## Advanced cases
### Linking
### Extern
### Attributes
### Creating shared library
### Create static libraries
### Join all objects together
### Compile with musl
### Inspect elf files
### No standard library
### Memory leaks
### Code coverage
### Profiling
### Canary
### Atomic
### Multithreading
## Embedding
### Embed in C++
### Embed in Go
### Embed in Swift
### Embed in JS
### Lua in C
### Python in C
## Multiplatform
### Cross compile
### Different flags
### Check architecture
### ARMv8
### AVR8
### Emscripten
## Graphics
### SDL2
### GTK
### OpenGL
### Generate image
|