1 /*===- InstrProfilingBuffer.c - Write instrumentation to a memory buffer --===*\
2 |*
3 |*                     The LLVM Compiler Infrastructure
4 |*
5 |* This file is distributed under the University of Illinois Open Source
6 |* License. See LICENSE.TXT for details.
7 |*
8 \*===----------------------------------------------------------------------===*/
9 
10 #include "InstrProfiling.h"
11 #include <string.h>
12 
13 uint64_t __llvm_profile_get_size_for_buffer(void) {
14   /* Match logic in __llvm_profile_write_buffer(). */
15   return sizeof(uint64_t) * PROFILE_HEADER_SIZE +
16      PROFILE_RANGE_SIZE(data) * sizeof(__llvm_profile_data) +
17      PROFILE_RANGE_SIZE(counters) * sizeof(uint64_t) +
18      PROFILE_RANGE_SIZE(names) * sizeof(char);
19 }
20 
21 int __llvm_profile_write_buffer(char *Buffer) {
22   /* Match logic in __llvm_profile_get_size_for_buffer().
23    * Match logic in __llvm_profile_write_file().
24    */
25   const __llvm_profile_data *DataBegin = __llvm_profile_data_begin();
26   const __llvm_profile_data *DataEnd = __llvm_profile_data_end();
27   const uint64_t *CountersBegin = __llvm_profile_counters_begin();
28   const uint64_t *CountersEnd   = __llvm_profile_counters_end();
29   const char *NamesBegin = __llvm_profile_names_begin();
30   const char *NamesEnd   = __llvm_profile_names_end();
31 
32   /* Calculate size of sections. */
33   const uint64_t DataSize = DataEnd - DataBegin;
34   const uint64_t CountersSize = CountersEnd - CountersBegin;
35   const uint64_t NamesSize = NamesEnd - NamesBegin;
36 
37   /* Create the header. */
38   uint64_t Header[PROFILE_HEADER_SIZE] = {
39     __llvm_profile_get_magic(),
40     __llvm_profile_get_version(),
41     DataSize,
42     CountersSize,
43     NamesSize,
44     (uintptr_t)CountersBegin,
45     (uintptr_t)NamesBegin
46   };
47 
48   /* Write the data. */
49 #define UPDATE_memcpy(Data, Size) \
50   do {                            \
51     memcpy(Buffer, Data, Size);   \
52     Buffer += Size;               \
53   } while (0)
54   UPDATE_memcpy(Header,  PROFILE_HEADER_SIZE * sizeof(uint64_t));
55   UPDATE_memcpy(DataBegin,     DataSize      * sizeof(__llvm_profile_data));
56   UPDATE_memcpy(CountersBegin, CountersSize  * sizeof(uint64_t));
57   UPDATE_memcpy(NamesBegin,    NamesSize     * sizeof(char));
58 #undef UPDATE_memcpy
59 
60   return 0;
61 }
62