]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/Support/TarWriter.cpp
Vendor import of llvm trunk r291274:
[FreeBSD/FreeBSD.git] / lib / Support / TarWriter.cpp
1 //===-- 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 //
12 // 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.
15 //
16 // 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.
19 //
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
30 using namespace llvm;
31
32 // Each file in an archive must be aligned to this block size.
33 static const int BlockSize = 512;
34
35 struct 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 };
54 static_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.
63 static std::string formatPax(StringRef Key, StringRef Val) {
64   int Len = Key.size() + Val.size() + 3; // +3 for " ", "=" and "\n"
65
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.
74 // This function forwards the current file position to the next boundary.
75 static 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.
81 static 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];
90   snprintf(Hdr.Checksum, sizeof(Hdr.Checksum), "%06o", Chksum);
91 }
92
93 // Create a tar header and write it to a given output stream.
94 static void writePaxHeader(raw_fd_ostream &OS, StringRef Path) {
95   // 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 = {};
101   snprintf(Hdr.Size, sizeof(Hdr.Size), "%011zo", PaxAttr.size());
102   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.
114 static void writeUstarHeader(raw_fd_ostream &OS, StringRef Path, size_t Size) {
115   UstarHeader Hdr = {};
116   memcpy(Hdr.Name, Path.data(), Path.size());
117   memcpy(Hdr.Mode, "0000664", 8);
118   snprintf(Hdr.Size, sizeof(Hdr.Size), "%011zo", Size);
119   memcpy(Hdr.Magic, "ustar", 6);
120   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.
126 static 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.
134 Expected<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
142 TarWriter::TarWriter(int FD, StringRef BaseDir)
143     : OS(FD, /*shouldClose=*/true, /*unbuffered=*/false), BaseDir(BaseDir) {}
144
145 // Append a given file to an archive.
146 void TarWriter::append(StringRef Path, StringRef Data) {
147   // Write Path and Data.
148   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
156   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 }