#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/param.h>
#include "parser.h"
#include "trace.h"
#include "db.h"
#include "util.h"
#include "errlog.h"
FILE *Bodyfp = NULL;
FILE *Headfp = NULL;
FILE *Mapfp = NULL;
static char headfile_name[MAXLINE];
static char mapfile_name[MAXLINE];
static int alt_code_file(void);
static void abort_code_file(void);
int
open_code_file(void)
{
char *dir = db_get_target_directory();
char *body_file_name;
int rc = YES;
errlog(BEGIN, "open_code_file() {");
(void) snprintf(headfile_name, sizeof (headfile_name), "%s.c",
db_get_output_file());
if ((Headfp = fopen(headfile_name, "w")) == NULL) {
errlog(FATAL, "%s: %s", headfile_name, strerror(errno));
}
(void) snprintf(mapfile_name, sizeof (mapfile_name), "%s-vers",
db_get_output_file());
if ((Mapfp = fopen(mapfile_name, "w")) == NULL) {
errlog(FATAL, "%s: %s", mapfile_name, strerror(errno));
}
(void) fputs("SUNWabi_1.1 {\n global:\n", Mapfp);
if ((body_file_name = tempnam(dir, NULL)) == NULL) {
errlog(FATAL, "out of memory creating a temp-file name");
}
if ((Bodyfp = fopen(body_file_name, "w+")) == NULL) {
errlog(FATAL, "%s: %s", body_file_name, strerror(errno));
}
if (unlink(body_file_name) != 0) {
errlog(FATAL, "unlink %s: %s", body_file_name, strerror(errno));
}
(void) free(body_file_name);
errlog(END, "}");
return (rc);
}
static void
abort_code_file(void)
{
errlog(BEGIN, "abort_code_file() {");
(void) fclose(Bodyfp);
(void) fclose(Headfp);
if (unlink(headfile_name) != 0) {
errlog(FATAL, "unlink %s: %s", headfile_name, strerror(errno));
}
errlog(END, "}");
}
int
alt_code_file(void)
{
char hfn[MAXLINE];
FILE *hfp;
abort_code_file();
(void) snprintf(hfn, sizeof (hfn), "%s.c", db_get_output_file());
if ((hfp = fopen(hfn, "w")) == NULL) {
errlog(FATAL, "%s: %s", headfile_name, strerror(errno));
}
(void) fputs("static int __abi_place_holder;\n", hfp);
(void) fclose(hfp);
return (YES);
}
int
commit_code_file(void)
{
char copy_buffer[BUFSIZ*8];
size_t n;
errlog(BEGIN, "commit_code_file() {");
(void) fputs(" local:\n\t*;\n};\n", Mapfp);
if (fclose(Mapfp) != 0) {
errlog(FATAL, "fclose %s: %s", mapfile_name, strerror(errno));
}
if (ftell(Bodyfp) == 0) {
errlog(END, "}");
return (alt_code_file());
} else {
rewind(Bodyfp);
while ((n = fread(copy_buffer, 1,
sizeof (copy_buffer), Bodyfp)) != 0) {
(void) fwrite(copy_buffer, 1, n, Headfp);
}
(void) fclose(Bodyfp);
if (fclose(Headfp) != 0) {
errlog(FATAL, "fclose <temp file>: %s",
strerror(errno));
}
}
errlog(END, "}");
return (YES);
}