blob: 57a4c8f4fc0a678d1f94ece277ef04285ddb2d14 [file] [log] [blame]
Rui Ueyama4bb7883f2017-01-06 02:29:48 +00001//===-- TarWriter.cpp - Tar archive file creator --------------------------===//
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// TarWriter class provides a feature to create a tar archive file.
11//
Rui Ueyamaf2a62752017-01-06 05:33:45 +000012// 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
14// at the moment.
Rui Ueyama4bb7883f2017-01-06 02:29:48 +000015//
Rui Ueyamaf2a62752017-01-06 05:33:45 +000016// 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
18// POSIX.1-2001.
Rui Ueyama4bb7883f2017-01-06 02:29:48 +000019//
20// The struct definition of UstarHeader is copied from
21// https://www.freebsd.org/cgi/man.cgi?query=tar&sektion=5
22//
23//===----------------------------------------------------------------------===//
24
25#include "llvm/Support/TarWriter.h"
26#include "llvm/ADT/StringRef.h"
27#include "llvm/Support/FileSystem.h"
28#include "llvm/Support/MathExtras.h"
29
30using namespace llvm;
31
32// Each file in an archive must be aligned to this block size.
33static const int BlockSize = 512;
34
35struct UstarHeader {
36 char Name[100];
37 char Mode[8];
38 char Uid[8];
39 char Gid[8];
40 char Size[12];
41 char Mtime[12];
42 char Checksum[8];
43 char TypeFlag;
44 char Linkname[100];
45 char Magic[6];
46 char Version[2];
47 char Uname[32];
48 char Gname[32];
49 char DevMajor[8];
50 char DevMinor[8];
51 char Prefix[155];
52 char Pad[12];
53};
54static_assert(sizeof(UstarHeader) == BlockSize, "invalid Ustar header");
55
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.
59//
60// 25 ctime=1084839148.1212\n
61//
62// This function create such string.
Rui Ueyamaf2a62752017-01-06 05:33:45 +000063static std::string formatPax(StringRef Key, StringRef Val) {
64 int Len = Key.size() + Val.size() + 3; // +3 for " ", "=" and "\n"
Rui Ueyama4bb7883f2017-01-06 02:29:48 +000065
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();
71}
72
73// Headers in tar files must be aligned to 512 byte boundaries.
Rui Ueyamaf2a62752017-01-06 05:33:45 +000074// This function forwards the current file position to the next boundary.
Rui Ueyama4bb7883f2017-01-06 02:29:48 +000075static void pad(raw_fd_ostream &OS) {
76 uint64_t Pos = OS.tell();
77 OS.seek(alignTo(Pos, BlockSize));
78}
79
80// Computes a checksum for a tar header.
81static 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));
85
86 // Compute a checksum and set it to the checksum field.
87 unsigned Chksum = 0;
88 for (size_t I = 0; I < sizeof(Hdr); ++I)
89 Chksum += reinterpret_cast<uint8_t *>(&Hdr)[I];
Reid Kleckner5984d012017-01-06 18:22:18 +000090 snprintf(Hdr.Checksum, sizeof(Hdr.Checksum), "%06o", Chksum);
Rui Ueyama4bb7883f2017-01-06 02:29:48 +000091}
92
93// Create a tar header and write it to a given output stream.
Rui Ueyamaf2a62752017-01-06 05:33:45 +000094static void writePaxHeader(raw_fd_ostream &OS, StringRef Path) {
Rui Ueyama4bb7883f2017-01-06 02:29:48 +000095 // 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);
98
99 // Create a 512-byte header.
100 UstarHeader Hdr = {};
Reid Kleckner5984d012017-01-06 18:22:18 +0000101 snprintf(Hdr.Size, sizeof(Hdr.Size), "%011zo", PaxAttr.size());
Rui Ueyama4bb7883f2017-01-06 02:29:48 +0000102 Hdr.TypeFlag = 'x'; // PAX magic
103 memcpy(Hdr.Magic, "ustar", 6); // Ustar magic
104 computeChecksum(Hdr);
105
106 // Write them down.
107 OS << StringRef(reinterpret_cast<char *>(&Hdr), sizeof(Hdr));
108 OS << PaxAttr;
109 pad(OS);
110}
111
Rui Ueyama999f0942017-01-07 08:28:56 +0000112// In the Ustar header, a path can be split at any '/' to store
113// a path into UstarHeader::Name and UstarHeader::Prefix. This
114// function splits a given path for that purpose.
115static std::pair<StringRef, StringRef> splitPath(StringRef Path) {
116 if (Path.size() <= sizeof(UstarHeader::Name))
117 return {"", Path};
118 size_t Sep = Path.rfind('/', sizeof(UstarHeader::Name) + 1);
119 if (Sep == StringRef::npos)
120 return {"", Path};
121 return {Path.substr(0, Sep), Path.substr(Sep + 1)};
122}
123
124// Returns true if a given path can be stored to a Ustar header
125// without the PAX extension.
Rui Ueyamad52f4b82017-01-07 08:32:07 +0000126static bool fitsInUstar(StringRef Path) {
Rui Ueyama999f0942017-01-07 08:28:56 +0000127 StringRef Prefix;
128 StringRef Name;
129 std::tie(Prefix, Name) = splitPath(Path);
130 return Name.size() <= sizeof(UstarHeader::Name);
131}
132
Rui Ueyama4bb7883f2017-01-06 02:29:48 +0000133// The PAX header is an extended format, so a PAX header needs
134// to be followed by a "real" header.
Rui Ueyamaf2a62752017-01-06 05:33:45 +0000135static void writeUstarHeader(raw_fd_ostream &OS, StringRef Path, size_t Size) {
Rui Ueyama999f0942017-01-07 08:28:56 +0000136 StringRef Prefix;
137 StringRef Name;
138 std::tie(Prefix, Name) = splitPath(Path);
139
Rui Ueyama4bb7883f2017-01-06 02:29:48 +0000140 UstarHeader Hdr = {};
Rui Ueyama999f0942017-01-07 08:28:56 +0000141 memcpy(Hdr.Name, Name.data(), Name.size());
Reid Kleckner5984d012017-01-06 18:22:18 +0000142 memcpy(Hdr.Mode, "0000664", 8);
143 snprintf(Hdr.Size, sizeof(Hdr.Size), "%011zo", Size);
Rui Ueyama4bb7883f2017-01-06 02:29:48 +0000144 memcpy(Hdr.Magic, "ustar", 6);
Rui Ueyama999f0942017-01-07 08:28:56 +0000145 memcpy(Hdr.Prefix, Prefix.data(), Prefix.size());
Rui Ueyama4bb7883f2017-01-06 02:29:48 +0000146 computeChecksum(Hdr);
147 OS << StringRef(reinterpret_cast<char *>(&Hdr), sizeof(Hdr));
148}
149
150// We want to use '/' as a path separator even on Windows.
151// This function canonicalizes a given path.
152static std::string canonicalize(std::string S) {
153#ifdef LLVM_ON_WIN32
154 std::replace(S.begin(), S.end(), '\\', '/');
155#endif
156 return S;
157}
158
159// Creates a TarWriter instance and returns it.
160Expected<std::unique_ptr<TarWriter>> TarWriter::create(StringRef OutputPath,
161 StringRef BaseDir) {
162 int FD;
163 if (std::error_code EC = openFileForWrite(OutputPath, FD, sys::fs::F_None))
164 return make_error<StringError>("cannot open " + OutputPath, EC);
165 return std::unique_ptr<TarWriter>(new TarWriter(FD, BaseDir));
166}
167
168TarWriter::TarWriter(int FD, StringRef BaseDir)
169 : OS(FD, /*shouldClose=*/true, /*unbuffered=*/false), BaseDir(BaseDir) {}
170
171// Append a given file to an archive.
172void TarWriter::append(StringRef Path, StringRef Data) {
173 // Write Path and Data.
Rui Ueyamaf2a62752017-01-06 05:33:45 +0000174 std::string S = BaseDir + "/" + canonicalize(Path) + "\0";
Rui Ueyamad52f4b82017-01-07 08:32:07 +0000175 if (fitsInUstar(S)) {
Rui Ueyamaf2a62752017-01-06 05:33:45 +0000176 writeUstarHeader(OS, S, Data.size());
177 } else {
178 writePaxHeader(OS, S);
179 writeUstarHeader(OS, "", Data.size());
180 }
181
Rui Ueyama4bb7883f2017-01-06 02:29:48 +0000182 OS << Data;
183 pad(OS);
184
185 // POSIX requires tar archives end with two null blocks.
186 // Here, we write the terminator and then seek back, so that
187 // the file being output is terminated correctly at any moment.
188 uint64_t Pos = OS.tell();
189 OS << std::string(BlockSize * 2, '\0');
190 OS.seek(Pos);
191 OS.flush();
192}