Skip to content

Comment on The Art of Assembly Language (1996)parent

Comments

If you know how to construct data structures in C, it's pretty straightforward to construct them in assembly language. In asm you tend to lose the benefit of arrays being a type. In x86 you have powerful addressing modes (the different ways you can calculate a memory address) which are normally encoded with modrm and sib bytes after the opcode. An example where eax, rbx, and rcx are registers:

  ; eax = rbx[rcx] where rbx points to the base of an array of dwords
  mov eax, [rcx*4 + rbx]
  ; => 8B 04 8B
  ; where the first 8B is the opcode for this version of mov, 04 is the modrm byte saying
  ; to mov the value into eax as well as that there will be a sib (scale/index/base)
  ; byte following specifying the data source, and then 8B specifying everything in the []'s.
  ; If we were moving into ecx, the modrm byte would be 0C because a the 3-bit 
  ; register specification portion of modrm would change to specify ecx.
If you are optimizing for size (which can be a fun exercise) there are other ways of iterating through "arrays" of bytes such as the various string instructions [1] (though these tend to be slower on modern processors because they are microcoded). This gets into designing your code to use registers which are used implicitly by small instructions reducing the need for modrm/sib bytes in the instruction bytes [2].

Another example might be:

  lodsd      ; eax = *rsi++  : "AD" (one byte opcode using implicit src/dst operands)
  shl eax, 2 ; eax *= 4      : "C1 E0 02" where C1 specifying shl instruction
             ;                 E0 specifying eax and immediate constant 
             ;                 02 the constant to shift eax by (this is a mul by 4)
  stosd      ; *rdi++ = eax  : "AB" store into destination (one byte opcode)
It's not hard to imagine that being in a loop to iterate over the contents of an array. Hash tables are just the way they are in C really.

[1] http://www.felixcloutier.com/x86/LODS:LODSB:LODSW:LODSD:LODS... (there are others)

[2] https://www.swansontec.com/sregisters.html

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.