blob: 5fc17d2763776d23261df9182701be1935549617 [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
112// The PAX header is an extended format, so a PAX header needs
113// to be followed by a "real" header.
Rui Ueyamaf2a62752017-01-06 05:33:45 +0000114static void writeUstarHeader(raw_fd_ostream &OS, StringRef Path, size_t Size) {
Rui Ueyama4bb7883f2017-01-06 02:29:48 +0000115 UstarHeader Hdr = {};
Rui Ueyamaf2a62752017-01-06 05:33:45 +0000116 memcpy(Hdr.Name, Path.data(), Path.size());
Reid Kleckner5984d012017-01-06 18:22:18 +0000117 memcpy(Hdr.Mode, "0000664", 8);
118 snprintf(Hdr.Size, sizeof(Hdr.Size), "%011zo", Size);
Rui Ueyama4bb7883f2017-01-06 02:29:48 +0000119 memcpy(Hdr.Magic, "ustar", 6);
Rui Ueyama4bb7883f2017-01-06 02:29:48 +0000120 computeChecksum(Hdr);
121 OS << StringRef(reinterpret_cast<char *>(&Hdr), sizeof(Hdr));
122}
123
124// We want to use '/' as a path separator even on Windows.
125// This function canonicalizes a given path.
126static std::string canonicalize(std::string S) {
127#ifdef LLVM_ON_WIN32
128 std::replace(S.begin(), S.end(), '\\', '/');
129#endif
130 return S;
131}
132
133// Creates a TarWriter instance and returns it.
134Expected<std::unique_ptr<TarWriter>> TarWriter::create(StringRef OutputPath,
135 StringRef BaseDir) {
136 int FD;
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));
140}
141
142TarWriter::TarWriter(int FD, StringRef BaseDir)
143 : OS(FD, /*shouldClose=*/true, /*unbuffered=*/false), BaseDir(BaseDir) {}
144
145// Append a given file to an archive.
146void TarWriter::append(StringRef Path, StringRef Data) {
147 // Write Path and Data.
Rui Ueyamaf2a62752017-01-06 05:33:45 +0000148 std::string S = BaseDir + "/" + canonicalize(Path) + "\0";
149 if (S.size() <= sizeof(UstarHeader::Name)) {
150 writeUstarHeader(OS, S, Data.size());
151 } else {
152 writePaxHeader(OS, S);
153 writeUstarHeader(OS, "", Data.size());
154 }
155
Rui Ueyama4bb7883f2017-01-06 02:29:48 +0000156 OS << Data;
157 pad(OS);
158
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');
164 OS.seek(Pos);
165 OS.flush();
166}