LLVM 24.0.0git
TarWriter.cpp
Go to the documentation of this file.
1//===-- TarWriter.cpp - Tar archive file creator --------------------------===//
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// TarWriter class provides a feature to create a tar archive file.
10//
11// 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.
14//
15// 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.
18//
19// The struct definition of UstarHeader is copied from
20// https://www.freebsd.org/cgi/man.cgi?query=tar&sektion=5
21//
22//===----------------------------------------------------------------------===//
23
25#include "llvm/ADT/StringRef.h"
28#include "llvm/Support/Path.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
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];
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
57 UstarHeader Hdr = {};
58 memcpy(Hdr.Magic, "ustar", 5); // Ustar magic
59 memcpy(Hdr.Version, "00", 2); // Ustar version
60 return Hdr;
61}
62
63// 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.
70static std::string formatPax(StringRef Key, StringRef Val) {
71 int Len = Key.size() + Val.size() + 3; // +3 for " ", "=" and "\n"
72
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.
81// This function forwards the current file position to the next boundary.
82static 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];
97 snprintf(Hdr.Checksum, sizeof(Hdr.Checksum), "%06o", Chksum);
98}
99
100// Writes a file size to the Size field of a tar header. The field holds 11
101// octal digits plus a terminating NUL, so the largest representable size is
102// 8 GiB - 1. Clamping the value also lets the compiler prove that the output
103// fits, which avoids -Wformat-truncation warnings in optimized builds.
104//
105// FIXME: Sizes come from data handed to TarWriter::append(), which can be
106// derived from user input, so this assert can fire at runtime. In release
107// builds, larger sizes are clamped, which yields a corrupt archive. They should
108// either be reported to the caller as an error, or be encoded in a PAX "size"
109// record.
110static void writeSize(UstarHeader &Hdr, uint64_t Size) {
111 const uint64_t MaxSize = 077777777777;
112 assert(Size <= MaxSize && "file is too large for a ustar header");
113 Size = std::min(Size, MaxSize);
114 snprintf(Hdr.Size, sizeof(Hdr.Size), "%011llo",
115 static_cast<unsigned long long>(Size));
116}
117
118// Create a tar header and write it to a given output stream.
120 // A PAX header consists of a 512-byte header followed
121 // by key-value strings. First, create key-value strings.
122 std::string PaxAttr = formatPax("path", Path);
123
124 // Create a 512-byte header.
126 writeSize(Hdr, PaxAttr.size());
127 Hdr.TypeFlag = 'x'; // PAX magic
128 computeChecksum(Hdr);
129
130 // Write them down.
131 OS << StringRef(reinterpret_cast<char *>(&Hdr), sizeof(Hdr));
132 OS << PaxAttr;
133 pad(OS);
134}
135
136// Path fits in a Ustar header if
137//
138// - Path is less than 100 characters long, or
139// - Path is in the form of "<prefix>/<name>" where <prefix> is less
140// than or equal to 155 characters long and <name> is less than 100
141// characters long. Both <prefix> and <name> can contain extra '/'.
142//
143// If Path fits in a Ustar header, updates Prefix and Name and returns true.
144// Otherwise, returns false.
145static bool splitUstar(StringRef Path, StringRef &Prefix, StringRef &Name) {
146 if (Path.size() < sizeof(UstarHeader::Name)) {
147 Prefix = "";
148 Name = Path;
149 return true;
150 }
151
152 // tar 1.13 and earlier unconditionally look at the tar header interpreted
153 // as an 'oldgnu_header', which has an 'isextended' byte at offset 482 in the
154 // header, corresponding to offset 137 in the prefix. That's the version of
155 // tar in gnuwin, so only use 137 of the 155 bytes in the prefix. This means
156 // we'll need a pax header after 237 bytes of path instead of after 255,
157 // but in return paths up to 237 bytes work with gnuwin, instead of just
158 // 137 bytes of directory + 100 bytes of basename previously.
159 // (tar-1.13 also doesn't support pax headers, but in practice all paths in
160 // llvm's test suite are short enough for that to not matter.)
161 const int MaxPrefix = 137;
162 size_t Sep = Path.rfind('/', MaxPrefix + 1);
163 if (Sep == StringRef::npos)
164 return false;
165 if (Path.size() - Sep - 1 >= sizeof(UstarHeader::Name))
166 return false;
167
168 Prefix = Path.substr(0, Sep);
169 Name = Path.substr(Sep + 1);
170 return true;
171}
172
173// The PAX header is an extended format, so a PAX header needs
174// to be followed by a "real" header.
176 StringRef Name, size_t Size) {
178 memcpy(Hdr.Name, Name.data(), Name.size());
179 memcpy(Hdr.Mode, "0000664", 8);
180 writeSize(Hdr, Size);
181 memcpy(Hdr.Prefix, Prefix.data(), Prefix.size());
182 computeChecksum(Hdr);
183 OS << StringRef(reinterpret_cast<char *>(&Hdr), sizeof(Hdr));
184}
185
186// Creates a TarWriter instance and returns it.
188 StringRef BaseDir) {
189 using namespace sys::fs;
190 int FD;
191 if (std::error_code EC =
192 openFileForWrite(OutputPath, FD, CD_CreateAlways, OF_None))
193 return make_error<StringError>("cannot open " + OutputPath, EC);
194 return std::unique_ptr<TarWriter>(new TarWriter(FD, BaseDir));
195}
196
197TarWriter::TarWriter(int FD, StringRef BaseDir)
198 : OS(FD, /*shouldClose=*/true, /*unbuffered=*/false),
199 BaseDir(std::string(BaseDir)) {}
200
201// Append a given file to an archive.
203 // Write Path and Data.
204 std::string Fullpath = BaseDir + "/" + sys::path::convert_to_slash(Path);
205
206 // We do not want to include the same file more than once.
207 if (!Files.insert(Fullpath).second)
208 return;
209
210 StringRef Prefix;
211 StringRef Name;
212 if (splitUstar(Fullpath, Prefix, Name)) {
213 writeUstarHeader(OS, Prefix, Name, Data.size());
214 } else {
215 writePaxHeader(OS, Fullpath);
216 writeUstarHeader(OS, "", "", Data.size());
217 }
218
219 OS << Data;
220 pad(OS);
221
222 // POSIX requires tar archives end with two null blocks.
223 // Here, we write the terminator and then seek back, so that
224 // the file being output is terminated correctly at any moment.
225 uint64_t Pos = OS.tell();
226 OS << std::string(BlockSize * 2, '\0');
227 OS.seek(Pos);
228 OS.flush();
229}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
#define I(x, y, z)
Definition MD5.cpp:57
static void writePaxHeader(raw_fd_ostream &OS, StringRef Path)
static void writeUstarHeader(raw_fd_ostream &OS, StringRef Prefix, StringRef Name, size_t Size)
static void pad(raw_fd_ostream &OS)
Definition TarWriter.cpp:82
static std::string formatPax(StringRef Key, StringRef Val)
Definition TarWriter.cpp:70
static UstarHeader makeUstarHeader()
Definition TarWriter.cpp:56
static const int BlockSize
Definition TarWriter.cpp:33
static void computeChecksum(UstarHeader &Hdr)
Definition TarWriter.cpp:88
static void writeSize(UstarHeader &Hdr, uint64_t Size)
static bool splitUstar(StringRef Path, StringRef &Prefix, StringRef &Name)
Tagged union holding either a T or a Error.
Definition Error.h:485
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
static constexpr size_t npos
Definition StringRef.h:58
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
static LLVM_ABI Expected< std::unique_ptr< TarWriter > > create(StringRef OutputPath, StringRef BaseDir)
LLVM_ABI void append(StringRef Path, StringRef Data)
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
LLVM_ABI std::string str() const
Return the twine contents as a std::string.
Definition Twine.cpp:17
A raw_ostream that writes to a file descriptor.
uint64_t seek(uint64_t off)
Flushes the stream and repositions the underlying file descriptor position to the offset specified fr...
uint64_t tell() const
tell - Return the current offset with the file.
LLVM_ABI std::string convert_to_slash(StringRef path, Style style=Style::native)
Replaces backslashes with slashes if Windows.
Definition Path.cpp:585
This is an optimization pass for GlobalISel generic memory operations.
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:149
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:879
char Name[100]
Definition TarWriter.cpp:36
char Pad[12]
Definition TarWriter.cpp:52
char Mtime[12]
Definition TarWriter.cpp:41
char Checksum[8]
Definition TarWriter.cpp:42
char Gid[8]
Definition TarWriter.cpp:39
char DevMajor[8]
Definition TarWriter.cpp:49
char Prefix[155]
Definition TarWriter.cpp:51
char Gname[32]
Definition TarWriter.cpp:48
char Size[12]
Definition TarWriter.cpp:40
char Uid[8]
Definition TarWriter.cpp:38
char Version[2]
Definition TarWriter.cpp:46
char Uname[32]
Definition TarWriter.cpp:47
char Linkname[100]
Definition TarWriter.cpp:44
char DevMinor[8]
Definition TarWriter.cpp:50
char Magic[6]
Definition TarWriter.cpp:45
char Mode[8]
Definition TarWriter.cpp:37