#include "Profiling.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
static char *SavedArgs = 0;
static unsigned SavedArgsLength = 0;
static const char *OutputFilename = "llvmprof.out";
int save_arguments(int argc, const char **argv) {
unsigned Length, i;
if (SavedArgs || !argv) return argc;
while (argc > 1 && !strncmp(argv[1], "-llvmprof-", 10)) {
const char *Arg = argv[1];
memmove(&argv[1], &argv[2], (argc-1)*sizeof(char*));
--argc;
if (!strcmp(Arg, "-llvmprof-output")) {
if (argc == 1)
puts("-llvmprof-output requires a filename argument!");
else {
OutputFilename = strdup(argv[1]);
memmove(&argv[1], &argv[2], (argc-1)*sizeof(char*));
--argc;
}
} else {
printf("Unknown option to the profiler runtime: '%s' - ignored.\n", Arg);
}
}
for (Length = 0, i = 0; i != (unsigned)argc; ++i)
Length += strlen(argv[i])+1;
SavedArgs = (char*)malloc(Length);
for (Length = 0, i = 0; i != (unsigned)argc; ++i) {
unsigned Len = strlen(argv[i]);
memcpy(SavedArgs+Length, argv[i], Len);
Length += Len;
SavedArgs[Length++] = ' ';
}
SavedArgsLength = Length;
return argc;
}
void write_profiling_data(enum ProfilingType PT, unsigned *Start,
unsigned NumElements) {
static int OutFile = -1;
int PTy;
if (OutFile == -1) {
OutFile = open(OutputFilename, O_CREAT | O_WRONLY | O_APPEND, 0666);
if (OutFile == -1) {
fprintf(stderr, "LLVM profiling runtime: while opening '%s': ",
OutputFilename);
perror("");
return;
}
{
int PTy = ArgumentInfo;
int Zeros = 0;
write(OutFile, &PTy, sizeof(int));
write(OutFile, &SavedArgsLength, sizeof(unsigned));
write(OutFile, SavedArgs, SavedArgsLength);
if (SavedArgsLength & 3)
write(OutFile, &Zeros, 4-(SavedArgsLength&3));
}
}
PTy = PT;
write(OutFile, &PTy, sizeof(int));
write(OutFile, &NumElements, sizeof(unsigned));
write(OutFile, Start, NumElements*sizeof(unsigned));
}