xref: /llvm-project/llvm/lib/Support/TarWriter.cpp (revision 4687b454339b9072e15df55e52ae8bc2a266225d)
14bb7883fSRui Ueyama //===-- TarWriter.cpp - Tar archive file creator --------------------------===//
24bb7883fSRui Ueyama //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
64bb7883fSRui Ueyama //
74bb7883fSRui Ueyama //===----------------------------------------------------------------------===//
84bb7883fSRui Ueyama //
94bb7883fSRui Ueyama // TarWriter class provides a feature to create a tar archive file.
104bb7883fSRui Ueyama //
11f2a62751SRui Ueyama // I put emphasis on simplicity over comprehensiveness when implementing this
12f2a62751SRui Ueyama // class because we don't need a full-fledged archive file generator in LLVM
13f2a62751SRui Ueyama // at the moment.
144bb7883fSRui Ueyama //
15f2a62751SRui Ueyama // The filename field in the Unix V7 tar header is 100 bytes. Longer filenames
16f2a62751SRui Ueyama // are stored using the PAX extension. The PAX header is standardized in
17f2a62751SRui Ueyama // POSIX.1-2001.
184bb7883fSRui Ueyama //
194bb7883fSRui Ueyama // The struct definition of UstarHeader is copied from
204bb7883fSRui Ueyama // https://www.freebsd.org/cgi/man.cgi?query=tar&sektion=5
214bb7883fSRui Ueyama //
224bb7883fSRui Ueyama //===----------------------------------------------------------------------===//
234bb7883fSRui Ueyama 
244bb7883fSRui Ueyama #include "llvm/Support/TarWriter.h"
254bb7883fSRui Ueyama #include "llvm/ADT/StringRef.h"
264bb7883fSRui Ueyama #include "llvm/Support/FileSystem.h"
274bb7883fSRui Ueyama #include "llvm/Support/MathExtras.h"
283e649039SRui Ueyama #include "llvm/Support/Path.h"
294bb7883fSRui Ueyama 
304bb7883fSRui Ueyama using namespace llvm;
314bb7883fSRui Ueyama 
324bb7883fSRui Ueyama // Each file in an archive must be aligned to this block size.
334bb7883fSRui Ueyama static const int BlockSize = 512;
344bb7883fSRui Ueyama 
354bb7883fSRui Ueyama struct UstarHeader {
364bb7883fSRui Ueyama   char Name[100];
374bb7883fSRui Ueyama   char Mode[8];
384bb7883fSRui Ueyama   char Uid[8];
394bb7883fSRui Ueyama   char Gid[8];
404bb7883fSRui Ueyama   char Size[12];
414bb7883fSRui Ueyama   char Mtime[12];
424bb7883fSRui Ueyama   char Checksum[8];
434bb7883fSRui Ueyama   char TypeFlag;
444bb7883fSRui Ueyama   char Linkname[100];
454bb7883fSRui Ueyama   char Magic[6];
464bb7883fSRui Ueyama   char Version[2];
474bb7883fSRui Ueyama   char Uname[32];
484bb7883fSRui Ueyama   char Gname[32];
494bb7883fSRui Ueyama   char DevMajor[8];
504bb7883fSRui Ueyama   char DevMinor[8];
514bb7883fSRui Ueyama   char Prefix[155];
524bb7883fSRui Ueyama   char Pad[12];
534bb7883fSRui Ueyama };
544bb7883fSRui Ueyama static_assert(sizeof(UstarHeader) == BlockSize, "invalid Ustar header");
554bb7883fSRui Ueyama 
makeUstarHeader()56a84ab073SRui Ueyama static UstarHeader makeUstarHeader() {
57a84ab073SRui Ueyama   UstarHeader Hdr = {};
58a84ab073SRui Ueyama   memcpy(Hdr.Magic, "ustar", 5); // Ustar magic
59a84ab073SRui Ueyama   memcpy(Hdr.Version, "00", 2);  // Ustar version
60a84ab073SRui Ueyama   return Hdr;
61a84ab073SRui Ueyama }
62a84ab073SRui Ueyama 
634bb7883fSRui Ueyama // A PAX attribute is in the form of "<length> <key>=<value>\n"
644bb7883fSRui Ueyama // where <length> is the length of the entire string including
654bb7883fSRui Ueyama // the length field itself. An example string is this.
664bb7883fSRui Ueyama //
674bb7883fSRui Ueyama //   25 ctime=1084839148.1212\n
684bb7883fSRui Ueyama //
694bb7883fSRui Ueyama // This function create such string.
formatPax(StringRef Key,StringRef Val)70f2a62751SRui Ueyama static std::string formatPax(StringRef Key, StringRef Val) {
71f2a62751SRui Ueyama   int Len = Key.size() + Val.size() + 3; // +3 for " ", "=" and "\n"
724bb7883fSRui Ueyama 
734bb7883fSRui Ueyama   // We need to compute total size twice because appending
744bb7883fSRui Ueyama   // a length field could change total size by one.
754bb7883fSRui Ueyama   int Total = Len + Twine(Len).str().size();
764bb7883fSRui Ueyama   Total = Len + Twine(Total).str().size();
774bb7883fSRui Ueyama   return (Twine(Total) + " " + Key + "=" + Val + "\n").str();
784bb7883fSRui Ueyama }
794bb7883fSRui Ueyama 
804bb7883fSRui Ueyama // Headers in tar files must be aligned to 512 byte boundaries.
81f2a62751SRui Ueyama // This function forwards the current file position to the next boundary.
pad(raw_fd_ostream & OS)824bb7883fSRui Ueyama static void pad(raw_fd_ostream &OS) {
834bb7883fSRui Ueyama   uint64_t Pos = OS.tell();
844bb7883fSRui Ueyama   OS.seek(alignTo(Pos, BlockSize));
854bb7883fSRui Ueyama }
864bb7883fSRui Ueyama 
874bb7883fSRui Ueyama // Computes a checksum for a tar header.
computeChecksum(UstarHeader & Hdr)884bb7883fSRui Ueyama static void computeChecksum(UstarHeader &Hdr) {
894bb7883fSRui Ueyama   // Before computing a checksum, checksum field must be
904bb7883fSRui Ueyama   // filled with space characters.
914bb7883fSRui Ueyama   memset(Hdr.Checksum, ' ', sizeof(Hdr.Checksum));
924bb7883fSRui Ueyama 
934bb7883fSRui Ueyama   // Compute a checksum and set it to the checksum field.
944bb7883fSRui Ueyama   unsigned Chksum = 0;
954bb7883fSRui Ueyama   for (size_t I = 0; I < sizeof(Hdr); ++I)
964bb7883fSRui Ueyama     Chksum += reinterpret_cast<uint8_t *>(&Hdr)[I];
975984d018SReid Kleckner   snprintf(Hdr.Checksum, sizeof(Hdr.Checksum), "%06o", Chksum);
984bb7883fSRui Ueyama }
994bb7883fSRui Ueyama 
1004bb7883fSRui Ueyama // Create a tar header and write it to a given output stream.
writePaxHeader(raw_fd_ostream & OS,StringRef Path)101f2a62751SRui Ueyama static void writePaxHeader(raw_fd_ostream &OS, StringRef Path) {
1024bb7883fSRui Ueyama   // A PAX header consists of a 512-byte header followed
1034bb7883fSRui Ueyama   // by key-value strings. First, create key-value strings.
1044bb7883fSRui Ueyama   std::string PaxAttr = formatPax("path", Path);
1054bb7883fSRui Ueyama 
1064bb7883fSRui Ueyama   // Create a 512-byte header.
107a84ab073SRui Ueyama   UstarHeader Hdr = makeUstarHeader();
1085984d018SReid Kleckner   snprintf(Hdr.Size, sizeof(Hdr.Size), "%011zo", PaxAttr.size());
1094bb7883fSRui Ueyama   Hdr.TypeFlag = 'x'; // PAX magic
1104bb7883fSRui Ueyama   computeChecksum(Hdr);
1114bb7883fSRui Ueyama 
1124bb7883fSRui Ueyama   // Write them down.
1134bb7883fSRui Ueyama   OS << StringRef(reinterpret_cast<char *>(&Hdr), sizeof(Hdr));
1144bb7883fSRui Ueyama   OS << PaxAttr;
1154bb7883fSRui Ueyama   pad(OS);
1164bb7883fSRui Ueyama }
1174bb7883fSRui Ueyama 
118283f56acSRui Ueyama // Path fits in a Ustar header if
119283f56acSRui Ueyama //
120283f56acSRui Ueyama // - Path is less than 100 characters long, or
121283f56acSRui Ueyama // - Path is in the form of "<prefix>/<name>" where <prefix> is less
122283f56acSRui Ueyama //   than or equal to 155 characters long and <name> is less than 100
123283f56acSRui Ueyama //   characters long. Both <prefix> and <name> can contain extra '/'.
124283f56acSRui Ueyama //
125283f56acSRui Ueyama // If Path fits in a Ustar header, updates Prefix and Name and returns true.
126283f56acSRui Ueyama // Otherwise, returns false.
splitUstar(StringRef Path,StringRef & Prefix,StringRef & Name)127283f56acSRui Ueyama static bool splitUstar(StringRef Path, StringRef &Prefix, StringRef &Name) {
128283f56acSRui Ueyama   if (Path.size() < sizeof(UstarHeader::Name)) {
1295908845aSRui Ueyama     Prefix = "";
130283f56acSRui Ueyama     Name = Path;
131283f56acSRui Ueyama     return true;
132999f094aSRui Ueyama   }
133999f094aSRui Ueyama 
134*4687b454SFangrui Song   // tar 1.13 and earlier unconditionally look at the tar header interpreted
135*4687b454SFangrui Song   // as an 'oldgnu_header', which has an 'isextended' byte at offset 482 in the
136*4687b454SFangrui Song   // header, corresponding to offset 137 in the prefix. That's the version of
137*4687b454SFangrui Song   // tar in gnuwin, so only use 137 of the 155 bytes in the prefix. This means
138*4687b454SFangrui Song   // we'll need a pax header after 237 bytes of path instead of after 255,
139*4687b454SFangrui Song   // but in return paths up to 237 bytes work with gnuwin, instead of just
140*4687b454SFangrui Song   // 137 bytes of directory + 100 bytes of basename previously.
141*4687b454SFangrui Song   // (tar-1.13 also doesn't support pax headers, but in practice all paths in
142*4687b454SFangrui Song   // llvm's test suite are short enough for that to not matter.)
143*4687b454SFangrui Song   const int MaxPrefix = 137;
144*4687b454SFangrui Song   size_t Sep = Path.rfind('/', MaxPrefix + 1);
145283f56acSRui Ueyama   if (Sep == StringRef::npos)
146283f56acSRui Ueyama     return false;
147283f56acSRui Ueyama   if (Path.size() - Sep - 1 >= sizeof(UstarHeader::Name))
148283f56acSRui Ueyama     return false;
149283f56acSRui Ueyama 
150283f56acSRui Ueyama   Prefix = Path.substr(0, Sep);
151283f56acSRui Ueyama   Name = Path.substr(Sep + 1);
152283f56acSRui Ueyama   return true;
153999f094aSRui Ueyama }
154999f094aSRui Ueyama 
1554bb7883fSRui Ueyama // The PAX header is an extended format, so a PAX header needs
1564bb7883fSRui Ueyama // to be followed by a "real" header.
writeUstarHeader(raw_fd_ostream & OS,StringRef Prefix,StringRef Name,size_t Size)157283f56acSRui Ueyama static void writeUstarHeader(raw_fd_ostream &OS, StringRef Prefix,
158283f56acSRui Ueyama                              StringRef Name, size_t Size) {
159a84ab073SRui Ueyama   UstarHeader Hdr = makeUstarHeader();
160999f094aSRui Ueyama   memcpy(Hdr.Name, Name.data(), Name.size());
1615984d018SReid Kleckner   memcpy(Hdr.Mode, "0000664", 8);
1625984d018SReid Kleckner   snprintf(Hdr.Size, sizeof(Hdr.Size), "%011zo", Size);
163999f094aSRui Ueyama   memcpy(Hdr.Prefix, Prefix.data(), Prefix.size());
1644bb7883fSRui Ueyama   computeChecksum(Hdr);
1654bb7883fSRui Ueyama   OS << StringRef(reinterpret_cast<char *>(&Hdr), sizeof(Hdr));
1664bb7883fSRui Ueyama }
1674bb7883fSRui Ueyama 
1684bb7883fSRui Ueyama // Creates a TarWriter instance and returns it.
create(StringRef OutputPath,StringRef BaseDir)1694bb7883fSRui Ueyama Expected<std::unique_ptr<TarWriter>> TarWriter::create(StringRef OutputPath,
1704bb7883fSRui Ueyama                                                        StringRef BaseDir) {
1711f67a3cbSZachary Turner   using namespace sys::fs;
1724bb7883fSRui Ueyama   int FD;
1731f67a3cbSZachary Turner   if (std::error_code EC =
1741f67a3cbSZachary Turner           openFileForWrite(OutputPath, FD, CD_CreateAlways, OF_None))
1754bb7883fSRui Ueyama     return make_error<StringError>("cannot open " + OutputPath, EC);
1764bb7883fSRui Ueyama   return std::unique_ptr<TarWriter>(new TarWriter(FD, BaseDir));
1774bb7883fSRui Ueyama }
1784bb7883fSRui Ueyama 
TarWriter(int FD,StringRef BaseDir)1794bb7883fSRui Ueyama TarWriter::TarWriter(int FD, StringRef BaseDir)
180adcd0268SBenjamin Kramer     : OS(FD, /*shouldClose=*/true, /*unbuffered=*/false),
181adcd0268SBenjamin Kramer       BaseDir(std::string(BaseDir)) {}
1824bb7883fSRui Ueyama 
1834bb7883fSRui Ueyama // Append a given file to an archive.
append(StringRef Path,StringRef Data)1844bb7883fSRui Ueyama void TarWriter::append(StringRef Path, StringRef Data) {
1854bb7883fSRui Ueyama   // Write Path and Data.
186283f56acSRui Ueyama   std::string Fullpath = BaseDir + "/" + sys::path::convert_to_slash(Path);
187283f56acSRui Ueyama 
188f91f0b0aSGeorge Rimar   // We do not want to include the same file more than once.
189f91f0b0aSGeorge Rimar   if (!Files.insert(Fullpath).second)
190f91f0b0aSGeorge Rimar     return;
191f91f0b0aSGeorge Rimar 
192283f56acSRui Ueyama   StringRef Prefix;
193283f56acSRui Ueyama   StringRef Name;
194283f56acSRui Ueyama   if (splitUstar(Fullpath, Prefix, Name)) {
195283f56acSRui Ueyama     writeUstarHeader(OS, Prefix, Name, Data.size());
196f2a62751SRui Ueyama   } else {
197283f56acSRui Ueyama     writePaxHeader(OS, Fullpath);
198283f56acSRui Ueyama     writeUstarHeader(OS, "", "", Data.size());
199f2a62751SRui Ueyama   }
200f2a62751SRui Ueyama 
2014bb7883fSRui Ueyama   OS << Data;
2024bb7883fSRui Ueyama   pad(OS);
2034bb7883fSRui Ueyama 
2044bb7883fSRui Ueyama   // POSIX requires tar archives end with two null blocks.
2054bb7883fSRui Ueyama   // Here, we write the terminator and then seek back, so that
2064bb7883fSRui Ueyama   // the file being output is terminated correctly at any moment.
2074bb7883fSRui Ueyama   uint64_t Pos = OS.tell();
2084bb7883fSRui Ueyama   OS << std::string(BlockSize * 2, '\0');
2094bb7883fSRui Ueyama   OS.seek(Pos);
2104bb7883fSRui Ueyama   OS.flush();
2114bb7883fSRui Ueyama }
212