xref: /llvm-project/compiler-rt/test/profile/Linux/corrupted-profile.c (revision c579c658cd42034449d4fa19f28b43f2082c0991)
1 // RUN: rm -f %t.profraw
2 // RUN: touch %t.profraw
3 // RUN: %clang_profgen -o %t %s
4 // RUN: %t %t.profraw
5 // RUN: %t %t.profraw modifyfile
6 // RUN: cp %t.profraw %t.profraw.old
7 // RUN: %t %t.profraw 2>&1 | FileCheck %s
8 // RUN: diff %t.profraw %t.profraw.old
9 // CHECK: Invalid profile data to merge
10 
11 #include <errno.h>
12 #include <stdio.h>
13 #include <stdint.h>
14 #include <stdlib.h>
15 #include <string.h>
16 #include <sys/mman.h>
17 #include <sys/stat.h>
18 #include <sys/stat.h>
19 #include <fcntl.h>
20 #include <unistd.h>
21 
22 enum ValueKind {
23 #define VALUE_PROF_KIND(Enumerator, Value, Descr) Enumerator = Value,
24 #include "profile/InstrProfData.inc"
25 };
26 
27 typedef struct __llvm_profile_header {
28 #define INSTR_PROF_RAW_HEADER(Type, Name, Initializer) Type Name;
29 #include "profile/InstrProfData.inc"
30 } __llvm_profile_header;
31 
32 typedef void *IntPtrT;
33 typedef struct __llvm_profile_data {
34 #define INSTR_PROF_DATA(Type, LLVMType, Name, Initializer) Type Name;
35 #include "profile/InstrProfData.inc"
36 } __llvm_profile_data;
37 
38 void __llvm_profile_set_file_object(FILE* File, int EnableMerge);
39 
bail(const char * str)40 void bail(const char* str) {
41   fprintf(stderr, "%s %s\n", str, strerror(errno));
42   exit(1);
43 }
44 
main(int argc,char ** argv)45 int main(int argc, char** argv) {
46   if (argc == 3) {
47     int fd = open(argv[1], O_RDWR);
48     if (fd == -1)
49       bail("open");
50 
51     struct stat st;
52     if (stat(argv[1], &st))
53       bail("stat");
54     uint64_t FileSize = st.st_size;
55 
56     char* Buf = (char *) mmap(NULL, FileSize, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
57     if (Buf == MAP_FAILED)
58       bail("mmap");
59 
60     __llvm_profile_header *Header = (__llvm_profile_header *)Buf;
61     __llvm_profile_data *SrcDataStart =
62         (__llvm_profile_data *)(Buf + sizeof(__llvm_profile_header) +
63                                 Header->BinaryIdsSize);
64     memset(&SrcDataStart->CounterPtr, 0xAB, sizeof(SrcDataStart->CounterPtr));
65 
66     if (munmap(Buf, FileSize))
67       bail("munmap");
68 
69     if (close(fd))
70       bail("close");
71   } else {
72     FILE* f = fopen(argv[1], "r+b");
73     if (!f)
74       bail("fopen");
75     __llvm_profile_set_file_object(f, 1);
76   }
77 }
78