1 //===-- TarWriter.cpp - Tar archive file creator --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // TarWriter class provides a feature to create a tar archive file.
12 // I put emphasis on simplicity over comprehensiveness when implementing this
13 // class because we don't need a full-fledged archive file generator in LLVM
16 // The filename field in the Unix V7 tar header is 100 bytes. Longer filenames
17 // are stored using the PAX extension. The PAX header is standardized in
20 // The struct definition of UstarHeader is copied from
21 // https://www.freebsd.org/cgi/man.cgi?query=tar&sektion=5
23 //===----------------------------------------------------------------------===//
25 #include "llvm/Support/TarWriter.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/Support/FileSystem.h"
28 #include "llvm/Support/MathExtras.h"
32 // Each file in an archive must be aligned to this block size.
33 static const int BlockSize = 512;
54 static_assert(sizeof(UstarHeader) == BlockSize, "invalid Ustar header");
56 // A PAX attribute is in the form of "<length> <key>=<value>\n"
57 // where <length> is the length of the entire string including
58 // the length field itself. An example string is this.
60 // 25 ctime=1084839148.1212\n
62 // This function create such string.
63 static std::string formatPax(StringRef Key, StringRef Val) {
64 int Len = Key.size() + Val.size() + 3; // +3 for " ", "=" and "\n"
66 // We need to compute total size twice because appending
67 // a length field could change total size by one.
68 int Total = Len + Twine(Len).str().size();
69 Total = Len + Twine(Total).str().size();
70 return (Twine(Total) + " " + Key + "=" + Val + "\n").str();
73 // Headers in tar files must be aligned to 512 byte boundaries.
74 // This function forwards the current file position to the next boundary.
75 static void pad(raw_fd_ostream &OS) {
76 uint64_t Pos = OS.tell();
77 OS.seek(alignTo(Pos, BlockSize));
80 // Computes a checksum for a tar header.
81 static void computeChecksum(UstarHeader &Hdr) {
82 // Before computing a checksum, checksum field must be
83 // filled with space characters.
84 memset(Hdr.Checksum, ' ', sizeof(Hdr.Checksum));
86 // Compute a checksum and set it to the checksum field.
88 for (size_t I = 0; I < sizeof(Hdr); ++I)
89 Chksum += reinterpret_cast<uint8_t *>(&Hdr)[I];
90 snprintf(Hdr.Checksum, sizeof(Hdr.Checksum), "%06o", Chksum);
93 // Create a tar header and write it to a given output stream.
94 static void writePaxHeader(raw_fd_ostream &OS, StringRef Path) {
95 // A PAX header consists of a 512-byte header followed
96 // by key-value strings. First, create key-value strings.
97 std::string PaxAttr = formatPax("path", Path);
99 // Create a 512-byte header.
100 UstarHeader Hdr = {};
101 snprintf(Hdr.Size, sizeof(Hdr.Size), "%011zo", PaxAttr.size());
102 Hdr.TypeFlag = 'x'; // PAX magic
103 memcpy(Hdr.Magic, "ustar", 6); // Ustar magic
104 computeChecksum(Hdr);
107 OS << StringRef(reinterpret_cast<char *>(&Hdr), sizeof(Hdr));
112 // The PAX header is an extended format, so a PAX header needs
113 // to be followed by a "real" header.
114 static void writeUstarHeader(raw_fd_ostream &OS, StringRef Path, size_t Size) {
115 UstarHeader Hdr = {};
116 memcpy(Hdr.Name, Path.data(), Path.size());
117 memcpy(Hdr.Mode, "0000664", 8);
118 snprintf(Hdr.Size, sizeof(Hdr.Size), "%011zo", Size);
119 memcpy(Hdr.Magic, "ustar", 6);
120 computeChecksum(Hdr);
121 OS << StringRef(reinterpret_cast<char *>(&Hdr), sizeof(Hdr));
124 // We want to use '/' as a path separator even on Windows.
125 // This function canonicalizes a given path.
126 static std::string canonicalize(std::string S) {
128 std::replace(S.begin(), S.end(), '\\', '/');
133 // Creates a TarWriter instance and returns it.
134 Expected<std::unique_ptr<TarWriter>> TarWriter::create(StringRef OutputPath,
137 if (std::error_code EC = openFileForWrite(OutputPath, FD, sys::fs::F_None))
138 return make_error<StringError>("cannot open " + OutputPath, EC);
139 return std::unique_ptr<TarWriter>(new TarWriter(FD, BaseDir));
142 TarWriter::TarWriter(int FD, StringRef BaseDir)
143 : OS(FD, /*shouldClose=*/true, /*unbuffered=*/false), BaseDir(BaseDir) {}
145 // Append a given file to an archive.
146 void TarWriter::append(StringRef Path, StringRef Data) {
147 // Write Path and Data.
148 std::string S = BaseDir + "/" + canonicalize(Path) + "\0";
149 if (S.size() <= sizeof(UstarHeader::Name)) {
150 writeUstarHeader(OS, S, Data.size());
152 writePaxHeader(OS, S);
153 writeUstarHeader(OS, "", Data.size());
159 // POSIX requires tar archives end with two null blocks.
160 // Here, we write the terminator and then seek back, so that
161 // the file being output is terminated correctly at any moment.
162 uint64_t Pos = OS.tell();
163 OS << std::string(BlockSize * 2, '\0');