1 //===- GsymCreator.h --------------------------------------------*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #ifndef LLVM_DEBUGINFO_GSYM_GSYMCREATOR_H 10 #define LLVM_DEBUGINFO_GSYM_GSYMCREATOR_H 11 12 #include "llvm/Support/Compiler.h" 13 #include <functional> 14 #include <memory> 15 #include <mutex> 16 #include <thread> 17 18 #include "llvm/ADT/AddressRanges.h" 19 #include "llvm/ADT/ArrayRef.h" 20 #include "llvm/ADT/StringSet.h" 21 #include "llvm/DebugInfo/GSYM/FileEntry.h" 22 #include "llvm/DebugInfo/GSYM/FunctionInfo.h" 23 #include "llvm/MC/StringTableBuilder.h" 24 #include "llvm/Support/Endian.h" 25 #include "llvm/Support/Error.h" 26 #include "llvm/Support/Path.h" 27 28 namespace llvm { 29 30 namespace gsym { 31 class FileWriter; 32 class OutputAggregator; 33 34 /// GsymCreator is used to emit GSYM data to a stand alone file or section 35 /// within a file. 36 /// 37 /// The GsymCreator is designed to be used in 3 stages: 38 /// - Create FunctionInfo objects and add them 39 /// - Finalize the GsymCreator object 40 /// - Save to file or section 41 /// 42 /// The first stage involves creating FunctionInfo objects from another source 43 /// of information like compiler debug info metadata, DWARF or Breakpad files. 44 /// Any strings in the FunctionInfo or contained information, like InlineInfo 45 /// or LineTable objects, should get the string table offsets by calling 46 /// GsymCreator::insertString(...). Any file indexes that are needed should be 47 /// obtained by calling GsymCreator::insertFile(...). All of the function calls 48 /// in GsymCreator are thread safe. This allows multiple threads to create and 49 /// add FunctionInfo objects while parsing debug information. 50 /// 51 /// Once all of the FunctionInfo objects have been added, the 52 /// GsymCreator::finalize(...) must be called prior to saving. This function 53 /// will sort the FunctionInfo objects, finalize the string table, and do any 54 /// other passes on the information needed to prepare the information to be 55 /// saved. 56 /// 57 /// Once the object has been finalized, it can be saved to a file or section. 58 /// 59 /// ENCODING 60 /// 61 /// GSYM files are designed to be memory mapped into a process as shared, read 62 /// only data, and used as is. 63 /// 64 /// The GSYM file format when in a stand alone file consists of: 65 /// - Header 66 /// - Address Table 67 /// - Function Info Offsets 68 /// - File Table 69 /// - String Table 70 /// - Function Info Data 71 /// 72 /// HEADER 73 /// 74 /// The header is fully described in "llvm/DebugInfo/GSYM/Header.h". 75 /// 76 /// ADDRESS TABLE 77 /// 78 /// The address table immediately follows the header in the file and consists 79 /// of Header.NumAddresses address offsets. These offsets are sorted and can be 80 /// binary searched for efficient lookups. Addresses in the address table are 81 /// stored as offsets from a 64 bit base address found in Header.BaseAddress. 82 /// This allows the address table to contain 8, 16, or 32 offsets. This allows 83 /// the address table to not require full 64 bit addresses for each address. 84 /// The resulting GSYM size is smaller and causes fewer pages to be touched 85 /// during address lookups when the address table is smaller. The size of the 86 /// address offsets in the address table is specified in the header in 87 /// Header.AddrOffSize. The first offset in the address table is aligned to 88 /// Header.AddrOffSize alignment to ensure efficient access when loaded into 89 /// memory. 90 /// 91 /// FUNCTION INFO OFFSETS TABLE 92 /// 93 /// The function info offsets table immediately follows the address table and 94 /// consists of Header.NumAddresses 32 bit file offsets: one for each address 95 /// in the address table. This data is aligned to a 4 byte boundary. The 96 /// offsets in this table are the relative offsets from the start offset of the 97 /// GSYM header and point to the function info data for each address in the 98 /// address table. Keeping this data separate from the address table helps to 99 /// reduce the number of pages that are touched when address lookups occur on a 100 /// GSYM file. 101 /// 102 /// FILE TABLE 103 /// 104 /// The file table immediately follows the function info offsets table. The 105 /// encoding of the FileTable is: 106 /// 107 /// struct FileTable { 108 /// uint32_t Count; 109 /// FileEntry Files[]; 110 /// }; 111 /// 112 /// The file table starts with a 32 bit count of the number of files that are 113 /// used in all of the function info, followed by that number of FileEntry 114 /// structures. The file table is aligned to a 4 byte boundary, Each file in 115 /// the file table is represented with a FileEntry structure. 116 /// See "llvm/DebugInfo/GSYM/FileEntry.h" for details. 117 /// 118 /// STRING TABLE 119 /// 120 /// The string table follows the file table in stand alone GSYM files and 121 /// contains all strings for everything contained in the GSYM file. Any string 122 /// data should be added to the string table and any references to strings 123 /// inside GSYM information must be stored as 32 bit string table offsets into 124 /// this string table. The string table always starts with an empty string at 125 /// offset zero and is followed by any strings needed by the GSYM information. 126 /// The start of the string table is not aligned to any boundary. 127 /// 128 /// FUNCTION INFO DATA 129 /// 130 /// The function info data is the payload that contains information about the 131 /// address that is being looked up. It contains all of the encoded 132 /// FunctionInfo objects. Each encoded FunctionInfo's data is pointed to by an 133 /// entry in the Function Info Offsets Table. For details on the exact encoding 134 /// of FunctionInfo objects, see "llvm/DebugInfo/GSYM/FunctionInfo.h". 135 class GsymCreator { 136 // Private member variables require Mutex protections 137 mutable std::mutex Mutex; 138 std::vector<FunctionInfo> Funcs; 139 StringTableBuilder StrTab; 140 StringSet<> StringStorage; 141 DenseMap<llvm::gsym::FileEntry, uint32_t> FileEntryToIndex; 142 // Needed for mapping string offsets back to the string stored in \a StrTab. 143 DenseMap<uint64_t, CachedHashStringRef> StringOffsetMap; 144 std::vector<llvm::gsym::FileEntry> Files; 145 std::vector<uint8_t> UUID; 146 std::optional<AddressRanges> ValidTextRanges; 147 std::optional<uint64_t> BaseAddress; 148 bool IsSegment = false; 149 bool Finalized = false; 150 bool Quiet; 151 152 153 /// Get the first function start address. 154 /// 155 /// \returns The start address of the first FunctionInfo or std::nullopt if 156 /// there are no function infos. 157 std::optional<uint64_t> getFirstFunctionAddress() const; 158 159 /// Get the last function address. 160 /// 161 /// \returns The start address of the last FunctionInfo or std::nullopt if 162 /// there are no function infos. 163 std::optional<uint64_t> getLastFunctionAddress() const; 164 165 /// Get the base address to use for this GSYM file. 166 /// 167 /// \returns The base address to put into the header and to use when creating 168 /// the address offset table or std::nullpt if there are no valid 169 /// function infos or if the base address wasn't specified. 170 std::optional<uint64_t> getBaseAddress() const; 171 172 /// Get the size of an address offset in the address offset table. 173 /// 174 /// GSYM files store offsets from the base address in the address offset table 175 /// and we store the size of the address offsets in the GSYM header. This 176 /// function will calculate the size in bytes of these address offsets based 177 /// on the current contents of the GSYM file. 178 /// 179 /// \returns The size in byets of the address offsets. 180 uint8_t getAddressOffsetSize() const; 181 182 /// Get the maximum address offset for the current address offset size. 183 /// 184 /// This is used when creating the address offset table to ensure we have 185 /// values that are in range so we don't end up truncating address offsets 186 /// when creating GSYM files as the code evolves. 187 /// 188 /// \returns The maximum address offset value that will be encoded into a GSYM 189 /// file. 190 uint64_t getMaxAddressOffset() const; 191 192 /// Calculate the byte size of the GSYM header and tables sizes. 193 /// 194 /// This function will calculate the exact size in bytes of the encocded GSYM 195 /// for the following items: 196 /// - The GSYM header 197 /// - The Address offset table 198 /// - The Address info offset table 199 /// - The file table 200 /// - The string table 201 /// 202 /// This is used to help split GSYM files into segments. 203 /// 204 /// \returns Size in bytes the GSYM header and tables. 205 uint64_t calculateHeaderAndTableSize() const; 206 207 /// Copy a FunctionInfo from the \a SrcGC GSYM creator into this creator. 208 /// 209 /// Copy the function info and only the needed files and strings and add a 210 /// converted FunctionInfo into this object. This is used to segment GSYM 211 /// files into separate files while only transferring the files and strings 212 /// that are needed from \a SrcGC. 213 /// 214 /// \param SrcGC The source gsym creator to copy from. 215 /// \param FuncInfoIdx The function info index within \a SrcGC to copy. 216 /// \returns The number of bytes it will take to encode the function info in 217 /// this GsymCreator. This helps calculate the size of the current GSYM 218 /// segment file. 219 uint64_t copyFunctionInfo(const GsymCreator &SrcGC, size_t FuncInfoIdx); 220 221 /// Copy a string from \a SrcGC into this object. 222 /// 223 /// Copy a string from \a SrcGC by string table offset into this GSYM creator. 224 /// If a string has already been copied, the uniqued string table offset will 225 /// be returned, otherwise the string will be copied and a unique offset will 226 /// be returned. 227 /// 228 /// \param SrcGC The source gsym creator to copy from. 229 /// \param StrOff The string table offset from \a SrcGC to copy. 230 /// \returns The new string table offset of the string within this object. 231 uint32_t copyString(const GsymCreator &SrcGC, uint32_t StrOff); 232 233 /// Copy a file from \a SrcGC into this object. 234 /// 235 /// Copy a file from \a SrcGC by file index into this GSYM creator. Files 236 /// consist of two string table entries, one for the directory and one for the 237 /// filename, this function will copy any needed strings ensure the file is 238 /// uniqued within this object. If a file already exists in this GSYM creator 239 /// the uniqued index will be returned, else the stirngs will be copied and 240 /// the new file index will be returned. 241 /// 242 /// \param SrcGC The source gsym creator to copy from. 243 /// \param FileIdx The 1 based file table index within \a SrcGC to copy. A 244 /// file index of zero will always return zero as the zero is a reserved file 245 /// index that means no file. 246 /// \returns The new file index of the file within this object. 247 uint32_t copyFile(const GsymCreator &SrcGC, uint32_t FileIdx); 248 249 /// Inserts a FileEntry into the file table. 250 /// 251 /// This is used to insert a file entry in a thread safe way into this object. 252 /// 253 /// \param FE A file entry object that contains valid string table offsets 254 /// from this object already. 255 uint32_t insertFileEntry(FileEntry FE); 256 257 /// Fixup any string and file references by updating any file indexes and 258 /// strings offsets in the InlineInfo parameter. 259 /// 260 /// When copying InlineInfo entries, we can simply make a copy of the object 261 /// and then fixup the files and strings for efficiency. 262 /// 263 /// \param SrcGC The source gsym creator to copy from. 264 /// \param II The inline info that contains file indexes and string offsets 265 /// that come from \a SrcGC. The entries will be updated by coping any files 266 /// and strings over into this object. 267 void fixupInlineInfo(const GsymCreator &SrcGC, InlineInfo &II); 268 269 /// Save this GSYM file into segments that are roughly \a SegmentSize in size. 270 /// 271 /// When segemented GSYM files are saved to disk, they will use \a Path as a 272 /// prefix and then have the first function info address appended to the path 273 /// when each segment is saved. Each segmented GSYM file has a only the 274 /// strings and files that are needed to save the function infos that are in 275 /// each segment. These smaller files are easy to compress and download 276 /// separately and allow for efficient lookups with very large GSYM files and 277 /// segmenting them allows servers to download only the segments that are 278 /// needed. 279 /// 280 /// \param Path The path prefix to use when saving the GSYM files. 281 /// \param ByteOrder The endianness to use when saving the file. 282 /// \param SegmentSize The size in bytes to segment the GSYM file into. 283 llvm::Error saveSegments(StringRef Path, llvm::endianness ByteOrder, 284 uint64_t SegmentSize) const; 285 286 /// Let this creator know that this is a segment of another GsymCreator. 287 /// 288 /// When we have a segment, we know that function infos will be added in 289 /// ascending address range order without having to be finalized. We also 290 /// don't need to sort and unique entries during the finalize function call. setIsSegment()291 void setIsSegment() { 292 IsSegment = true; 293 } 294 295 public: 296 LLVM_ABI GsymCreator(bool Quiet = false); 297 298 /// Save a GSYM file to a stand alone file. 299 /// 300 /// \param Path The file path to save the GSYM file to. 301 /// \param ByteOrder The endianness to use when saving the file. 302 /// \param SegmentSize The size in bytes to segment the GSYM file into. If 303 /// this option is set this function will create N segments 304 /// that are all around \a SegmentSize bytes in size. This 305 /// allows a very large GSYM file to be broken up into 306 /// shards. Each GSYM file will have its own file table, 307 /// and string table that only have the files and strings 308 /// needed for the shared. If this argument has no value, 309 /// a single GSYM file that contains all function 310 /// information will be created. 311 /// \returns An error object that indicates success or failure of the save. 312 LLVM_ABI llvm::Error 313 save(StringRef Path, llvm::endianness ByteOrder, 314 std::optional<uint64_t> SegmentSize = std::nullopt) const; 315 316 /// Encode a GSYM into the file writer stream at the current position. 317 /// 318 /// \param O The stream to save the binary data to 319 /// \returns An error object that indicates success or failure of the save. 320 LLVM_ABI llvm::Error encode(FileWriter &O) const; 321 322 /// Insert a string into the GSYM string table. 323 /// 324 /// All strings used by GSYM files must be uniqued by adding them to this 325 /// string pool and using the returned offset for any string values. 326 /// 327 /// \param S The string to insert into the string table. 328 /// \param Copy If true, then make a backing copy of the string. If false, 329 /// the string is owned by another object that will stay around 330 /// long enough for the GsymCreator to save the GSYM file. 331 /// \returns The unique 32 bit offset into the string table. 332 LLVM_ABI uint32_t insertString(StringRef S, bool Copy = true); 333 334 /// Retrieve a string from the GSYM string table given its offset. 335 /// 336 /// The offset is assumed to be a valid offset into the string table. 337 /// otherwise an assert will be triggered. 338 /// 339 /// \param Offset The offset of the string to retrieve, previously returned by 340 /// insertString. 341 /// \returns The string at the given offset in the string table. 342 LLVM_ABI StringRef getString(uint32_t Offset); 343 344 /// Insert a file into this GSYM creator. 345 /// 346 /// Inserts a file by adding a FileEntry into the "Files" member variable if 347 /// the file has not already been added. The file path is split into 348 /// directory and filename which are both added to the string table. This 349 /// allows paths to be stored efficiently by reusing the directories that are 350 /// common between multiple files. 351 /// 352 /// \param Path The path to the file to insert. 353 /// \param Style The path style for the "Path" parameter. 354 /// \returns The unique file index for the inserted file. 355 LLVM_ABI uint32_t 356 insertFile(StringRef Path, sys::path::Style Style = sys::path::Style::native); 357 358 /// Add a function info to this GSYM creator. 359 /// 360 /// All information in the FunctionInfo object must use the 361 /// GsymCreator::insertString(...) function when creating string table 362 /// offsets for names and other strings. 363 /// 364 /// \param FI The function info object to emplace into our functions list. 365 LLVM_ABI void addFunctionInfo(FunctionInfo &&FI); 366 367 /// Load call site information from a YAML file. 368 /// 369 /// This function reads call site information from a specified YAML file and 370 /// adds it to the GSYM data. 371 /// 372 /// \param YAMLFile The path to the YAML file containing call site 373 /// information. 374 LLVM_ABI llvm::Error loadCallSitesFromYAML(StringRef YAMLFile); 375 376 /// Organize merged FunctionInfo's 377 /// 378 /// This method processes the list of function infos (Funcs) to identify and 379 /// group functions with overlapping address ranges. 380 /// 381 /// \param Out Output stream to report information about how merged 382 /// FunctionInfo's were handled. 383 LLVM_ABI void prepareMergedFunctions(OutputAggregator &Out); 384 385 /// Finalize the data in the GSYM creator prior to saving the data out. 386 /// 387 /// Finalize must be called after all FunctionInfo objects have been added 388 /// and before GsymCreator::save() is called. 389 /// 390 /// \param OS Output stream to report duplicate function infos, overlapping 391 /// function infos, and function infos that were merged or removed. 392 /// \returns An error object that indicates success or failure of the 393 /// finalize. 394 LLVM_ABI llvm::Error finalize(OutputAggregator &OS); 395 396 /// Set the UUID value. 397 /// 398 /// \param UUIDBytes The new UUID bytes. setUUID(llvm::ArrayRef<uint8_t> UUIDBytes)399 void setUUID(llvm::ArrayRef<uint8_t> UUIDBytes) { 400 UUID.assign(UUIDBytes.begin(), UUIDBytes.end()); 401 } 402 403 /// Thread safe iteration over all function infos. 404 /// 405 /// \param Callback A callback function that will get called with each 406 /// FunctionInfo. If the callback returns false, stop iterating. 407 LLVM_ABI void 408 forEachFunctionInfo(std::function<bool(FunctionInfo &)> const &Callback); 409 410 /// Thread safe const iteration over all function infos. 411 /// 412 /// \param Callback A callback function that will get called with each 413 /// FunctionInfo. If the callback returns false, stop iterating. 414 LLVM_ABI void forEachFunctionInfo( 415 std::function<bool(const FunctionInfo &)> const &Callback) const; 416 417 /// Get the current number of FunctionInfo objects contained in this 418 /// object. 419 LLVM_ABI size_t getNumFunctionInfos() const; 420 421 /// Set valid .text address ranges that all functions must be contained in. SetValidTextRanges(AddressRanges & TextRanges)422 void SetValidTextRanges(AddressRanges &TextRanges) { 423 ValidTextRanges = TextRanges; 424 } 425 426 /// Get the valid text ranges. GetValidTextRanges()427 const std::optional<AddressRanges> GetValidTextRanges() const { 428 return ValidTextRanges; 429 } 430 431 /// Check if an address is a valid code address. 432 /// 433 /// Any functions whose addresses do not exist within these function bounds 434 /// will not be converted into the final GSYM. This allows the object file 435 /// to figure out the valid file address ranges of all the code sections 436 /// and ensure we don't add invalid functions to the final output. Many 437 /// linkers have issues when dead stripping functions from DWARF debug info 438 /// where they set the DW_AT_low_pc to zero, but newer DWARF has the 439 /// DW_AT_high_pc as an offset from the DW_AT_low_pc and these size 440 /// attributes have no relocations that can be applied. This results in DWARF 441 /// where many functions have an DW_AT_low_pc of zero and a valid offset size 442 /// for DW_AT_high_pc. If we extract all valid ranges from an object file 443 /// that are marked with executable permissions, we can properly ensure that 444 /// these functions are removed. 445 /// 446 /// \param Addr An address to check. 447 /// 448 /// \returns True if the address is in the valid text ranges or if no valid 449 /// text ranges have been set, false otherwise. 450 LLVM_ABI bool IsValidTextAddress(uint64_t Addr) const; 451 452 /// Set the base address to use for the GSYM file. 453 /// 454 /// Setting the base address to use for the GSYM file. Object files typically 455 /// get loaded from a base address when the OS loads them into memory. Using 456 /// GSYM files for symbolication becomes easier if the base address in the 457 /// GSYM header is the same address as it allows addresses to be easily slid 458 /// and allows symbolication without needing to find the original base 459 /// address in the original object file. 460 /// 461 /// \param Addr The address to use as the base address of the GSYM file 462 /// when it is saved to disk. setBaseAddress(uint64_t Addr)463 void setBaseAddress(uint64_t Addr) { 464 BaseAddress = Addr; 465 } 466 467 /// Whether the transformation should be quiet, i.e. not output warnings. isQuiet()468 bool isQuiet() const { return Quiet; } 469 470 471 /// Create a segmented GSYM creator starting with function info index 472 /// \a FuncIdx. 473 /// 474 /// This function will create a GsymCreator object that will encode into 475 /// roughly \a SegmentSize bytes and return it. It is used by the private 476 /// saveSegments(...) function and also is used by the GSYM unit tests to test 477 /// segmenting of GSYM files. The returned GsymCreator can be finalized and 478 /// encoded. 479 /// 480 /// \param [in] SegmentSize The size in bytes to roughly segment the GSYM file 481 /// into. 482 /// \param [in,out] FuncIdx The index of the first function info to encode 483 /// into the returned GsymCreator. This index will be updated so it can be 484 /// used in subsequent calls to this function to allow more segments to be 485 /// created. 486 /// \returns An expected unique pointer to a GsymCreator or an error. The 487 /// returned unique pointer can be NULL if there are no more functions to 488 /// encode. 489 LLVM_ABI llvm::Expected<std::unique_ptr<GsymCreator>> 490 createSegment(uint64_t SegmentSize, size_t &FuncIdx) const; 491 }; 492 493 } // namespace gsym 494 } // namespace llvm 495 496 #endif // LLVM_DEBUGINFO_GSYM_GSYMCREATOR_H 497