blob: 6c62f8861afd4c036d0d547aa02577b44dfca859 [file] [log] [blame]
Rui Ueyama4bb7883f2017-01-06 02:29:48 +00001//===-- TarWriter.cpp - Tar archive file creator --------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Rui Ueyama4bb7883f2017-01-06 02:29:48 +00006//
7//===----------------------------------------------------------------------===//
8//
9// TarWriter class provides a feature to create a tar archive file.
10//
Rui Ueyamaf2a62752017-01-06 05:33:45 +000011// I put emphasis on simplicity over comprehensiveness when implementing this
12// class because we don't need a full-fledged archive file generator in LLVM
13// at the moment.
Rui Ueyama4bb7883f2017-01-06 02:29:48 +000014//
Rui Ueyamaf2a62752017-01-06 05:33:45 +000015// The filename field in the Unix V7 tar header is 100 bytes. Longer filenames
16// are stored using the PAX extension. The PAX header is standardized in
17// POSIX.1-2001.
Rui Ueyama4bb7883f2017-01-06 02:29:48 +000018//
19// The struct definition of UstarHeader is copied from
20// https://www.freebsd.org/cgi/man.cgi?query=tar&sektion=5
21//
22//===----------------------------------------------------------------------===//
23
24#include "llvm/Support/TarWriter.h"
25#include "llvm/ADT/StringRef.h"
26#include "llvm/Support/FileSystem.h"
27#include "llvm/Support/MathExtras.h"
Rui Ueyama3e649032017-01-09 01:47:15 +000028#include "llvm/Support/Path.h"
Rui Ueyama4bb7883f2017-01-06 02:29:48 +000029
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
Rui Ueyamaa84ab072017-01-09 21:20:42 +000056static UstarHeader makeUstarHeader() {
57 UstarHeader Hdr = {};
58 memcpy(Hdr.Magic, "ustar", 5); // Ustar magic
59 memcpy(Hdr.Version, "00", 2); // Ustar version
60 return Hdr;
61}
62
Rui Ueyama4bb7883f2017-01-06 02:29:48 +000063// A PAX attribute is in the form of "<length> <key>=<value>\n"
64// where <length> is the length of the entire string including
65// the length field itself. An example string is this.
66//
67// 25 ctime=1084839148.1212\n
68//
69// This function create such string.
Rui Ueyamaf2a62752017-01-06 05:33:45 +000070static std::string formatPax(StringRef Key, StringRef Val) {
71 int Len = Key.size() + Val.size() + 3; // +3 for " ", "=" and "\n"
Rui Ueyama4bb7883f2017-01-06 02:29:48 +000072
73 // We need to compute total size twice because appending
74 // a length field could change total size by one.
75 int Total = Len + Twine(Len).str().size();
76 Total = Len + Twine(Total).str().size();
77 return (Twine(Total) + " " + Key + "=" + Val + "\n").str();
78}
79
80// Headers in tar files must be aligned to 512 byte boundaries.
Rui Ueyamaf2a62752017-01-06 05:33:45 +000081// This function forwards the current file position to the next boundary.
Rui Ueyama4bb7883f2017-01-06 02:29:48 +000082static void pad(raw_fd_ostream &OS) {
83 uint64_t Pos = OS.tell();
84 OS.seek(alignTo(Pos, BlockSize));
85}
86
87// Computes a checksum for a tar header.
88static void computeChecksum(UstarHeader &Hdr) {
89 // Before computing a checksum, checksum field must be
90 // filled with space characters.
91 memset(Hdr.Checksum, ' ', sizeof(Hdr.Checksum));
92
93 // Compute a checksum and set it to the checksum field.
94 unsigned Chksum = 0;
95 for (size_t I = 0; I < sizeof(Hdr); ++I)
96 Chksum += reinterpret_cast<uint8_t *>(&Hdr)[I];
Reid Kleckner5984d012017-01-06 18:22:18 +000097 snprintf(Hdr.Checksum, sizeof(Hdr.Checksum), "%06o", Chksum);
Rui Ueyama4bb7883f2017-01-06 02:29:48 +000098}
99
100// Create a tar header and write it to a given output stream.
Rui Ueyamaf2a62752017-01-06 05:33:45 +0000101static void writePaxHeader(raw_fd_ostream &OS, StringRef Path) {
Rui Ueyama4bb7883f2017-01-06 02:29:48 +0000102 // A PAX header consists of a 512-byte header followed
103 // by key-value strings. First, create key-value strings.
104 std::string PaxAttr = formatPax("path", Path);
105
106 // Create a 512-byte header.
Rui Ueyamaa84ab072017-01-09 21:20:42 +0000107 UstarHeader Hdr = makeUstarHeader();
Reid Kleckner5984d012017-01-06 18:22:18 +0000108 snprintf(Hdr.Size, sizeof(Hdr.Size), "%011zo", PaxAttr.size());
Rui Ueyamaa84ab072017-01-09 21:20:42 +0000109 Hdr.TypeFlag = 'x'; // PAX magic
Rui Ueyama4bb7883f2017-01-06 02:29:48 +0000110 computeChecksum(Hdr);
111
112 // Write them down.
113 OS << StringRef(reinterpret_cast<char *>(&Hdr), sizeof(Hdr));
114 OS << PaxAttr;
115 pad(OS);
116}
117
Rui Ueyama283f56a2017-09-27 21:38:02 +0000118// Path fits in a Ustar header if
119//
120// - Path is less than 100 characters long, or
121// - Path is in the form of "<prefix>/<name>" where <prefix> is less
122// than or equal to 155 characters long and <name> is less than 100
123// characters long. Both <prefix> and <name> can contain extra '/'.
124//
125// If Path fits in a Ustar header, updates Prefix and Name and returns true.
126// Otherwise, returns false.
127static bool splitUstar(StringRef Path, StringRef &Prefix, StringRef &Name) {
128 if (Path.size() < sizeof(UstarHeader::Name)) {
Rui Ueyama59088452017-09-28 00:27:39 +0000129 Prefix = "";
Rui Ueyama283f56a2017-09-27 21:38:02 +0000130 Name = Path;
131 return true;
132 }
133
Rui Ueyamae9d17542017-01-09 22:55:00 +0000134 size_t Sep = Path.rfind('/', sizeof(UstarHeader::Prefix) + 1);
Rui Ueyama999f0942017-01-07 08:28:56 +0000135 if (Sep == StringRef::npos)
Rui Ueyama283f56a2017-09-27 21:38:02 +0000136 return false;
137 if (Path.size() - Sep - 1 >= sizeof(UstarHeader::Name))
138 return false;
Rui Ueyama999f0942017-01-07 08:28:56 +0000139
Rui Ueyama283f56a2017-09-27 21:38:02 +0000140 Prefix = Path.substr(0, Sep);
141 Name = Path.substr(Sep + 1);
142 return true;
Rui Ueyama999f0942017-01-07 08:28:56 +0000143}
144
Rui Ueyama4bb7883f2017-01-06 02:29:48 +0000145// The PAX header is an extended format, so a PAX header needs
146// to be followed by a "real" header.
Rui Ueyama283f56a2017-09-27 21:38:02 +0000147static void writeUstarHeader(raw_fd_ostream &OS, StringRef Prefix,
148 StringRef Name, size_t Size) {
Rui Ueyamaa84ab072017-01-09 21:20:42 +0000149 UstarHeader Hdr = makeUstarHeader();
Rui Ueyama999f0942017-01-07 08:28:56 +0000150 memcpy(Hdr.Name, Name.data(), Name.size());
Reid Kleckner5984d012017-01-06 18:22:18 +0000151 memcpy(Hdr.Mode, "0000664", 8);
152 snprintf(Hdr.Size, sizeof(Hdr.Size), "%011zo", Size);
Rui Ueyama999f0942017-01-07 08:28:56 +0000153 memcpy(Hdr.Prefix, Prefix.data(), Prefix.size());
Rui Ueyama4bb7883f2017-01-06 02:29:48 +0000154 computeChecksum(Hdr);
155 OS << StringRef(reinterpret_cast<char *>(&Hdr), sizeof(Hdr));
156}
157
Rui Ueyama4bb7883f2017-01-06 02:29:48 +0000158// Creates a TarWriter instance and returns it.
159Expected<std::unique_ptr<TarWriter>> TarWriter::create(StringRef OutputPath,
160 StringRef BaseDir) {
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000161 using namespace sys::fs;
Rui Ueyama4bb7883f2017-01-06 02:29:48 +0000162 int FD;
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000163 if (std::error_code EC =
164 openFileForWrite(OutputPath, FD, CD_CreateAlways, OF_None))
Rui Ueyama4bb7883f2017-01-06 02:29:48 +0000165 return make_error<StringError>("cannot open " + OutputPath, EC);
166 return std::unique_ptr<TarWriter>(new TarWriter(FD, BaseDir));
167}
168
169TarWriter::TarWriter(int FD, StringRef BaseDir)
Benjamin Krameradcd0262020-01-28 20:23:46 +0100170 : OS(FD, /*shouldClose=*/true, /*unbuffered=*/false),
171 BaseDir(std::string(BaseDir)) {}
Rui Ueyama4bb7883f2017-01-06 02:29:48 +0000172
173// Append a given file to an archive.
174void TarWriter::append(StringRef Path, StringRef Data) {
175 // Write Path and Data.
Rui Ueyama283f56a2017-09-27 21:38:02 +0000176 std::string Fullpath = BaseDir + "/" + sys::path::convert_to_slash(Path);
177
George Rimarf91f0b02017-12-05 10:09:59 +0000178 // We do not want to include the same file more than once.
179 if (!Files.insert(Fullpath).second)
180 return;
181
Rui Ueyama283f56a2017-09-27 21:38:02 +0000182 StringRef Prefix;
183 StringRef Name;
184 if (splitUstar(Fullpath, Prefix, Name)) {
185 writeUstarHeader(OS, Prefix, Name, Data.size());
Rui Ueyamaf2a62752017-01-06 05:33:45 +0000186 } else {
Rui Ueyama283f56a2017-09-27 21:38:02 +0000187 writePaxHeader(OS, Fullpath);
188 writeUstarHeader(OS, "", "", Data.size());
Rui Ueyamaf2a62752017-01-06 05:33:45 +0000189 }
190
Rui Ueyama4bb7883f2017-01-06 02:29:48 +0000191 OS << Data;
192 pad(OS);
193
194 // POSIX requires tar archives end with two null blocks.
195 // Here, we write the terminator and then seek back, so that
196 // the file being output is terminated correctly at any moment.
197 uint64_t Pos = OS.tell();
198 OS << std::string(BlockSize * 2, '\0');
199 OS.seek(Pos);
200 OS.flush();
201}