; macroinstruction for importing functions in Linux

include '_elf.inc'

macro interpreter [library]
{
 db library,0
}

; creates symbols list with needed libraries.
macro import_proto library, [name, arg]
{
  common
    local str
    match needed,needed@dynamic \{ define needed@dynamic needed, str:library \}
    match ,needed@dynamic \{ define needed@dynamic str:library \}
  forward
    match imported, imported@dynamic \{ imported@dynamic equ imported, name \}
    match ,imported@dynamic \{ imported@dynamic equ name \}
    define name#@arg arg
}
define needed@dynamic
define imported@dynamic



macro define_import_arguments [argument] {
common
  virtual at ebp+8
forward
    argument dd ?
common
  end virtual
}


macro __do_import [name]
{
 common
  local strtab,strsz,symtab,rel,relsz,hash
  segment dynamic readable
  match needed,needed@dynamic
  \{ irp item,needed \\{ match str:library,item \\\{ dd DT_NEEDED,str-strtab \\\} \\} \}
  dd DT_STRTAB,strtab
  dd DT_STRSZ,strsz
  dd DT_SYMTAB,symtab
  dd DT_SYMENT,sizeof.Elf32_Sym
  dd DT_REL,rel
  dd DT_RELSZ,relsz
  dd DT_RELENT,sizeof.Elf32_Rel
  dd DT_HASH,hash
  dd DT_NULL,0
  segment readable writeable
  symtab: Elf32_Sym
 forward
  if used name
    local fstr
    Elf32_Sym fstr-strtab,0,0,STB_GLOBAL,STT_FUNC,0,0
  end if
 common
  rel:
  local counter
  counter = 1
 forward
   if used name
     Elf32_Rel name, counter, R_386_32
     counter = counter + 1
   end if
 common
  relsz = $-rel
  hash:
  dd 1,counter
  dd 0
  repeat counter
   if %=counter
    dd 0
   else
    dd %
   end if
  end repeat
  strtab db 0
 forward
  if used name
    fstr db `name,0
  end if
 common
  match needed,needed@dynamic
  \{ irp item,needed \\{ match str:library,item \\\{ str db library,0 \\\} \\} \}
  strsz = $-strtab
 forward
  if used name
    name dd 0
  else
    label name
  end if

  if name#@arg eq VOID
    .__info.argtype=1
  else
    if name#@arg eq NONE
      .__info.argtype = 0
    else
      match args, name#@arg \{ define_import_arguments args \}
      .__info.argtype = 2
    end if
  end if
}


macro ImportAll {
  match arguments, __do_import imported@dynamic \{ arguments \}
}

