PackageTool.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. //
  2. // Copyright (c) 2008-2014 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include <Atomic/Atomic.h>
  23. #include <Atomic/Core/Context.h>
  24. #include <Atomic/Container/ArrayPtr.h>
  25. #include <Atomic/Core/ProcessUtils.h>
  26. #include <Atomic/IO/File.h>
  27. #include <Atomic/IO/FileSystem.h>
  28. #include <Atomic/IO/PackageFile.h>
  29. #ifdef WIN32
  30. #include <windows.h>
  31. #endif
  32. #include <LZ4/lz4.h>
  33. #include <LZ4/lz4hc.h>
  34. #include <Atomic/DebugNew.h>
  35. using namespace Atomic;
  36. static const unsigned COMPRESSED_BLOCK_SIZE = 32768;
  37. struct FileEntry
  38. {
  39. String name_;
  40. unsigned offset_;
  41. unsigned size_;
  42. unsigned checksum_;
  43. };
  44. SharedPtr<Context> context_(new Context());
  45. SharedPtr<FileSystem> fileSystem_(new FileSystem(context_));
  46. String basePath_;
  47. Vector<FileEntry> entries_;
  48. unsigned checksum_ = 0;
  49. bool compress_ = false;
  50. bool quiet_ = false;
  51. unsigned blockSize_ = COMPRESSED_BLOCK_SIZE;
  52. String ignoreExtensions_[] = {
  53. ".bak",
  54. ".rule",
  55. ""
  56. };
  57. int main(int argc, char** argv);
  58. void Run(const Vector<String>& arguments);
  59. void ProcessFile(const String& fileName, const String& rootDir);
  60. void WritePackageFile(const String& fileName, const String& rootDir);
  61. void WriteHeader(File& dest);
  62. int main(int argc, char** argv)
  63. {
  64. Vector<String> arguments;
  65. #ifdef WIN32
  66. arguments = ParseArguments(GetCommandLineW());
  67. #else
  68. arguments = ParseArguments(argc, argv);
  69. #endif
  70. Run(arguments);
  71. return 0;
  72. }
  73. void Run(const Vector<String>& arguments)
  74. {
  75. if (arguments.Size() < 2)
  76. ErrorExit(
  77. "Usage: PackageTool <directory to process> <package name> [basepath] [options]\n"
  78. "\n"
  79. "Options:\n"
  80. "-c Enable package file LZ4 compression\n"
  81. "-q Enable quiet mode\n"
  82. "\n"
  83. "Basepath is an optional prefix that will be added to the file entries.\n\n"
  84. "Alternative output usage: PackageTool <output option> <package name>\n"
  85. "Output option:\n"
  86. "-i Output package file information\n"
  87. "-l Output file names (including their paths) contained in the package\n"
  88. "-L Similar to -l but also output compression ratio (compressed package file only)\n"
  89. );
  90. const String& dirName = arguments[0];
  91. const String& packageName = arguments[1];
  92. bool isOutputMode = arguments[0].Length() == 2 && arguments[0][0] == '-';
  93. if (arguments.Size() > 2)
  94. {
  95. for (unsigned i = 2; i < arguments.Size(); ++i)
  96. {
  97. if (arguments[i][0] != '-')
  98. basePath_ = AddTrailingSlash(arguments[i]);
  99. else
  100. {
  101. if (arguments[i].Length() > 1)
  102. {
  103. switch (arguments[i][1])
  104. {
  105. case 'c':
  106. compress_ = true;
  107. break;
  108. case 'q':
  109. quiet_ = true;
  110. break;
  111. default:
  112. ErrorExit("Unrecognized option");
  113. }
  114. }
  115. }
  116. }
  117. }
  118. if (!isOutputMode)
  119. {
  120. if (!quiet_)
  121. PrintLine("Scanning directory " + dirName + " for files");
  122. // Get the file list recursively
  123. Vector<String> fileNames;
  124. fileSystem_->ScanDir(fileNames, dirName, "*.*", SCAN_FILES, true);
  125. if (!fileNames.Size())
  126. ErrorExit("No files found");
  127. // Check for extensions to ignore
  128. for (unsigned i = fileNames.Size() - 1; i < fileNames.Size(); --i)
  129. {
  130. String extension = GetExtension(fileNames[i]);
  131. for (unsigned j = 0; ignoreExtensions_[j].Length(); ++j)
  132. {
  133. if (extension == ignoreExtensions_[j])
  134. {
  135. fileNames.Erase(fileNames.Begin() + i);
  136. break;
  137. }
  138. }
  139. }
  140. for (unsigned i = 0; i < fileNames.Size(); ++i)
  141. ProcessFile(fileNames[i], dirName);
  142. WritePackageFile(packageName, dirName);
  143. }
  144. else
  145. {
  146. SharedPtr<PackageFile> packageFile(new PackageFile(context_, packageName));
  147. bool outputCompressionRatio = false;
  148. switch (arguments[0][1])
  149. {
  150. case 'i':
  151. PrintLine("Number of files: " + String(packageFile->GetNumFiles()));
  152. PrintLine("File data size: " + String(packageFile->GetTotalDataSize()));
  153. PrintLine("Package size: " + String(packageFile->GetTotalSize()));
  154. PrintLine("Checksum: " + String(packageFile->GetChecksum()));
  155. PrintLine("Compressed: " + String(packageFile->IsCompressed() ? "yes" : "no"));
  156. break;
  157. case 'L':
  158. if (!packageFile->IsCompressed())
  159. ErrorExit("Invalid output option: -L is applicable for compressed package file only");
  160. outputCompressionRatio = true;
  161. // Fallthrough
  162. case 'l':
  163. {
  164. const HashMap<String, PackageEntry>& entries = packageFile->GetEntries();
  165. for (HashMap<String, PackageEntry>::ConstIterator i = entries.Begin(); i != entries.End();)
  166. {
  167. HashMap<String, PackageEntry>::ConstIterator current = i++;
  168. String fileEntry(current->first_);
  169. if (outputCompressionRatio)
  170. {
  171. unsigned compressedSize =
  172. (i == entries.End() ? packageFile->GetTotalSize() - sizeof(unsigned) : i->second_.offset_) -
  173. current->second_.offset_;
  174. fileEntry.AppendWithFormat("\tin: %u\tout: %u\tratio: %f", current->second_.size_, compressedSize,
  175. compressedSize ? 1.f * current->second_.size_ / compressedSize : 0.f);
  176. }
  177. PrintLine(fileEntry);
  178. }
  179. }
  180. break;
  181. default:
  182. ErrorExit("Unrecognized output option");
  183. }
  184. }
  185. }
  186. void ProcessFile(const String& fileName, const String& rootDir)
  187. {
  188. String fullPath = rootDir + "/" + fileName;
  189. File file(context_);
  190. if (!file.Open(fullPath))
  191. ErrorExit("Could not open file " + fileName);
  192. if (!file.GetSize())
  193. return;
  194. FileEntry newEntry;
  195. newEntry.name_ = fileName;
  196. newEntry.offset_ = 0; // Offset not yet known
  197. newEntry.size_ = file.GetSize();
  198. newEntry.checksum_ = 0; // Will be calculated later
  199. entries_.Push(newEntry);
  200. }
  201. void WritePackageFile(const String& fileName, const String& rootDir)
  202. {
  203. if (!quiet_)
  204. PrintLine("Writing package");
  205. File dest(context_);
  206. if (!dest.Open(fileName, FILE_WRITE))
  207. ErrorExit("Could not open output file " + fileName);
  208. // Write ID, number of files & placeholder for checksum
  209. WriteHeader(dest);
  210. for (unsigned i = 0; i < entries_.Size(); ++i)
  211. {
  212. // Write entry (correct offset is still unknown, will be filled in later)
  213. dest.WriteString(basePath_ + entries_[i].name_);
  214. dest.WriteUInt(entries_[i].offset_);
  215. dest.WriteUInt(entries_[i].size_);
  216. dest.WriteUInt(entries_[i].checksum_);
  217. }
  218. unsigned totalDataSize = 0;
  219. unsigned lastOffset;
  220. // Write file data, calculate checksums & correct offsets
  221. for (unsigned i = 0; i < entries_.Size(); ++i)
  222. {
  223. lastOffset = entries_[i].offset_ = dest.GetSize();
  224. String fileFullPath = rootDir + "/" + entries_[i].name_;
  225. File srcFile(context_, fileFullPath);
  226. if (!srcFile.IsOpen())
  227. ErrorExit("Could not open file " + fileFullPath);
  228. unsigned dataSize = entries_[i].size_;
  229. totalDataSize += dataSize;
  230. SharedArrayPtr<unsigned char> buffer(new unsigned char[dataSize]);
  231. if (srcFile.Read(&buffer[0], dataSize) != dataSize)
  232. ErrorExit("Could not read file " + fileFullPath);
  233. srcFile.Close();
  234. for (unsigned j = 0; j < dataSize; ++j)
  235. {
  236. checksum_ = SDBMHash(checksum_, buffer[j]);
  237. entries_[i].checksum_ = SDBMHash(entries_[i].checksum_, buffer[j]);
  238. }
  239. if (!compress_)
  240. {
  241. if (!quiet_)
  242. PrintLine(entries_[i].name_ + " size " + String(dataSize));
  243. dest.Write(&buffer[0], entries_[i].size_);
  244. }
  245. else
  246. {
  247. SharedArrayPtr<unsigned char> compressBuffer(new unsigned char[LZ4_compressBound(blockSize_)]);
  248. unsigned pos = 0;
  249. while (pos < dataSize)
  250. {
  251. unsigned unpackedSize = blockSize_;
  252. if (pos + unpackedSize > dataSize)
  253. unpackedSize = dataSize - pos;
  254. unsigned packedSize = (unsigned)LZ4_compressHC((const char*)&buffer[pos], (char*)compressBuffer.Get(), unpackedSize);
  255. if (!packedSize)
  256. ErrorExit("LZ4 compression failed for file " + entries_[i].name_ + " at offset " + String(pos));
  257. dest.WriteUShort((unsigned short)unpackedSize);
  258. dest.WriteUShort((unsigned short)packedSize);
  259. dest.Write(compressBuffer.Get(), packedSize);
  260. pos += unpackedSize;
  261. }
  262. if (!quiet_)
  263. {
  264. unsigned totalPackedBytes = dest.GetSize() - lastOffset;
  265. String fileEntry(entries_[i].name_);
  266. fileEntry.AppendWithFormat("\tin: %u\tout: %u\tratio: %f", dataSize, totalPackedBytes,
  267. totalPackedBytes ? 1.f * dataSize / totalPackedBytes : 0.f);
  268. PrintLine(fileEntry);
  269. }
  270. }
  271. }
  272. // Write package size to the end of file to allow finding it linked to an executable file
  273. unsigned currentSize = dest.GetSize();
  274. dest.WriteUInt(currentSize + sizeof(unsigned));
  275. // Write header again with correct offsets & checksums
  276. dest.Seek(0);
  277. WriteHeader(dest);
  278. for (unsigned i = 0; i < entries_.Size(); ++i)
  279. {
  280. dest.WriteString(basePath_ + entries_[i].name_);
  281. dest.WriteUInt(entries_[i].offset_);
  282. dest.WriteUInt(entries_[i].size_);
  283. dest.WriteUInt(entries_[i].checksum_);
  284. }
  285. if (!quiet_)
  286. {
  287. PrintLine("Number of files: " + String(entries_.Size()));
  288. PrintLine("File data size: " + String(totalDataSize));
  289. PrintLine("Package size: " + String(dest.GetSize()));
  290. PrintLine("Checksum: " + String(checksum_));
  291. PrintLine("Compressed: " + String(compress_ ? "yes" : "no"));
  292. }
  293. }
  294. void WriteHeader(File& dest)
  295. {
  296. if (!compress_)
  297. dest.WriteFileID("UPAK");
  298. else
  299. dest.WriteFileID("ULZ4");
  300. dest.WriteUInt(entries_.Size());
  301. dest.WriteUInt(checksum_);
  302. }