Dump the deobfuscate data using Protocol buffers

Using Google Protocol buffers to dump the obfuscating mapping
information of being used to deobfuscate items.
* shortened file path -> original file path
* resource id -> original resource name

This patch add a new option --save-obfuscating-map to deprecate
--resource-path-shortening-map. The option
--resource-path-shortening-map is kept until no one to use it.

Bug: 246489170
Bug: 228192695
     b/228192695#comment2
Test: make WITH_TIDY=1 aapt2
Test: atest aapt2_test

Change-Id: I29733c4dbae9f6dd2f0e9b2c87b0d2046662fc59
diff --git a/tools/aapt2/optimize/Obfuscator.cpp b/tools/aapt2/optimize/Obfuscator.cpp
index 2533f80..cc21093 100644
--- a/tools/aapt2/optimize/Obfuscator.cpp
+++ b/tools/aapt2/optimize/Obfuscator.cpp
@@ -16,6 +16,7 @@
 
 #include "optimize/Obfuscator.h"
 
+#include <fstream>
 #include <map>
 #include <set>
 #include <string>
@@ -192,6 +193,29 @@
   return true;
 }
 
+bool Obfuscator::WriteObfuscationMap(const std::string& file_path) const {
+  pb::ResourceMappings resourceMappings;
+  for (const auto& [id, name] : options_.id_resource_map) {
+    auto* collapsedNameMapping = resourceMappings.mutable_collapsed_names()->add_resource_names();
+    collapsedNameMapping->set_id(id);
+    collapsedNameMapping->set_name(name);
+  }
+
+  for (const auto& [original_path, shortened_path] : options_.shortened_path_map) {
+    auto* resource_path = resourceMappings.mutable_shortened_paths()->add_resource_paths();
+    resource_path->set_original_path(original_path);
+    resource_path->set_shortened_path(shortened_path);
+  }
+
+  {  // RAII style, output the pb content to file and close fout in destructor
+    std::ofstream fout(file_path, std::ios::out | std::ios::trunc | std::ios::binary);
+    if (!fout.is_open()) {
+      return false;
+    }
+    return resourceMappings.SerializeToOstream(&fout);
+  }
+}
+
 /**
  * Tell the optimizer whether it's needed to dump information for de-obfuscating.
  *