-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCompilers.txt
More file actions
905 lines (680 loc) · 27.1 KB
/
Compilers.txt
File metadata and controls
905 lines (680 loc) · 27.1 KB
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
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
@@@@@@@@@@@@@@@@@@@@@@@ GCC @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
What are .LXXX labels in assembly?
.L prefix indicates label is local to this file and so it will not
conflict with same name labels in other files.
.LFB0 = Function Begin 0 (1st function)
.LFE0 = End of 1st Function
.LFB1 = 2nd Function Begin
etc
GCC Flags:
-fno-asynchronous-unwind-tables
Call Frame Information [1] tags are used by GCC Assembler to
reconstruct a stack backtrace. Some of .cfi labels look like:
.cfi_start_proc
.cfi_def_cfa_offset
.cfi_end_proc
.cfi_offset_cfa_register
// CFA = Call Frame Address
// CFI = Call Frame Information
.cfi_start_proc
Beginning of a function; must have a corresponding end.
.cfi_end_proc
End of a function.
.cfi_def_cfa <register>, <offset>
Define a rule for computing CFA as "take address from register and add
offset to it"
.cfi_offset <register>, <offset>
Previous value of <register> is saved at offset <offset> from CFA
.cfi_def_cfa_register <register>
From now on <register> will be used instead of old one for computing CFA.
.cfi_def_cfa_offset <offset>
Modify a rule for computing CFA. Register remains the same, but offset is
new. Note that it is the absolute offset that will be added to a defined
register to compute CFA address.
-c Compile or assemble the source, but don't link.
-S Stop after compilation. Don't assemble.
-E Stop after preprocessing. Don't compile.
-o <file> Place output in <file.
-v Print the commands executed to run stages of compilation.
Reference:
[1] http://en.wikipedia.org/wiki/Call_stack#Structure Call Frame Information
[2] https://gcc.gnu.org/onlinedocs/gcc-5.2.0/gcc/
[3] https://sourceware.org/binutils/docs-2.17/as/CFI-directives.html#CFI-directives
@@@@@@@@@@@@@@@@@@@@@@@@@@ GDB Commands @@@@@@@@@@@@@@@@@@@@@@@@@@@
(gdb) frame <number> // jump to corresponding frame.
(gdb) info frame // Quite a lot of details of the frame.
(gdb) list // +/- few lines around code of interest.
(gdb)
Examining Memory
----------------
(gdb) x/nfu addr
x - examine memory (can also use p)
n - repeat count; how many times to show
f - format
s = null terminated string
i = assembly, machine instruction
x = hex opcode
u - unit size
b = bytes
h = half words (2 bytes)
w = words (4 bytes)
g = giant words (8 bytes)
- Order of unit size and formatting unit doesn't matter
Example:
(gdb) x/3uh 0x54320
Display 3 halfwords(h) of memory, formatted as unsigned decimal(u),
starting at 0x54320.
(gdb) x/4xw $sp
Prints 4 words(w) of memory in hex(x) above stack pointer($sp)
n-curses Window (TUI mode: Text User Interface)
---
- Ctrl+xa, doing same thing switches to CLI
- Ctrl+l, repaints the screen, if chars are distorted
- Ctrl+x2, gives 2 windows
Reference:
[1] http://www.delorie.com/gnu/docs/gdb/gdb_toc.html
@@@@@@@@@@@@@@@@@@@@@@@@@@ GDB Process Record @@@@@@@@@@@@@@@@@@@@@@@@@@@
// You can start 'recording' any time after 'run'.
(gdb) record // or 'target record' to start recording
(gdb) record stop // to stop recording
(gdb) record delete // to delete recording
(gdb) record save <filename> // default filename is gdb_record.process_id
(gdb) record restore <filename> // restore execution log from <filename>
- If you run till end of program, but process record will ask and stop recording
- All gdb commands have counter commands, in reverse direction
continue; reverse-continue
next; reverse-next
step; reverse-step
finish; reverse-finish
- We can set execution direction
(gdb) set exec-direction reverse
(gdb) set exec-direction forward
(gdb) show exec-direction
- Set the number of instructions to be recorded
(gdb) show record insn-number-max
Record/replay buffer limit is 200000.
(gdb) set record insn-number-max 400000
(gdb)
- Memory/Buffer layout. Internal memory can be treated as linear or circular.
- If linear then when limit is reached, recording is stopped.
- If treated as circular then recording can go forever but memory is
overwritten. So, recording can't go back to the beginning.
(gdb) show record stop-at-limit
Whether record/replay stops when record/replay buffer becomes full is on.
(gdb) set record stop-at-limit off
(gdb)
- Show how many instructions are saved in memory
(gdb) info record insn-number
Record instruction number is 1287.
(gdb)
Reference:
[1] https://sourceware.org/gdb/wiki/ProcessRecord/Tutorial
@@@@@@@@@@@@@@@@@@@@@@@@@@ GDB Macros @@@@@@@@@@@@@@@@@@@@@@@@@@@
GDB macro-coding language basic structure:
define <command>
<code>
end
document <command>
<help text>
end
When <command> is run, <code> is executed.
When help <command> is run, the <help text> is displayed.
Enter this code in .gdbinit file and run GDB.
Simple example: clear screen
define cls
shell clear
end
document cls
Clears the screen with a simple command
end
User defined variables:
set $<var name>=<expression>
set $c=*(unsigned char *)($arg0)
Conditional Loops:
if - else - end
Same as other if() conditionals
while - end
Same as other while() loop
Calling user defined macros inside another macro:
<macro name> <arguments>
Read up more at [1]
References:
[1] http://www.ibm.com/developerworks/aix/library/au-gdb.html
@@@@@@@@@@@@@@@@@@ OTOOL NOTES @@@@@@@@@@@@@@@@@@@@@@@@@
'otool' comes as part of Xcode Tools that can act as replacement for
'objdump'. Objdump can be installed as part of binutils[1] but it is not
installed by default on Mac. Homebrew has it.
Here are few flags of otool that I found useful:
Sample Usage:
otool [ options ] <file> [ <file2> ... ]
Options:
-l Load commands are displayed.
-t Contents of __TEXT__ is displayed. Combined with -v flag to
disassemble the text. Use -V to symbolically disassemble the
operands.
Useful: otool -tVX test.o
-d Display __DATA__ section.
-r relocation entries.
-X avoid printing leading addresses.
'dwarftool' (or dwarfdump) is another option that's available on Mac. It
is used only to dump/disassemble DWARF information from object file. More
to come ...
References:
[1] http://binutils.darwinports.com
@@@@@@@@@@@@@@@@@@ EXAMINING (SHARED) LIBRARY FILES @@@@@@@@@@@@@@@@@@
$ ldd -r lib.so
@@@@@@@@@@@@@@@@@@@@@@@@@ MAKEFILE NOTES @@@@@@@@@@@@@@@@@@@@@@@
Symbols/Notations
---
$@ The file name of the target.
$% The target member name, when the target is an archive member.
$< The name of the first (or only) prerequisite/dependency.
$? The names of all the prerequisites that are newer than the target separated by spaces.
$^ The names of all dependencies separated by space, but duplicates removed.
$+ The names of all the prerequisites, with spaces between them. The value of $^ omits duplicate prerequisites, while $+ retains them and preserves their order.
$* The stem with which an implicit rule matches.
$(@D)
$(@F) The directory part and the file-within-directory part of $@
$(*D)
$(*F) The directory part and the file-within-directory part of $*
$(%D)
$(%F) The directory part and the file-within-directory part of $%
$(<D)
$(<F) The directory part and the file-within-directory part of $<
$(^D)
$(^F) The directory part and the file-within-directory part of $^
$(+D)
$(+F) The directory part and the file-within-directory part of $+
$(?D)
$(?F) The directory part and the file-within-directory part of $?
Debugging make
---
- make can be debug by passing -d flag. This can spit out lot of details.
$ make -d
$ make --debug // this is same as make
$ make --debug=FLAGS
where FLAGS can be:
a - for all debugging. Same as 'make -d' and 'make --debug'
b - for basic debugging
v - slightly more verbose basic debugging.
i - implicit rules
j - invocation info
m - info during makefile remakes
>>>> Notes from [5]
Drawbacks:
---
- 'make' itself is not bad or buggy. But the way Makefiles are constructed,
particularly for large projects, 'make' becomes very inefficient.
- Makefiles are poorly written and don't capture correct dependencies and
create incorrect DAGs (Direct Acyclic Graph).
- make is a macro language. It reads dependencies as strings and uses Deferred
Evaluation. Hence it keeps replacing variables with strings.
- Order of dependency evaluation effects the build. To overcome, make is
repeated or Makefile is written to clean up object files (overkill).
Efficiently writing Makefiles:
---
- Use Immediate Evaluation wherever possible.
- Use single, project level Makefile and use module.mk for modules.
- Use make's 'include' functionality.
- Use VPATH Semantics to build 'Sand Boxes'
Including Other Makefiles [6]
---
include filenames ...
- 'include' directive tells make to suspend reading current makefile and read
one or more makefiles before continuing.
- 'filenames' can contain shell patterns. For example, if you have 3 .mk files
(a.mk, b.mk, c.mk) and $(bar) expands to 'bish bash' then:
include foo *.mk $(bar)
is equivalent to
include foo a.mk b.mk c.mk bish bash
- Having a '-' before include indicates that if there's any error, do not throw
to stdout.
Double-Colon Rules [7]
---
Reference:
[1] http://www.schacherer.de/frank/technology/tools/make.html
[2] https://www.gnu.org/software/make/manual/html_node/Quick-Reference.html
[3] http://martinvseticka.eu/temp/make/normal.html
[4] http://www2.inf.fh-brs.de/~rberre2m/sonstiges/make_short.pdf
[5] http://aegis.sourceforge.net/auug97.pdf
[6] https://www.gnu.org/software/make/manual/html_node/Include.html
[7] https://www.gnu.org/software/make/manual/html_node/Double_002dColon.html#Double_002dColon
@@@@@@@@@@@@@@@@@@@@@@@@@@@@ Yocto Project @@@@@@@@@@@@@@@@@@@@@@@@@@@
- What is purpose of Yocto Project?
* To build custom linux OS for any embedded devices.
* It is NOT an embedded linux distribution. It creates one for you.
- Hosted by Linux Foundation.
- The build system used by Yocto is called Poky.
Poky = BitBake + Metadata
Poky = Build system used by Yocto Project.
BitBake = Task executor and scheduler.
Metadata = Task definitions
* Configuration (.config) = global defs of variables, such as compiler
flags, location of image paths, machine archs etc.
* Classes (.bbclass) = encaps and inheritance of build logic, packaging etc.
This does most heavy lifting in system. There are .bbclass for
'how to build linux kernel', 'how to generate rpm package', 'how
create root file system image' and so on.
* Recipes (.bb) = Logical units of software/images to build, ex. recipe for
GNU tar command, GTK library, and so on. Recipes are also used
define what packages get included in your final image.
Recipe = Set of instructions for building packages including
* where to obtain upstream sources and which patches to apply.
* dependencies.
* configurations/compilation options.
* define what files go in to what output packages. Like documentation has
it's own package.
Build System Workflow:
- Build process starts by setting shell env for the build: oe-init-build-env.
- Sourcing above file creates config files and shell scripts that Poky uses.
- Poky verifies if system reqs have been met to create minimal image.
- During creation of image, bitbake does following
* include additional layers
* include classes, tasks or recipes
* create ordered, weighted dependency chain in form of a map.
- BitBake uses this map to order task executions. Tasks required most by other
tasks have higher weight and executed earlier.
- BitBake spawns threads for each task and begins executing.
- Tasks can be modified using recipe.
Poky Build System Concepts:
---------------------------
- In Poky, every aspect of build system is controlled by metadata.
- Loosely, metadata is combination of config files and package recipes.
- Recipe contains data used by BitBake. BitBake can use this to set additional
variables or build-time tasks.
- Config files are 2 types:
* Those configuring BitBake and overall build process
* Those configuring layers that Poky uses
- A layer is grouping of metadata to provide some additional functionality
// It all seems so hand-wavy at this point to me :(
- Sourcing oe-build-init-env generates bblayers.conf as first of the many
config files. This contains BBLAYERS, which BitBake uses in building.
bblayers.conf looks like this:
# LAYER_CONF_VERSION is increased each time build/conf/bblayers.conf
# changes incompatibly
LCONF_VERSION = "4"
BBFILES ?= ""
BBLAYERS = " \
/home/eflanagan/poky/meta \
/home/eflanagan/poky/meta-yocto \
/home/eflanagan/poky/meta-intel/crownbay \
/home/eflanagan/poky/meta-x32 \
/home/eflanagan/poky/meta-baryon\
/home/eflanagan/poky/meta-myproject \
"
- After parsing bblayers.conf, BitBake parses conf/layers.conf file
- After that, it adds additional recipes, classes and configuration to the
build.
(Example of meta-baryon layer: git://git.yoctoproject.org/meta-baryon)
Custom Layer (meta-myproject)
-----------------------------
Sofware Layer (meta-baryon)
Additional Layers -----------------------------
Kernel Enablement Layer (experimental/meta-x32)
-----------------------------
Hardware Enablement Layer
(meta-intel/meta-fsl-ppc)
==========================================================
Yocto Layer (./meta-yocto)
Default Layers --------------------------
OE-Core (./meta)
- BitBake config files generate BitBake datastore which is used during
creation of task execution queue.
- BitBakes "BBCooker" class is started at beginning of build.
- BBCooker builds task execution queue by "Baking" the "Recipes".
- BBCooker's "parseConfigurationFiles" method first looks for bblayers.conf
file
- After this, BitBake parses each layer's layer.conf file
- After this, BitBake parses bitbake.conf
Recipe has following.
Summary:
Description:
Homepage:
License:
Depends: // declare build time dependencies.
SRC_URI:
// Variable PV is used to indicate Packet Version. Usually, recipes have
// version number in it's name (like: ethtool_2.6.36.bb). PV indicates
// 2.6.36 in this case.
- Standard Recipe Build Steps:
* Following functions are typical steps. They can be overridden when needed.
do_fetch
do_unpack
do_patch
do_configure
do_compile
do_install
do_package
+ LAYERS:
- Powerful software abstraction used by Yocto build system.
- Yocto build system consists of many layers.
- Layer is a logical collection of recipes representing Core, BSP (Board
Support Package) or an application stack.
- All layers have a priority and can override policy and config settings of
layers beneath it.
+ Example usage of layers:
Developer-Specific Layer
Commercial Layer (from OSV)
UI Specific Layer
Hardware Specific BSP
Yocto Specific Layer Metadata (meta-yocto)
OpenEmbedded Core Metadata (oe-core)
BitBake Architecture
====================
Resources:
[1] Getting Started with Yocto Project:
https://vimeo.com/36450321
[2] http://aosabook.org/en/yocto.html
@@@@@@@@@@@@@@@ AUTOTOOLS @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
- Common name for autoconf, automake, libtool etc
- Autotools: What do user do, a very simplified view.
./configure --> Makefile
// probes the build system and generate Makefile
make
// uses Makefile
make install
configure.ac -------> autoconf ------> ./configure ----+
| ^ |
| | |
Makefile.in ----v---> automake ---> Makefile.in--+ |
|
Makefile <----+
|
|
|
v
make
|
v
make install
- autoconf and automake are invoked in order using autoreconf.
-
[1]
https://www.youtube.com/watch?v=4q_inV9M_us&index=1&list=WL
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// GCC flags:
// gets preprocessed file, object file and assembly output
gcc test.c -save-temps
// Assembly
gcc -S test.c
// Output of all gcc passes, after GIMPLE
gcc -dapA test.c
// Includes GIMPLE output in above output
gcc -fdump-tree-all -dapA test.c
$ gcc -c -S test.c
/* generates a test.s assembly file */
$ gcc -g -c test.c
/* generates test.o object file, with debug symbols present (-g flag) */
$ objdump
$ readelf
$ nm
$ strings
$ size <object or exec file>
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ readelf commands @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
/* header info */
$ readelf --file-header <elf-file>
Ex:
$ readelf --file-header vim.core
ELF Header:
Magic: 7f 45 4c 46 02 01 01 09 00 00 00 00 00 00 00 00
Class: ELF64
Data: 2's complement, little endian
Version: 1 (current)
OS/ABI: UNIX - FreeBSD
ABI Version: 0
Type: CORE (Core file)
Machine: Advanced Micro Devices X86-64
Version: 0x1
Entry point address: 0x0
Start of program headers: 64 (bytes into file)
Start of section headers: 0 (bytes into file)
Flags: 0x0
Size of this header: 64 (bytes)
Size of program headers: 56 (bytes)
Number of program headers: 79
Size of section headers: 64 (bytes)
Number of section headers: 0
Section header string table index: 0
/* notes sections of elf-files have more info about the file (like .core files) */
$ readelf --notes <elf-file>
Ex:
$ readelf --notes vim.core
Notes at offset 0x00001188 with length 0x0000ad18:
Owner Data size Description
FreeBSD 0x00000078 NT_PRPSINFO (prpsinfo structure)
FreeBSD 0x000000e0 NT_PRSTATUS (prstatus structure)
FreeBSD 0x00000200 NT_FPREGSET (floating point registers)
FreeBSD 0x00000018 NT_THRMISC (thrmisc structure)
FreeBSD 0x000000e0 NT_PRSTATUS (prstatus structure)
FreeBSD 0x00000200 NT_FPREGSET (floating point registers)
FreeBSD 0x00000018 NT_THRMISC (thrmisc structure)
FreeBSD 0x00000884 NT_PROCSTAT_PROC (proc data)
FreeBSD 0x0000156c NT_PROCSTAT_FILES (files data)
FreeBSD 0x00008574 NT_PROCSTAT_VMMAP (vmmap data)
FreeBSD 0x00000008 NT_PROCSTAT_GROUPS (groups data)
FreeBSD 0x00000006 NT_PROCSTAT_UMASK (umask data)
FreeBSD 0x000000d4 NT_PROCSTAT_RLIMIT (rlimit data)
FreeBSD 0x00000008 NT_PROCSTAT_OSREL (osreldate data)
FreeBSD 0x0000000c NT_PROCSTAT_PSSTRINGS (ps_strings data)
FreeBSD 0x00000114 NT_PROCSTAT_AUXV (auxv data)
/* segments info. Segments are info on chunks of code from various files that a
* process/binary includes. */
$ readelf --segments <elf-file>
Reference:
[1] Section 3 in:
https://gcc.gnu.org/onlinedocs/gcc-5.2.0/gcc/
[2] Info on coredump:
http://backtrace.io/blog/blog/2015/10/03/whats-a-coredump/
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ objdump commands @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
-f header info
-p more specific object file format
-h Section headers
-x ALL headers (file and section) in one command
-d Assembler contents of executable portions of object file
-s Full contents of all sections
-g Debug info
-t Contents of symbol table
-T Contents of Dynamic symbol table
-R Relocation entries in file
-j <section-name> Display specific section
Reference:
[1]
http://www.thegeekstuff.com/2012/09/objdump-examples/?utm_source=feedburner
@@@@@@@@@@@@@@@@@@ PROGRAMMING PARADIGMS @@@@@@@@@@@@@@@@@
- Data types (in C/C++)
* bool
* char - 1 byte
* short - 2 bytes
* int - 4 bytes
* long - 4 bytes
* float - 4 bytes
* double - 8 bytes
- Two's complement representation is used for negative numbers because it's
easy to do binary add/subtract
Ex: I want a + (-a) = 0. To do this, how to represent (-a)?
Two's complement representation was born
- When down casting or up casting variables, bytes are truncated or added. In
case of negative numbers, 'Sign Extension' happens
char c = 'A';
int i = c; // i gets 65
short s = 67;
int i = 67; // lower 2 bytes of i will have 67
short s = -1; // 111...11 (sixteen 1's)
int i = s; // 111...11 (thirty two 1's) - This is Sign Extension
- How are floating points represented?
7.5 = 0001 1111 0000 0000 // last 2 bytes
bits: 1 8 23
+---+-------------------+-------------------------------------------+
| | | |
+---+-------------------+-------------------------------------------+
1: Signed bit
8: Unsigned number BEFORE the decimal point
23: Number AFTER the decimal point
// WIP
// Listen to Lec 2 from 39th minute
Lec 3-7:
=====
short s = 45; // 2 bytes
double d = *(doube *)&s; // d will point to s and following 6 bytes is
// assumed part of d
Q: What about endianness?
- Memory layout for structs
struct fraction {
int num;
int denom;
};
struct fraction pi;
&pi and &(pi.num) will have same address
- Memory layout for arrays
int array[10];
// The following are synonymous
// array and &array[0]
// *array and array[0]
// array+k and &array[k]
// *(array+k) and array[k]
- Generics in C
void swap(void *vp1, void *vp2, int sz) { // sz is # of bytes of being
// swapped
char buf[sz];
memcpy(buf, vp1, sz);
memcpy(vp1, vp2, sz);
memcpy(vp2, buf, sz);
}
void *lsearch(void *key, void *base, int n, int elemSize) {
for(int i=0; i<n; i++) {
// note the type cast of char *
void *elem = (char *)base + (i * elemSize);
// doesn't work well for structs, char *, function pointers
// works for standard data types
if(memcmp(key, elem, elemSize)==0) {
return elem;
}
}
return NULL;
}
// We are assuming cmpFunc takes care of comparisons
void *lsearch(void *key, void *base, int n, int elemSize,
int (*cmpFunc)(void *, void *)) {
for(int i=0; i<n; i++) {
void *elem = (char *)base + (i * elemSize);
if(cmpFunc(key, elem)==0) {
return elem;
}
}
return NULL;
}
int cmpFunc(void *elem1, void *elem2) {
int *ip1 = elem1; // implicit type casting
int *ip2 = elem2;
return *ip1 - *ip2;
}
// Generic Stack API
typedef struct {
void *head;
int elemSize;
int logLength;
int allocLength;
} stack;
void StackNew(stack *s, int elemSize) {
if(s == NULL) // this shouldn't happen
return;
s->elemSize = elemSize;
s->logLength = 0;
s->allocLength = CAPACITY;
s->head = malloc(CAPACITY * elemSize);
}
void StackDispose(stack *s) {
free(s->head);
}
static void StackGrow(stack *s) {
s->allocLength *= 2;
s->head = realloc(s->head, s->allocLength * s->elemSize);
}
void StackPush(stack *s, void *elemAddress) {
if(s->logLength == s->allocLength) {
StackGrow(s);
}
void *target = (char *) s->head + s->logLength * s->elemSize;
memcpy(target, elemAddress, s->elemSize);
s->logLength++;
}
void StackPop(stack *s, void *elemAddr) {
// check for zero elements??
void *src = (char *)s->head + s->logLength * s->elemSize;
memcpy(elemAddr, src, s->elemSize);
s->logLength--;
}
Lec 8:
=====
Heap Memory Layout
---
- When a program starts, the Heap memory address range is advertised to malloc
library that maintains the Heap.
- 4 or 8 bytes of book keeping at beginning of each malloc() returned to
client (or requester). Address of B is returned to client.
A B C
+---+------------------------------------------------------+
| | |
| | |
| | |
+---+------------------------------------------------------+
- free(B) knows that meta data is stores at A (4 bytes back) and uses it to
free the memory.
- What is saved at A?
* If memory at B is already allocated then it has size of requested memory
+ Some extra info may be there indicating what comes after
* If not, it has size of available free memory and linked list to next
available free memory.
- Linked list of free nodes are maintained in Heap. There may be other
algorithms
* slabs of memory is one (512, 1024, 2048 byte slabs)
* linked list of free memory for each slab available
* coalescing of free memory and all such things are done
- Activation Record (goes in a Stack Frame)
* It's the memory for local variables inside a function.
Lec 9:
======
Mock Assembly Instructions
M[R1 + 4] = 10; // Store 10 in to memory region at R1 + 4
R2 = M[R1 + 4]; // Load operation
R3 = R2 + 7; // ALU operation
M[R1] = R3; // Store op
R2 = M[R1];
R2 = R2 + 1;
- There are 6 relational operators between two integers (or int types)
<, <=, >, >=, ==, !=
- How will following code translate to assembly look like?
int arr[4];
int i;
for(i=0; i<4; i++) {
arr[i] = 0;
}
i--;
Few things to look for in assembly:
* i<4 test
* for loop operation (jump/branch instruction)
* array implementation
Lec 10:
=======
Activation Records
---
- Area of memory on stack that contains function local variables
void foo(int bar, int *baz) {
char sink[4];
short *why;
}
|<----- 4 bytes ----->|
+-----------------------+
| | baz (has address to int var)
+-----------------------+
| | bar
+-----------------------+
| | RESERVED (or Return Address??)
+-----------------------+
| | sink[0..3]
+-----------------------+
| | why (has address to short var)
+-----------------------+
- Above memory layout is how an activation record looks like.
Reference:
[1] Jerry Cain's lectures at Stanford on "Programming Paradigms"