blob: f79b364dc1f7be59cbcc27cec8f1243e5900ef93 [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"
Rui Ueyama3e649032017-01-09 01:47:15 +000029#include "llvm/Support/Path.h"
Rui Ueyama4bb7883f2017-01-06 02:29:48 +000030
31using namespace llvm;
32
33// Each file in an archive must be aligned to this block size.
34static const int BlockSize = 512;
35
36struct UstarHeader {
37 char Name[100];
38 char Mode[8];
39 char Uid[8];
40 char Gid[8];
41 char Size[12];
42 char Mtime[12];
43 char Checksum[8];
44 char TypeFlag;
45 char Linkname[100];
46 char Magic[6];
47 char Version[2];
48 char Uname[32];
49 char Gname[32];
50 char DevMajor[8];
51 char DevMinor[8];
52 char Prefix[155];
53 char Pad[12];
54};
55static_assert(sizeof(UstarHeader) == BlockSize, "invalid Ustar header");
56
57// A PAX attribute is in the form of "<length> <key>=<value>\n"
58// where <length> is the length of the entire string including
59// the length field itself. An example string is this.
60//
61// 25 ctime=1084839148.1212\n
62//
63// This function create such string.
Rui Ueyamaf2a62752017-01-06 05:33:45 +000064static std::string formatPax(StringRef Key, StringRef Val) {
65 int Len = Key.size() + Val.size() + 3; // +3 for " ", "=" and "\n"
Rui Ueyama4bb7883f2017-01-06 02:29:48 +000066
67 // We need to compute total size twice because appending
68 // a length field could change total size by one.
69 int Total = Len + Twine(Len).str().size();
70 Total = Len + Twine(Total).str().size();
71 return (Twine(Total) + " " + Key + "=" + Val + "\n").str();
72}
73
74// Headers in tar files must be aligned to 512 byte boundaries.
Rui Ueyamaf2a62752017-01-06 05:33:45 +000075// This function forwards the current file position to the next boundary.
Rui Ueyama4bb7883f2017-01-06 02:29:48 +000076static void pad(raw_fd_ostream &OS) {
77 uint64_t Pos = OS.tell();
78 OS.seek(alignTo(Pos, BlockSize));
79}
80
81// Computes a checksum for a tar header.
82static void computeChecksum(UstarHeader &Hdr) {
83 // Before computing a checksum, checksum field must be
84 // filled with space characters.
85 memset(Hdr.Checksum, ' ', sizeof(Hdr.Checksum));
86
87 // Compute a checksum and set it to the checksum field.
88 unsigned Chksum = 0;
89 for (size_t I = 0; I < sizeof(Hdr); ++I)
90 Chksum += reinterpret_cast<uint8_t *>(&Hdr)[I];
Reid Kleckner5984d012017-01-06 18:22:18 +000091 snprintf(Hdr.Checksum, sizeof(Hdr.Checksum), "%06o", Chksum);
Rui Ueyama4bb7883f2017-01-06 02:29:48 +000092}
93
94// Create a tar header and write it to a given output stream.
Rui Ueyamaf2a62752017-01-06 05:33:45 +000095static void writePaxHeader(raw_fd_ostream &OS, StringRef Path) {
Rui Ueyama4bb7883f2017-01-06 02:29:48 +000096 // A PAX header consists of a 512-byte header followed
97 // by key-value strings. First, create key-value strings.
98 std::string PaxAttr = formatPax("path", Path);
99
100 // Create a 512-byte header.
101 UstarHeader Hdr = {};
Reid Kleckner5984d012017-01-06 18:22:18 +0000102 snprintf(Hdr.Size, sizeof(Hdr.Size), "%011zo", PaxAttr.size());
Rui Ueyama4bb7883f2017-01-06 02:29:48 +0000103 Hdr.TypeFlag = 'x'; // PAX magic
104 memcpy(Hdr.Magic, "ustar", 6); // Ustar magic
105 computeChecksum(Hdr);
106
107 // Write them down.
108 OS << StringRef(reinterpret_cast<char *>(&Hdr), sizeof(Hdr));
109 OS << PaxAttr;
110 pad(OS);
111}
112
Rui Ueyama999f0942017-01-07 08:28:56 +0000113// In the Ustar header, a path can be split at any '/' to store
114// a path into UstarHeader::Name and UstarHeader::Prefix. This
115// function splits a given path for that purpose.
116static std::pair<StringRef, StringRef> splitPath(StringRef Path) {
117 if (Path.size() <= sizeof(UstarHeader::Name))
118 return {"", Path};
119 size_t Sep = Path.rfind('/', sizeof(UstarHeader::Name) + 1);
120 if (Sep == StringRef::npos)
121 return {"", Path};
122 return {Path.substr(0, Sep), Path.substr(Sep + 1)};
123}
124
125// Returns true if a given path can be stored to a Ustar header
126// without the PAX extension.
Rui Ueyamad52f4b82017-01-07 08:32:07 +0000127static bool fitsInUstar(StringRef Path) {
Rui Ueyama999f0942017-01-07 08:28:56 +0000128 StringRef Prefix;
129 StringRef Name;
130 std::tie(Prefix, Name) = splitPath(Path);
131 return Name.size() <= sizeof(UstarHeader::Name);
132}
133
Rui Ueyama4bb7883f2017-01-06 02:29:48 +0000134// The PAX header is an extended format, so a PAX header needs
135// to be followed by a "real" header.
Rui Ueyamaf2a62752017-01-06 05:33:45 +0000136static void writeUstarHeader(raw_fd_ostream &OS, StringRef Path, size_t Size) {
Rui Ueyama999f0942017-01-07 08:28:56 +0000137 StringRef Prefix;
138 StringRef Name;
139 std::tie(Prefix, Name) = splitPath(Path);
140
Rui Ueyama4bb7883f2017-01-06 02:29:48 +0000141 UstarHeader Hdr = {};
Rui Ueyama999f0942017-01-07 08:28:56 +0000142 memcpy(Hdr.Name, Name.data(), Name.size());
Reid Kleckner5984d012017-01-06 18:22:18 +0000143 memcpy(Hdr.Mode, "0000664", 8);
144 snprintf(Hdr.Size, sizeof(Hdr.Size), "%011zo", Size);
Rui Ueyama4bb7883f2017-01-06 02:29:48 +0000145 memcpy(Hdr.Magic, "ustar", 6);
Rui Ueyama999f0942017-01-07 08:28:56 +0000146 memcpy(Hdr.Prefix, Prefix.data(), Prefix.size());
Rui Ueyama4bb7883f2017-01-06 02:29:48 +0000147 computeChecksum(Hdr);
148 OS << StringRef(reinterpret_cast<char *>(&Hdr), sizeof(Hdr));
149}
150
Rui Ueyama4bb7883f2017-01-06 02:29:48 +0000151// Creates a TarWriter instance and returns it.
152Expected<std::unique_ptr<TarWriter>> TarWriter::create(StringRef OutputPath,
153 StringRef BaseDir) {
154 int FD;
155 if (std::error_code EC = openFileForWrite(OutputPath, FD, sys::fs::F_None))
156 return make_error<StringError>("cannot open " + OutputPath, EC);
157 return std::unique_ptr<TarWriter>(new TarWriter(FD, BaseDir));
158}
159
160TarWriter::TarWriter(int FD, StringRef BaseDir)
161 : OS(FD, /*shouldClose=*/true, /*unbuffered=*/false), BaseDir(BaseDir) {}
162
163// Append a given file to an archive.
164void TarWriter::append(StringRef Path, StringRef Data) {
165 // Write Path and Data.
Rui Ueyama3e649032017-01-09 01:47:15 +0000166 std::string S = BaseDir + "/" + sys::path::convert_to_slash(Path) + "\0";
Rui Ueyamad52f4b82017-01-07 08:32:07 +0000167 if (fitsInUstar(S)) {
Rui Ueyamaf2a62752017-01-06 05:33:45 +0000168 writeUstarHeader(OS, S, Data.size());
169 } else {
170 writePaxHeader(OS, S);
171 writeUstarHeader(OS, "", Data.size());
172 }
173
Rui Ueyama4bb7883f2017-01-06 02:29:48 +0000174 OS << Data;
175 pad(OS);
176
177 // POSIX requires tar archives end with two null blocks.
178 // Here, we write the terminator and then seek back, so that
179 // the file being output is terminated correctly at any moment.
180 uint64_t Pos = OS.tell();
181 OS << std::string(BlockSize * 2, '\0');
182 OS.seek(Pos);
183 OS.flush();
184}