
/*
 * out.c
 *
 * (C) Copyright 1995 Archie L. Cobbs
 */

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "util.h"
#include "error.h"
#include "names.h"
#include "obj.h"
#include "link.h"

/*
 * WriteObj()
 *
 * Write out object file
 */

void
WriteObj(FILE *fp, struct ObjHeader *hdr)
{

/* Write incomplete header */

	hdr->n_magic = 0;
	if (fwrite(hdr, sizeof(*hdr), 1, fp) != 1)
	{
		perror("fwrite");
		cerror("can't write object header");
	}

/* Write text segment */

	if (fwrite(gSegBuffer[CodeSegment], 1, hdr->n_text, fp) != hdr->n_text)
	{
		if (ferror(fp))
			perror("fwrite");
		cerror("can't write text segment");
	}

/* Write data segment */

	if (fwrite(gSegBuffer[DataSegment], 1, hdr->n_data, fp) != hdr->n_data)
	{
		if (ferror(fp))
			perror("fwrite");
		cerror("can't write data segment");
	}

/* Write text relocations */

	if (fwrite(gRelocs[CodeSegment], sizeof(struct ObjReloc),
		hdr->n_treloc, fp) != hdr->n_treloc)
	{
		if (ferror(fp))
			perror("fwrite");
		cerror("can't write text relocs");
	}

/* Write data relocations */

	if (fwrite(gRelocs[DataSegment], sizeof(struct ObjReloc),
		hdr->n_dreloc, fp) != hdr->n_dreloc)
	{
		if (ferror(fp))
			perror("fwrite");
		cerror("can't write data relocs");
	}

/* Write symbols */

	if (hdr->n_symbols != SymWrite(fp))
		assert(0);

/* Write strings */

	hdr->n_strings = NamesDump(fp, gNames);

/* Rewrite completed header */

	hdr->n_magic = OBJ_HEADER_MAGIC;

	rewind(fp);
	if (fwrite(hdr, sizeof(*hdr), 1, fp) != 1)
	{
		perror("fwrite");
		cerror("can't write object header");
	}
}

