/*
 * aof.c
 *
 * Creating AOF files
 *
 *  1994-1998 Straylight
 */

/*----- Licensing note ----------------------------------------------------*
 *
 * This file is part of Straylight's AOF library (aoflib).
 *
 * Aoflib is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2, or (at your option)
 * any later version.
 *
 * Aoflib is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Aoflib.  If not, write to the Free Software Foundation,
 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "aof.h"
#include "chunk.h"

extern void aof_error(void);

int aof_fillBlock(void *p,size_t offset,size_t l,aof_chunkinfo *i)
{
  void *xp;
  if (offset+l>i->size)
  {
    i->size=(offset+l+255)&~255;
    xp=realloc(i->p,i->size);
    if (!xp)
      aof_error();
    i->p=xp;
  }
  memcpy(i->p+offset,p,l);
  return (offset);
}

int aof_addBlock(void *p,size_t l,aof_chunkinfo *i)
{
  aof_fillBlock(p,i->next,l,i);
  i->next+=l;
  return (i->next-l);
}

int aof_branch(int from,int to)
{
  return (0xEA000000 | (((to-from-8) & 0x03FFFFFC) >> 2));
}

void aof_reloc(char *name,int offset,int weak,aof_file *f)
{
  aof_symbol sym={0};
  aof_relocstr r={0};
  sym.name=aof_string(name,f->strt);
  sym.defined=0;
  sym.export=1;
  sym.weak=weak;
  r.offset=offset;
  r.t.type_1.symbol=aof_add(sym,f->symt)/sizeof(aof_symbol);
  r.t.type_1.field=aof_FULLWORD;
  r.t.type_1.type=aof_ADDITIVE;
  r.t.type_1.symreloc=1;

  aof_add(r,f->reloc);
}

void aof_reloc_b(char *name,int offset,aof_file *f)
{
  aof_symbol sym={0};
  aof_relocstr r={0};
  sym.name=aof_string(name,f->strt);
  sym.defined=0;
  sym.export=1;
  r.offset=offset;
  r.t.type_1.symbol=aof_add(sym,f->symt)/sizeof(aof_symbol);
  r.t.type_1.field=aof_FULLWORD;
  r.t.type_1.type=aof_PCRELATIVE;
  r.t.type_1.symreloc=1;
  aof_add(r,f->reloc);
}

void aof_roff(int offset,aof_file *f)
{
  aof_relocstr r={0};
  r.offset=offset;
  r.t.type_1.field=aof_FULLWORD;
  r.t.type_1.type=aof_ADDITIVE;
  r.t.type_1.symreloc=0;
  aof_add(r,f->reloc);
}

void aof_addsym(char *name,int offset,int local,int area,aof_file *f)
{
  aof_symbol sym={0};
  sym.name=aof_string(name,f->strt);
  sym.defined=1;
  sym.export=!local;
  sym.value=offset;
  sym.area=area;
  aof_add(sym,f->symt);
}
