dexopt.cpp 114 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913
  1. /*
  2. * Copyright (C) 2016 The Android Open Source Project
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #define LOG_TAG "installd"
  17. #include <array>
  18. #include <fcntl.h>
  19. #include <stdlib.h>
  20. #include <string.h>
  21. #include <sys/capability.h>
  22. #include <sys/file.h>
  23. #include <sys/stat.h>
  24. #include <sys/time.h>
  25. #include <sys/types.h>
  26. #include <sys/resource.h>
  27. #include <sys/wait.h>
  28. #include <unistd.h>
  29. #include <iomanip>
  30. #include <android-base/file.h>
  31. #include <android-base/logging.h>
  32. #include <android-base/properties.h>
  33. #include <android-base/stringprintf.h>
  34. #include <android-base/strings.h>
  35. #include <android-base/unique_fd.h>
  36. #include <cutils/fs.h>
  37. #include <cutils/properties.h>
  38. #include <cutils/sched_policy.h>
  39. #include <dex2oat_return_codes.h>
  40. #include <log/log.h> // TODO: Move everything to base/logging.
  41. #include <openssl/sha.h>
  42. #include <private/android_filesystem_config.h>
  43. #include <processgroup/sched_policy.h>
  44. #include <selinux/android.h>
  45. #include <server_configurable_flags/get_flags.h>
  46. #include <system/thread_defs.h>
  47. #include "dexopt.h"
  48. #include "dexopt_return_codes.h"
  49. #include "globals.h"
  50. #include "installd_deps.h"
  51. #include "otapreopt_utils.h"
  52. #include "utils.h"
  53. using android::base::EndsWith;
  54. using android::base::GetBoolProperty;
  55. using android::base::GetProperty;
  56. using android::base::ReadFdToString;
  57. using android::base::ReadFully;
  58. using android::base::StringPrintf;
  59. using android::base::WriteFully;
  60. using android::base::unique_fd;
  61. namespace android {
  62. namespace installd {
  63. // Should minidebug info be included in compiled artifacts? Even if this value is
  64. // "true," usage might still be conditional to other constraints, e.g., system
  65. // property overrides.
  66. static constexpr bool kEnableMinidebugInfo = true;
  67. static constexpr const char* kMinidebugInfoSystemProperty = "dalvik.vm.dex2oat-minidebuginfo";
  68. static constexpr bool kMinidebugInfoSystemPropertyDefault = false;
  69. static constexpr const char* kMinidebugDex2oatFlag = "--generate-mini-debug-info";
  70. static constexpr const char* kDisableCompactDexFlag = "--compact-dex-level=none";
  71. // Deleter using free() for use with std::unique_ptr<>. See also UniqueCPtr<> below.
  72. struct FreeDelete {
  73. // NOTE: Deleting a const object is valid but free() takes a non-const pointer.
  74. void operator()(const void* ptr) const {
  75. free(const_cast<void*>(ptr));
  76. }
  77. };
  78. // Alias for std::unique_ptr<> that uses the C function free() to delete objects.
  79. template <typename T>
  80. using UniqueCPtr = std::unique_ptr<T, FreeDelete>;
  81. static unique_fd invalid_unique_fd() {
  82. return unique_fd(-1);
  83. }
  84. static bool is_debug_runtime() {
  85. return android::base::GetProperty("persist.sys.dalvik.vm.lib.2", "") == "libartd.so";
  86. }
  87. static bool is_debuggable_build() {
  88. return android::base::GetBoolProperty("ro.debuggable", false);
  89. }
  90. static bool clear_profile(const std::string& profile) {
  91. unique_fd ufd(open(profile.c_str(), O_WRONLY | O_NOFOLLOW | O_CLOEXEC));
  92. if (ufd.get() < 0) {
  93. if (errno != ENOENT) {
  94. PLOG(WARNING) << "Could not open profile " << profile;
  95. return false;
  96. } else {
  97. // Nothing to clear. That's ok.
  98. return true;
  99. }
  100. }
  101. if (flock(ufd.get(), LOCK_EX | LOCK_NB) != 0) {
  102. if (errno != EWOULDBLOCK) {
  103. PLOG(WARNING) << "Error locking profile " << profile;
  104. }
  105. // This implies that the app owning this profile is running
  106. // (and has acquired the lock).
  107. //
  108. // If we can't acquire the lock bail out since clearing is useless anyway
  109. // (the app will write again to the profile).
  110. //
  111. // Note:
  112. // This does not impact the this is not an issue for the profiling correctness.
  113. // In case this is needed because of an app upgrade, profiles will still be
  114. // eventually cleared by the app itself due to checksum mismatch.
  115. // If this is needed because profman advised, then keeping the data around
  116. // until the next run is again not an issue.
  117. //
  118. // If the app attempts to acquire a lock while we've held one here,
  119. // it will simply skip the current write cycle.
  120. return false;
  121. }
  122. bool truncated = ftruncate(ufd.get(), 0) == 0;
  123. if (!truncated) {
  124. PLOG(WARNING) << "Could not truncate " << profile;
  125. }
  126. if (flock(ufd.get(), LOCK_UN) != 0) {
  127. PLOG(WARNING) << "Error unlocking profile " << profile;
  128. }
  129. return truncated;
  130. }
  131. // Clear the reference profile for the given location.
  132. // The location is the profile name for primary apks or the dex path for secondary dex files.
  133. static bool clear_reference_profile(const std::string& package_name, const std::string& location,
  134. bool is_secondary_dex) {
  135. return clear_profile(create_reference_profile_path(package_name, location, is_secondary_dex));
  136. }
  137. // Clear the reference profile for the given location.
  138. // The location is the profile name for primary apks or the dex path for secondary dex files.
  139. static bool clear_current_profile(const std::string& package_name, const std::string& location,
  140. userid_t user, bool is_secondary_dex) {
  141. return clear_profile(create_current_profile_path(user, package_name, location,
  142. is_secondary_dex));
  143. }
  144. // Clear the reference profile for the primary apk of the given package.
  145. // The location is the profile name for primary apks or the dex path for secondary dex files.
  146. bool clear_primary_reference_profile(const std::string& package_name,
  147. const std::string& location) {
  148. return clear_reference_profile(package_name, location, /*is_secondary_dex*/false);
  149. }
  150. // Clear all current profile for the primary apk of the given package.
  151. // The location is the profile name for primary apks or the dex path for secondary dex files.
  152. bool clear_primary_current_profiles(const std::string& package_name, const std::string& location) {
  153. bool success = true;
  154. // For secondary dex files, we don't really need the user but we use it for sanity checks.
  155. std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
  156. for (auto user : users) {
  157. success &= clear_current_profile(package_name, location, user, /*is_secondary_dex*/false);
  158. }
  159. return success;
  160. }
  161. // Clear the current profile for the primary apk of the given package and user.
  162. bool clear_primary_current_profile(const std::string& package_name, const std::string& location,
  163. userid_t user) {
  164. return clear_current_profile(package_name, location, user, /*is_secondary_dex*/false);
  165. }
  166. static std::vector<std::string> SplitBySpaces(const std::string& str) {
  167. if (str.empty()) {
  168. return {};
  169. }
  170. return android::base::Split(str, " ");
  171. }
  172. static const char* get_location_from_path(const char* path) {
  173. static constexpr char kLocationSeparator = '/';
  174. const char *location = strrchr(path, kLocationSeparator);
  175. if (location == nullptr) {
  176. return path;
  177. } else {
  178. // Skip the separator character.
  179. return location + 1;
  180. }
  181. }
  182. // ExecVHelper prepares and holds pointers to parsed command line arguments so that no allocations
  183. // need to be performed between the fork and exec.
  184. class ExecVHelper {
  185. public:
  186. // Store a placeholder for the binary name.
  187. ExecVHelper() : args_(1u, std::string()) {}
  188. void PrepareArgs(const std::string& bin) {
  189. CHECK(!args_.empty());
  190. CHECK(args_[0].empty());
  191. args_[0] = bin;
  192. // Write char* into array.
  193. for (const std::string& arg : args_) {
  194. argv_.push_back(arg.c_str());
  195. }
  196. argv_.push_back(nullptr); // Add null terminator.
  197. }
  198. [[ noreturn ]]
  199. void Exec(int exit_code) {
  200. execv(argv_[0], (char * const *)&argv_[0]);
  201. PLOG(ERROR) << "execv(" << argv_[0] << ") failed";
  202. exit(exit_code);
  203. }
  204. // Add an arg if it's not empty.
  205. void AddArg(const std::string& arg) {
  206. if (!arg.empty()) {
  207. args_.push_back(arg);
  208. }
  209. }
  210. // Add a runtime arg if it's not empty.
  211. void AddRuntimeArg(const std::string& arg) {
  212. if (!arg.empty()) {
  213. args_.push_back("--runtime-arg");
  214. args_.push_back(arg);
  215. }
  216. }
  217. protected:
  218. // Holder arrays for backing arg storage.
  219. std::vector<std::string> args_;
  220. // Argument poiners.
  221. std::vector<const char*> argv_;
  222. };
  223. static std::string MapPropertyToArg(const std::string& property,
  224. const std::string& format,
  225. const std::string& default_value = "") {
  226. std::string prop = GetProperty(property, default_value);
  227. if (!prop.empty()) {
  228. return StringPrintf(format.c_str(), prop.c_str());
  229. }
  230. return "";
  231. }
  232. // Determines which binary we should use for execution (the debug or non-debug version).
  233. // e.g. dex2oatd vs dex2oat
  234. static const char* select_execution_binary(const char* binary, const char* debug_binary,
  235. bool background_job_compile) {
  236. return select_execution_binary(
  237. binary,
  238. debug_binary,
  239. background_job_compile,
  240. is_debug_runtime(),
  241. (android::base::GetProperty("ro.build.version.codename", "") == "REL"),
  242. is_debuggable_build());
  243. }
  244. // Determines which binary we should use for execution (the debug or non-debug version).
  245. // e.g. dex2oatd vs dex2oat
  246. // This is convenient method which is much easier to test because it doesn't read
  247. // system properties.
  248. const char* select_execution_binary(
  249. const char* binary,
  250. const char* debug_binary,
  251. bool background_job_compile,
  252. bool is_debug_runtime,
  253. bool is_release,
  254. bool is_debuggable_build) {
  255. // Do not use debug binaries for release candidates (to give more soak time).
  256. bool is_debug_bg_job = background_job_compile && is_debuggable_build && !is_release;
  257. // If the runtime was requested to use libartd.so, we'll run the debug version - assuming
  258. // the file is present (it may not be on images with very little space available).
  259. bool useDebug = (is_debug_runtime || is_debug_bg_job) && (access(debug_binary, X_OK) == 0);
  260. return useDebug ? debug_binary : binary;
  261. }
  262. // Namespace for Android Runtime flags applied during boot time.
  263. static const char* RUNTIME_NATIVE_BOOT_NAMESPACE = "runtime_native_boot";
  264. // Feature flag name for running the JIT in Zygote experiment, b/119800099.
  265. static const char* ENABLE_APEX_IMAGE = "enable_apex_image";
  266. // Location of the apex image.
  267. static const char* kApexImage = "/system/framework/apex.art";
  268. class RunDex2Oat : public ExecVHelper {
  269. public:
  270. RunDex2Oat(int zip_fd,
  271. int oat_fd,
  272. int input_vdex_fd,
  273. int output_vdex_fd,
  274. int image_fd,
  275. const char* input_file_name,
  276. const char* output_file_name,
  277. int swap_fd,
  278. const char* instruction_set,
  279. const char* compiler_filter,
  280. bool debuggable,
  281. bool post_bootcomplete,
  282. bool background_job_compile,
  283. int profile_fd,
  284. const char* class_loader_context,
  285. const std::string& class_loader_context_fds,
  286. int target_sdk_version,
  287. bool enable_hidden_api_checks,
  288. bool generate_compact_dex,
  289. int dex_metadata_fd,
  290. const char* compilation_reason) {
  291. // Get the relative path to the input file.
  292. const char* relative_input_file_name = get_location_from_path(input_file_name);
  293. std::string dex2oat_Xms_arg = MapPropertyToArg("dalvik.vm.dex2oat-Xms", "-Xms%s");
  294. std::string dex2oat_Xmx_arg = MapPropertyToArg("dalvik.vm.dex2oat-Xmx", "-Xmx%s");
  295. const char* threads_property = post_bootcomplete
  296. ? "dalvik.vm.dex2oat-threads"
  297. : "dalvik.vm.boot-dex2oat-threads";
  298. std::string dex2oat_threads_arg = MapPropertyToArg(threads_property, "-j%s");
  299. std::string bootclasspath;
  300. char* dex2oat_bootclasspath = getenv("DEX2OATBOOTCLASSPATH");
  301. if (dex2oat_bootclasspath != nullptr) {
  302. bootclasspath = StringPrintf("-Xbootclasspath:%s", dex2oat_bootclasspath);
  303. }
  304. // If DEX2OATBOOTCLASSPATH is not in the environment, dex2oat is going to query
  305. // BOOTCLASSPATH.
  306. const std::string dex2oat_isa_features_key =
  307. StringPrintf("dalvik.vm.isa.%s.features", instruction_set);
  308. std::string instruction_set_features_arg =
  309. MapPropertyToArg(dex2oat_isa_features_key, "--instruction-set-features=%s");
  310. const std::string dex2oat_isa_variant_key =
  311. StringPrintf("dalvik.vm.isa.%s.variant", instruction_set);
  312. std::string instruction_set_variant_arg =
  313. MapPropertyToArg(dex2oat_isa_variant_key, "--instruction-set-variant=%s");
  314. const char* dex2oat_norelocation = "-Xnorelocate";
  315. const std::string dex2oat_flags = GetProperty("dalvik.vm.dex2oat-flags", "");
  316. std::vector<std::string> dex2oat_flags_args = SplitBySpaces(dex2oat_flags);
  317. ALOGV("dalvik.vm.dex2oat-flags=%s\n", dex2oat_flags.c_str());
  318. // If we are booting without the real /data, don't spend time compiling.
  319. std::string vold_decrypt = GetProperty("vold.decrypt", "");
  320. bool skip_compilation = vold_decrypt == "trigger_restart_min_framework" ||
  321. vold_decrypt == "1";
  322. std::string resolve_startup_string_arg =
  323. MapPropertyToArg("persist.device_config.runtime.dex2oat_resolve_startup_strings",
  324. "--resolve-startup-const-strings=%s");
  325. if (resolve_startup_string_arg.empty()) {
  326. // If empty, fall back to system property.
  327. resolve_startup_string_arg =
  328. MapPropertyToArg("dalvik.vm.dex2oat-resolve-startup-strings",
  329. "--resolve-startup-const-strings=%s");
  330. }
  331. const std::string image_block_size_arg =
  332. MapPropertyToArg("dalvik.vm.dex2oat-max-image-block-size",
  333. "--max-image-block-size=%s");
  334. const bool generate_debug_info = GetBoolProperty("debug.generate-debug-info", false);
  335. std::string image_format_arg;
  336. if (image_fd >= 0) {
  337. image_format_arg = MapPropertyToArg("dalvik.vm.appimageformat", "--image-format=%s");
  338. }
  339. std::string dex2oat_large_app_threshold_arg =
  340. MapPropertyToArg("dalvik.vm.dex2oat-very-large", "--very-large-app-threshold=%s");
  341. const char* dex2oat_bin = select_execution_binary(
  342. kDex2oatPath, kDex2oatDebugPath, background_job_compile);
  343. bool generate_minidebug_info = kEnableMinidebugInfo &&
  344. GetBoolProperty(kMinidebugInfoSystemProperty, kMinidebugInfoSystemPropertyDefault);
  345. std::string boot_image;
  346. std::string use_apex_image =
  347. server_configurable_flags::GetServerConfigurableFlag(RUNTIME_NATIVE_BOOT_NAMESPACE,
  348. ENABLE_APEX_IMAGE,
  349. /*default_value=*/ "");
  350. if (use_apex_image == "true") {
  351. boot_image = StringPrintf("-Ximage:%s", kApexImage);
  352. } else {
  353. boot_image = MapPropertyToArg("dalvik.vm.boot-image", "-Ximage:%s");
  354. }
  355. // clang FORTIFY doesn't let us use strlen in constant array bounds, so we
  356. // use arraysize instead.
  357. std::string zip_fd_arg = StringPrintf("--zip-fd=%d", zip_fd);
  358. std::string zip_location_arg = StringPrintf("--zip-location=%s", relative_input_file_name);
  359. std::string input_vdex_fd_arg = StringPrintf("--input-vdex-fd=%d", input_vdex_fd);
  360. std::string output_vdex_fd_arg = StringPrintf("--output-vdex-fd=%d", output_vdex_fd);
  361. std::string oat_fd_arg = StringPrintf("--oat-fd=%d", oat_fd);
  362. std::string oat_location_arg = StringPrintf("--oat-location=%s", output_file_name);
  363. std::string instruction_set_arg = StringPrintf("--instruction-set=%s", instruction_set);
  364. std::string dex2oat_compiler_filter_arg;
  365. std::string dex2oat_swap_fd;
  366. std::string dex2oat_image_fd;
  367. std::string target_sdk_version_arg;
  368. if (target_sdk_version != 0) {
  369. target_sdk_version_arg = StringPrintf("-Xtarget-sdk-version:%d", target_sdk_version);
  370. }
  371. std::string class_loader_context_arg;
  372. std::string class_loader_context_fds_arg;
  373. if (class_loader_context != nullptr) {
  374. class_loader_context_arg = StringPrintf("--class-loader-context=%s",
  375. class_loader_context);
  376. if (!class_loader_context_fds.empty()) {
  377. class_loader_context_fds_arg = StringPrintf("--class-loader-context-fds=%s",
  378. class_loader_context_fds.c_str());
  379. }
  380. }
  381. if (swap_fd >= 0) {
  382. dex2oat_swap_fd = StringPrintf("--swap-fd=%d", swap_fd);
  383. }
  384. if (image_fd >= 0) {
  385. dex2oat_image_fd = StringPrintf("--app-image-fd=%d", image_fd);
  386. }
  387. // Compute compiler filter.
  388. bool have_dex2oat_relocation_skip_flag = false;
  389. if (skip_compilation) {
  390. dex2oat_compiler_filter_arg = "--compiler-filter=extract";
  391. have_dex2oat_relocation_skip_flag = true;
  392. } else if (compiler_filter != nullptr) {
  393. dex2oat_compiler_filter_arg = StringPrintf("--compiler-filter=%s", compiler_filter);
  394. }
  395. if (dex2oat_compiler_filter_arg.empty()) {
  396. dex2oat_compiler_filter_arg = MapPropertyToArg("dalvik.vm.dex2oat-filter",
  397. "--compiler-filter=%s");
  398. }
  399. // Check whether all apps should be compiled debuggable.
  400. if (!debuggable) {
  401. debuggable = GetProperty("dalvik.vm.always_debuggable", "") == "1";
  402. }
  403. std::string profile_arg;
  404. if (profile_fd != -1) {
  405. profile_arg = StringPrintf("--profile-file-fd=%d", profile_fd);
  406. }
  407. // Get the directory of the apk to pass as a base classpath directory.
  408. std::string base_dir;
  409. std::string apk_dir(input_file_name);
  410. unsigned long dir_index = apk_dir.rfind('/');
  411. bool has_base_dir = dir_index != std::string::npos;
  412. if (has_base_dir) {
  413. apk_dir = apk_dir.substr(0, dir_index);
  414. base_dir = StringPrintf("--classpath-dir=%s", apk_dir.c_str());
  415. }
  416. std::string dex_metadata_fd_arg = "--dm-fd=" + std::to_string(dex_metadata_fd);
  417. std::string compilation_reason_arg = compilation_reason == nullptr
  418. ? ""
  419. : std::string("--compilation-reason=") + compilation_reason;
  420. ALOGV("Running %s in=%s out=%s\n", dex2oat_bin, relative_input_file_name, output_file_name);
  421. // Disable cdex if update input vdex is true since this combination of options is not
  422. // supported.
  423. const bool disable_cdex = !generate_compact_dex || (input_vdex_fd == output_vdex_fd);
  424. AddArg(zip_fd_arg);
  425. AddArg(zip_location_arg);
  426. AddArg(input_vdex_fd_arg);
  427. AddArg(output_vdex_fd_arg);
  428. AddArg(oat_fd_arg);
  429. AddArg(oat_location_arg);
  430. AddArg(instruction_set_arg);
  431. AddArg(instruction_set_variant_arg);
  432. AddArg(instruction_set_features_arg);
  433. AddRuntimeArg(boot_image);
  434. AddRuntimeArg(bootclasspath);
  435. AddRuntimeArg(dex2oat_Xms_arg);
  436. AddRuntimeArg(dex2oat_Xmx_arg);
  437. AddArg(resolve_startup_string_arg);
  438. AddArg(image_block_size_arg);
  439. AddArg(dex2oat_compiler_filter_arg);
  440. AddArg(dex2oat_threads_arg);
  441. AddArg(dex2oat_swap_fd);
  442. AddArg(dex2oat_image_fd);
  443. if (generate_debug_info) {
  444. AddArg("--generate-debug-info");
  445. }
  446. if (debuggable) {
  447. AddArg("--debuggable");
  448. }
  449. AddArg(image_format_arg);
  450. AddArg(dex2oat_large_app_threshold_arg);
  451. if (have_dex2oat_relocation_skip_flag) {
  452. AddRuntimeArg(dex2oat_norelocation);
  453. }
  454. AddArg(profile_arg);
  455. AddArg(base_dir);
  456. AddArg(class_loader_context_arg);
  457. AddArg(class_loader_context_fds_arg);
  458. if (generate_minidebug_info) {
  459. AddArg(kMinidebugDex2oatFlag);
  460. }
  461. if (disable_cdex) {
  462. AddArg(kDisableCompactDexFlag);
  463. }
  464. AddRuntimeArg(target_sdk_version_arg);
  465. if (enable_hidden_api_checks) {
  466. AddRuntimeArg("-Xhidden-api-policy:enabled");
  467. }
  468. if (dex_metadata_fd > -1) {
  469. AddArg(dex_metadata_fd_arg);
  470. }
  471. AddArg(compilation_reason_arg);
  472. // Do not add args after dex2oat_flags, they should override others for debugging.
  473. args_.insert(args_.end(), dex2oat_flags_args.begin(), dex2oat_flags_args.end());
  474. PrepareArgs(dex2oat_bin);
  475. }
  476. };
  477. /*
  478. * Whether dexopt should use a swap file when compiling an APK.
  479. *
  480. * If kAlwaysProvideSwapFile, do this on all devices (dex2oat will make a more informed decision
  481. * itself, anyways).
  482. *
  483. * Otherwise, read "dalvik.vm.dex2oat-swap". If the property exists, return whether it is "true".
  484. *
  485. * Otherwise, return true if this is a low-mem device.
  486. *
  487. * Otherwise, return default value.
  488. */
  489. static bool kAlwaysProvideSwapFile = false;
  490. static bool kDefaultProvideSwapFile = true;
  491. static bool ShouldUseSwapFileForDexopt() {
  492. if (kAlwaysProvideSwapFile) {
  493. return true;
  494. }
  495. // Check the "override" property. If it exists, return value == "true".
  496. std::string dex2oat_prop_buf = GetProperty("dalvik.vm.dex2oat-swap", "");
  497. if (!dex2oat_prop_buf.empty()) {
  498. return dex2oat_prop_buf == "true";
  499. }
  500. // Shortcut for default value. This is an implementation optimization for the process sketched
  501. // above. If the default value is true, we can avoid to check whether this is a low-mem device,
  502. // as low-mem is never returning false. The compiler will optimize this away if it can.
  503. if (kDefaultProvideSwapFile) {
  504. return true;
  505. }
  506. if (GetBoolProperty("ro.config.low_ram", false)) {
  507. return true;
  508. }
  509. // Default value must be false here.
  510. return kDefaultProvideSwapFile;
  511. }
  512. static void SetDex2OatScheduling(bool set_to_bg) {
  513. if (set_to_bg) {
  514. if (set_sched_policy(0, SP_BACKGROUND) < 0) {
  515. PLOG(ERROR) << "set_sched_policy failed";
  516. exit(DexoptReturnCodes::kSetSchedPolicy);
  517. }
  518. if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
  519. PLOG(ERROR) << "setpriority failed";
  520. exit(DexoptReturnCodes::kSetPriority);
  521. }
  522. }
  523. }
  524. static unique_fd create_profile(uid_t uid, const std::string& profile, int32_t flags) {
  525. unique_fd fd(TEMP_FAILURE_RETRY(open(profile.c_str(), flags, 0600)));
  526. if (fd.get() < 0) {
  527. if (errno != EEXIST) {
  528. PLOG(ERROR) << "Failed to create profile " << profile;
  529. return invalid_unique_fd();
  530. }
  531. }
  532. // Profiles should belong to the app; make sure of that by giving ownership to
  533. // the app uid. If we cannot do that, there's no point in returning the fd
  534. // since dex2oat/profman will fail with SElinux denials.
  535. if (fchown(fd.get(), uid, uid) < 0) {
  536. PLOG(ERROR) << "Could not chown profile " << profile;
  537. return invalid_unique_fd();
  538. }
  539. return fd;
  540. }
  541. static unique_fd open_profile(uid_t uid, const std::string& profile, int32_t flags) {
  542. // Do not follow symlinks when opening a profile:
  543. // - primary profiles should not contain symlinks in their paths
  544. // - secondary dex paths should have been already resolved and validated
  545. flags |= O_NOFOLLOW;
  546. // Check if we need to create the profile
  547. // Reference profiles and snapshots are created on the fly; so they might not exist beforehand.
  548. unique_fd fd;
  549. if ((flags & O_CREAT) != 0) {
  550. fd = create_profile(uid, profile, flags);
  551. } else {
  552. fd.reset(TEMP_FAILURE_RETRY(open(profile.c_str(), flags)));
  553. }
  554. if (fd.get() < 0) {
  555. if (errno != ENOENT) {
  556. // Profiles might be missing for various reasons. For example, in a
  557. // multi-user environment, the profile directory for one user can be created
  558. // after we start a merge. In this case the current profile for that user
  559. // will not be found.
  560. // Also, the secondary dex profiles might be deleted by the app at any time,
  561. // so we can't we need to prepare if they are missing.
  562. PLOG(ERROR) << "Failed to open profile " << profile;
  563. }
  564. return invalid_unique_fd();
  565. }
  566. return fd;
  567. }
  568. static unique_fd open_current_profile(uid_t uid, userid_t user, const std::string& package_name,
  569. const std::string& location, bool is_secondary_dex) {
  570. std::string profile = create_current_profile_path(user, package_name, location,
  571. is_secondary_dex);
  572. return open_profile(uid, profile, O_RDONLY);
  573. }
  574. static unique_fd open_reference_profile(uid_t uid, const std::string& package_name,
  575. const std::string& location, bool read_write, bool is_secondary_dex) {
  576. std::string profile = create_reference_profile_path(package_name, location, is_secondary_dex);
  577. return open_profile(uid, profile, read_write ? (O_CREAT | O_RDWR) : O_RDONLY);
  578. }
  579. static unique_fd open_spnashot_profile(uid_t uid, const std::string& package_name,
  580. const std::string& location) {
  581. std::string profile = create_snapshot_profile_path(package_name, location);
  582. return open_profile(uid, profile, O_CREAT | O_RDWR | O_TRUNC);
  583. }
  584. static void open_profile_files(uid_t uid, const std::string& package_name,
  585. const std::string& location, bool is_secondary_dex,
  586. /*out*/ std::vector<unique_fd>* profiles_fd, /*out*/ unique_fd* reference_profile_fd) {
  587. // Open the reference profile in read-write mode as profman might need to save the merge.
  588. *reference_profile_fd = open_reference_profile(uid, package_name, location,
  589. /*read_write*/ true, is_secondary_dex);
  590. // For secondary dex files, we don't really need the user but we use it for sanity checks.
  591. // Note: the user owning the dex file should be the current user.
  592. std::vector<userid_t> users;
  593. if (is_secondary_dex){
  594. users.push_back(multiuser_get_user_id(uid));
  595. } else {
  596. users = get_known_users(/*volume_uuid*/ nullptr);
  597. }
  598. for (auto user : users) {
  599. unique_fd profile_fd = open_current_profile(uid, user, package_name, location,
  600. is_secondary_dex);
  601. // Add to the lists only if both fds are valid.
  602. if (profile_fd.get() >= 0) {
  603. profiles_fd->push_back(std::move(profile_fd));
  604. }
  605. }
  606. }
  607. static constexpr int PROFMAN_BIN_RETURN_CODE_COMPILE = 0;
  608. static constexpr int PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION = 1;
  609. static constexpr int PROFMAN_BIN_RETURN_CODE_BAD_PROFILES = 2;
  610. static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_IO = 3;
  611. static constexpr int PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING = 4;
  612. class RunProfman : public ExecVHelper {
  613. public:
  614. void SetupArgs(const std::vector<unique_fd>& profile_fds,
  615. const unique_fd& reference_profile_fd,
  616. const std::vector<unique_fd>& apk_fds,
  617. const std::vector<std::string>& dex_locations,
  618. bool copy_and_update,
  619. bool store_aggregation_counters) {
  620. // TODO(calin): Assume for now we run in the bg compile job (which is in
  621. // most of the invocation). With the current data flow, is not very easy or
  622. // clean to discover this in RunProfman (it will require quite a messy refactoring).
  623. const char* profman_bin = select_execution_binary(
  624. kProfmanPath, kProfmanDebugPath, /*background_job_compile=*/ true);
  625. if (copy_and_update) {
  626. CHECK_EQ(1u, profile_fds.size());
  627. CHECK_EQ(1u, apk_fds.size());
  628. }
  629. if (reference_profile_fd != -1) {
  630. AddArg("--reference-profile-file-fd=" + std::to_string(reference_profile_fd.get()));
  631. }
  632. for (const unique_fd& fd : profile_fds) {
  633. AddArg("--profile-file-fd=" + std::to_string(fd.get()));
  634. }
  635. for (const unique_fd& fd : apk_fds) {
  636. AddArg("--apk-fd=" + std::to_string(fd.get()));
  637. }
  638. for (const std::string& dex_location : dex_locations) {
  639. AddArg("--dex-location=" + dex_location);
  640. }
  641. if (copy_and_update) {
  642. AddArg("--copy-and-update-profile-key");
  643. }
  644. if (store_aggregation_counters) {
  645. AddArg("--store-aggregation-counters");
  646. }
  647. // Do not add after dex2oat_flags, they should override others for debugging.
  648. PrepareArgs(profman_bin);
  649. }
  650. void SetupMerge(const std::vector<unique_fd>& profiles_fd,
  651. const unique_fd& reference_profile_fd,
  652. const std::vector<unique_fd>& apk_fds = std::vector<unique_fd>(),
  653. const std::vector<std::string>& dex_locations = std::vector<std::string>(),
  654. bool store_aggregation_counters = false) {
  655. SetupArgs(profiles_fd,
  656. reference_profile_fd,
  657. apk_fds,
  658. dex_locations,
  659. /*copy_and_update=*/false,
  660. store_aggregation_counters);
  661. }
  662. void SetupCopyAndUpdate(unique_fd&& profile_fd,
  663. unique_fd&& reference_profile_fd,
  664. unique_fd&& apk_fd,
  665. const std::string& dex_location) {
  666. // The fds need to stay open longer than the scope of the function, so put them into a local
  667. // variable vector.
  668. profiles_fd_.push_back(std::move(profile_fd));
  669. apk_fds_.push_back(std::move(apk_fd));
  670. reference_profile_fd_ = std::move(reference_profile_fd);
  671. std::vector<std::string> dex_locations = {dex_location};
  672. SetupArgs(profiles_fd_,
  673. reference_profile_fd_,
  674. apk_fds_,
  675. dex_locations,
  676. /*copy_and_update=*/true,
  677. /*store_aggregation_counters=*/false);
  678. }
  679. void SetupDump(const std::vector<unique_fd>& profiles_fd,
  680. const unique_fd& reference_profile_fd,
  681. const std::vector<std::string>& dex_locations,
  682. const std::vector<unique_fd>& apk_fds,
  683. const unique_fd& output_fd) {
  684. AddArg("--dump-only");
  685. AddArg(StringPrintf("--dump-output-to-fd=%d", output_fd.get()));
  686. SetupArgs(profiles_fd,
  687. reference_profile_fd,
  688. apk_fds,
  689. dex_locations,
  690. /*copy_and_update=*/false,
  691. /*store_aggregation_counters=*/false);
  692. }
  693. void Exec() {
  694. ExecVHelper::Exec(DexoptReturnCodes::kProfmanExec);
  695. }
  696. private:
  697. unique_fd reference_profile_fd_;
  698. std::vector<unique_fd> profiles_fd_;
  699. std::vector<unique_fd> apk_fds_;
  700. };
  701. // Decides if profile guided compilation is needed or not based on existing profiles.
  702. // The location is the package name for primary apks or the dex path for secondary dex files.
  703. // Returns true if there is enough information in the current profiles that makes it
  704. // worth to recompile the given location.
  705. // If the return value is true all the current profiles would have been merged into
  706. // the reference profiles accessible with open_reference_profile().
  707. static bool analyze_profiles(uid_t uid, const std::string& package_name,
  708. const std::string& location, bool is_secondary_dex) {
  709. std::vector<unique_fd> profiles_fd;
  710. unique_fd reference_profile_fd;
  711. open_profile_files(uid, package_name, location, is_secondary_dex,
  712. &profiles_fd, &reference_profile_fd);
  713. if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
  714. // Skip profile guided compilation because no profiles were found.
  715. // Or if the reference profile info couldn't be opened.
  716. return false;
  717. }
  718. RunProfman profman_merge;
  719. profman_merge.SetupMerge(profiles_fd, reference_profile_fd);
  720. pid_t pid = fork();
  721. if (pid == 0) {
  722. /* child -- drop privileges before continuing */
  723. drop_capabilities(uid);
  724. profman_merge.Exec();
  725. }
  726. /* parent */
  727. int return_code = wait_child(pid);
  728. bool need_to_compile = false;
  729. bool should_clear_current_profiles = false;
  730. bool should_clear_reference_profile = false;
  731. if (!WIFEXITED(return_code)) {
  732. LOG(WARNING) << "profman failed for location " << location << ": " << return_code;
  733. } else {
  734. return_code = WEXITSTATUS(return_code);
  735. switch (return_code) {
  736. case PROFMAN_BIN_RETURN_CODE_COMPILE:
  737. need_to_compile = true;
  738. should_clear_current_profiles = true;
  739. should_clear_reference_profile = false;
  740. break;
  741. case PROFMAN_BIN_RETURN_CODE_SKIP_COMPILATION:
  742. need_to_compile = false;
  743. should_clear_current_profiles = false;
  744. should_clear_reference_profile = false;
  745. break;
  746. case PROFMAN_BIN_RETURN_CODE_BAD_PROFILES:
  747. LOG(WARNING) << "Bad profiles for location " << location;
  748. need_to_compile = false;
  749. should_clear_current_profiles = true;
  750. should_clear_reference_profile = true;
  751. break;
  752. case PROFMAN_BIN_RETURN_CODE_ERROR_IO: // fall-through
  753. case PROFMAN_BIN_RETURN_CODE_ERROR_LOCKING:
  754. // Temporary IO problem (e.g. locking). Ignore but log a warning.
  755. LOG(WARNING) << "IO error while reading profiles for location " << location;
  756. need_to_compile = false;
  757. should_clear_current_profiles = false;
  758. should_clear_reference_profile = false;
  759. break;
  760. default:
  761. // Unknown return code or error. Unlink profiles.
  762. LOG(WARNING) << "Unknown error code while processing profiles for location "
  763. << location << ": " << return_code;
  764. need_to_compile = false;
  765. should_clear_current_profiles = true;
  766. should_clear_reference_profile = true;
  767. break;
  768. }
  769. }
  770. if (should_clear_current_profiles) {
  771. if (is_secondary_dex) {
  772. // For secondary dex files, the owning user is the current user.
  773. clear_current_profile(package_name, location, multiuser_get_user_id(uid),
  774. is_secondary_dex);
  775. } else {
  776. clear_primary_current_profiles(package_name, location);
  777. }
  778. }
  779. if (should_clear_reference_profile) {
  780. clear_reference_profile(package_name, location, is_secondary_dex);
  781. }
  782. return need_to_compile;
  783. }
  784. // Decides if profile guided compilation is needed or not based on existing profiles.
  785. // The analysis is done for the primary apks of the given package.
  786. // Returns true if there is enough information in the current profiles that makes it
  787. // worth to recompile the package.
  788. // If the return value is true all the current profiles would have been merged into
  789. // the reference profiles accessible with open_reference_profile().
  790. bool analyze_primary_profiles(uid_t uid, const std::string& package_name,
  791. const std::string& profile_name) {
  792. return analyze_profiles(uid, package_name, profile_name, /*is_secondary_dex*/false);
  793. }
  794. bool dump_profiles(int32_t uid, const std::string& pkgname, const std::string& profile_name,
  795. const std::string& code_path) {
  796. std::vector<unique_fd> profile_fds;
  797. unique_fd reference_profile_fd;
  798. std::string out_file_name = StringPrintf("/data/misc/profman/%s-%s.txt",
  799. pkgname.c_str(), profile_name.c_str());
  800. open_profile_files(uid, pkgname, profile_name, /*is_secondary_dex*/false,
  801. &profile_fds, &reference_profile_fd);
  802. const bool has_reference_profile = (reference_profile_fd.get() != -1);
  803. const bool has_profiles = !profile_fds.empty();
  804. if (!has_reference_profile && !has_profiles) {
  805. LOG(ERROR) << "profman dump: no profiles to dump for " << pkgname;
  806. return false;
  807. }
  808. unique_fd output_fd(open(out_file_name.c_str(),
  809. O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0644));
  810. if (fchmod(output_fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0) {
  811. LOG(ERROR) << "installd cannot chmod file for dump_profile" << out_file_name;
  812. return false;
  813. }
  814. std::vector<std::string> dex_locations;
  815. std::vector<unique_fd> apk_fds;
  816. unique_fd apk_fd(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW));
  817. if (apk_fd == -1) {
  818. PLOG(ERROR) << "installd cannot open " << code_path.c_str();
  819. return false;
  820. }
  821. dex_locations.push_back(get_location_from_path(code_path.c_str()));
  822. apk_fds.push_back(std::move(apk_fd));
  823. RunProfman profman_dump;
  824. profman_dump.SetupDump(profile_fds, reference_profile_fd, dex_locations, apk_fds, output_fd);
  825. pid_t pid = fork();
  826. if (pid == 0) {
  827. /* child -- drop privileges before continuing */
  828. drop_capabilities(uid);
  829. profman_dump.Exec();
  830. }
  831. /* parent */
  832. int return_code = wait_child(pid);
  833. if (!WIFEXITED(return_code)) {
  834. LOG(WARNING) << "profman failed for package " << pkgname << ": "
  835. << return_code;
  836. return false;
  837. }
  838. return true;
  839. }
  840. bool copy_system_profile(const std::string& system_profile,
  841. uid_t packageUid, const std::string& package_name, const std::string& profile_name) {
  842. unique_fd in_fd(open(system_profile.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC));
  843. unique_fd out_fd(open_reference_profile(packageUid,
  844. package_name,
  845. profile_name,
  846. /*read_write*/ true,
  847. /*secondary*/ false));
  848. if (in_fd.get() < 0) {
  849. PLOG(WARNING) << "Could not open profile " << system_profile;
  850. return false;
  851. }
  852. if (out_fd.get() < 0) {
  853. PLOG(WARNING) << "Could not open profile " << package_name;
  854. return false;
  855. }
  856. // As a security measure we want to write the profile information with the reduced capabilities
  857. // of the package user id. So we fork and drop capabilities in the child.
  858. pid_t pid = fork();
  859. if (pid == 0) {
  860. /* child -- drop privileges before continuing */
  861. drop_capabilities(packageUid);
  862. if (flock(out_fd.get(), LOCK_EX | LOCK_NB) != 0) {
  863. if (errno != EWOULDBLOCK) {
  864. PLOG(WARNING) << "Error locking profile " << package_name;
  865. }
  866. // This implies that the app owning this profile is running
  867. // (and has acquired the lock).
  868. //
  869. // The app never acquires the lock for the reference profiles of primary apks.
  870. // Only dex2oat from installd will do that. Since installd is single threaded
  871. // we should not see this case. Nevertheless be prepared for it.
  872. PLOG(WARNING) << "Failed to flock " << package_name;
  873. return false;
  874. }
  875. bool truncated = ftruncate(out_fd.get(), 0) == 0;
  876. if (!truncated) {
  877. PLOG(WARNING) << "Could not truncate " << package_name;
  878. }
  879. // Copy over data.
  880. static constexpr size_t kBufferSize = 4 * 1024;
  881. char buffer[kBufferSize];
  882. while (true) {
  883. ssize_t bytes = read(in_fd.get(), buffer, kBufferSize);
  884. if (bytes == 0) {
  885. break;
  886. }
  887. write(out_fd.get(), buffer, bytes);
  888. }
  889. if (flock(out_fd.get(), LOCK_UN) != 0) {
  890. PLOG(WARNING) << "Error unlocking profile " << package_name;
  891. }
  892. // Use _exit since we don't want to run the global destructors in the child.
  893. // b/62597429
  894. _exit(0);
  895. }
  896. /* parent */
  897. int return_code = wait_child(pid);
  898. return return_code == 0;
  899. }
  900. static std::string replace_file_extension(const std::string& oat_path, const std::string& new_ext) {
  901. // A standard dalvik-cache entry. Replace ".dex" with `new_ext`.
  902. if (EndsWith(oat_path, ".dex")) {
  903. std::string new_path = oat_path;
  904. new_path.replace(new_path.length() - strlen(".dex"), strlen(".dex"), new_ext);
  905. CHECK(EndsWith(new_path, new_ext));
  906. return new_path;
  907. }
  908. // An odex entry. Not that this may not be an extension, e.g., in the OTA
  909. // case (where the base name will have an extension for the B artifact).
  910. size_t odex_pos = oat_path.rfind(".odex");
  911. if (odex_pos != std::string::npos) {
  912. std::string new_path = oat_path;
  913. new_path.replace(odex_pos, strlen(".odex"), new_ext);
  914. CHECK_NE(new_path.find(new_ext), std::string::npos);
  915. return new_path;
  916. }
  917. // Don't know how to handle this.
  918. return "";
  919. }
  920. // Translate the given oat path to an art (app image) path. An empty string
  921. // denotes an error.
  922. static std::string create_image_filename(const std::string& oat_path) {
  923. return replace_file_extension(oat_path, ".art");
  924. }
  925. // Translate the given oat path to a vdex path. An empty string denotes an error.
  926. static std::string create_vdex_filename(const std::string& oat_path) {
  927. return replace_file_extension(oat_path, ".vdex");
  928. }
  929. static int open_output_file(const char* file_name, bool recreate, int permissions) {
  930. int flags = O_RDWR | O_CREAT;
  931. if (recreate) {
  932. if (unlink(file_name) < 0) {
  933. if (errno != ENOENT) {
  934. PLOG(ERROR) << "open_output_file: Couldn't unlink " << file_name;
  935. }
  936. }
  937. flags |= O_EXCL;
  938. }
  939. return open(file_name, flags, permissions);
  940. }
  941. static bool set_permissions_and_ownership(
  942. int fd, bool is_public, int uid, const char* path, bool is_secondary_dex) {
  943. // Primary apks are owned by the system. Secondary dex files are owned by the app.
  944. int owning_uid = is_secondary_dex ? uid : AID_SYSTEM;
  945. if (fchmod(fd,
  946. S_IRUSR|S_IWUSR|S_IRGRP |
  947. (is_public ? S_IROTH : 0)) < 0) {
  948. ALOGE("installd cannot chmod '%s' during dexopt\n", path);
  949. return false;
  950. } else if (fchown(fd, owning_uid, uid) < 0) {
  951. ALOGE("installd cannot chown '%s' during dexopt\n", path);
  952. return false;
  953. }
  954. return true;
  955. }
  956. static bool IsOutputDalvikCache(const char* oat_dir) {
  957. // InstallerConnection.java (which invokes installd) transforms Java null arguments
  958. // into '!'. Play it safe by handling it both.
  959. // TODO: ensure we never get null.
  960. // TODO: pass a flag instead of inferring if the output is dalvik cache.
  961. return oat_dir == nullptr || oat_dir[0] == '!';
  962. }
  963. // Best-effort check whether we can fit the the path into our buffers.
  964. // Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
  965. // without a swap file, if necessary. Reference profiles file also add an extra ".prof"
  966. // extension to the cache path (5 bytes).
  967. // TODO(calin): move away from char* buffers and PKG_PATH_MAX.
  968. static bool validate_dex_path_size(const std::string& dex_path) {
  969. if (dex_path.size() >= (PKG_PATH_MAX - 8)) {
  970. LOG(ERROR) << "dex_path too long: " << dex_path;
  971. return false;
  972. }
  973. return true;
  974. }
  975. static bool create_oat_out_path(const char* apk_path, const char* instruction_set,
  976. const char* oat_dir, bool is_secondary_dex, /*out*/ char* out_oat_path) {
  977. if (!validate_dex_path_size(apk_path)) {
  978. return false;
  979. }
  980. if (!IsOutputDalvikCache(oat_dir)) {
  981. // Oat dirs for secondary dex files are already validated.
  982. if (!is_secondary_dex && validate_apk_path(oat_dir)) {
  983. ALOGE("cannot validate apk path with oat_dir '%s'\n", oat_dir);
  984. return false;
  985. }
  986. if (!calculate_oat_file_path(out_oat_path, oat_dir, apk_path, instruction_set)) {
  987. return false;
  988. }
  989. } else {
  990. if (!create_cache_path(out_oat_path, apk_path, instruction_set)) {
  991. return false;
  992. }
  993. }
  994. return true;
  995. }
  996. // Helper for fd management. This is similar to a unique_fd in that it closes the file descriptor
  997. // on destruction. It will also run the given cleanup (unless told not to) after closing.
  998. //
  999. // Usage example:
  1000. //
  1001. // Dex2oatFileWrapper file(open(...),
  1002. // [name]() {
  1003. // unlink(name.c_str());
  1004. // });
  1005. // // Note: care needs to be taken about name, as it needs to have a lifetime longer than the
  1006. // wrapper if captured as a reference.
  1007. //
  1008. // if (file.get() == -1) {
  1009. // // Error opening...
  1010. // }
  1011. //
  1012. // ...
  1013. // if (error) {
  1014. // // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will run
  1015. // // and delete the file (after the fd is closed).
  1016. // return -1;
  1017. // }
  1018. //
  1019. // (Success case)
  1020. // file.SetCleanup(false);
  1021. // // At this point, when the Dex2oatFileWrapper is destructed, the cleanup function will not run
  1022. // // (leaving the file around; after the fd is closed).
  1023. //
  1024. class Dex2oatFileWrapper {
  1025. public:
  1026. Dex2oatFileWrapper() : value_(-1), cleanup_(), do_cleanup_(true), auto_close_(true) {
  1027. }
  1028. Dex2oatFileWrapper(int value, std::function<void ()> cleanup)
  1029. : value_(value), cleanup_(cleanup), do_cleanup_(true), auto_close_(true) {}
  1030. Dex2oatFileWrapper(Dex2oatFileWrapper&& other) {
  1031. value_ = other.value_;
  1032. cleanup_ = other.cleanup_;
  1033. do_cleanup_ = other.do_cleanup_;
  1034. auto_close_ = other.auto_close_;
  1035. other.release();
  1036. }
  1037. Dex2oatFileWrapper& operator=(Dex2oatFileWrapper&& other) {
  1038. value_ = other.value_;
  1039. cleanup_ = other.cleanup_;
  1040. do_cleanup_ = other.do_cleanup_;
  1041. auto_close_ = other.auto_close_;
  1042. other.release();
  1043. return *this;
  1044. }
  1045. ~Dex2oatFileWrapper() {
  1046. reset(-1);
  1047. }
  1048. int get() {
  1049. return value_;
  1050. }
  1051. void SetCleanup(bool cleanup) {
  1052. do_cleanup_ = cleanup;
  1053. }
  1054. void reset(int new_value) {
  1055. if (auto_close_ && value_ >= 0) {
  1056. close(value_);
  1057. }
  1058. if (do_cleanup_ && cleanup_ != nullptr) {
  1059. cleanup_();
  1060. }
  1061. value_ = new_value;
  1062. }
  1063. void reset(int new_value, std::function<void ()> new_cleanup) {
  1064. if (auto_close_ && value_ >= 0) {
  1065. close(value_);
  1066. }
  1067. if (do_cleanup_ && cleanup_ != nullptr) {
  1068. cleanup_();
  1069. }
  1070. value_ = new_value;
  1071. cleanup_ = new_cleanup;
  1072. }
  1073. void DisableAutoClose() {
  1074. auto_close_ = false;
  1075. }
  1076. private:
  1077. void release() {
  1078. value_ = -1;
  1079. do_cleanup_ = false;
  1080. cleanup_ = nullptr;
  1081. }
  1082. int value_;
  1083. std::function<void ()> cleanup_;
  1084. bool do_cleanup_;
  1085. bool auto_close_;
  1086. };
  1087. // (re)Creates the app image if needed.
  1088. Dex2oatFileWrapper maybe_open_app_image(const char* out_oat_path,
  1089. bool generate_app_image, bool is_public, int uid, bool is_secondary_dex) {
  1090. // We don't create an image for secondary dex files.
  1091. if (is_secondary_dex) {
  1092. return Dex2oatFileWrapper();
  1093. }
  1094. const std::string image_path = create_image_filename(out_oat_path);
  1095. if (image_path.empty()) {
  1096. // Happens when the out_oat_path has an unknown extension.
  1097. return Dex2oatFileWrapper();
  1098. }
  1099. // In case there is a stale image, remove it now. Ignore any error.
  1100. unlink(image_path.c_str());
  1101. // Not enabled, exit.
  1102. if (!generate_app_image) {
  1103. return Dex2oatFileWrapper();
  1104. }
  1105. std::string app_image_format = GetProperty("dalvik.vm.appimageformat", "");
  1106. if (app_image_format.empty()) {
  1107. return Dex2oatFileWrapper();
  1108. }
  1109. // Recreate is true since we do not want to modify a mapped image. If the app is
  1110. // already running and we modify the image file, it can cause crashes (b/27493510).
  1111. Dex2oatFileWrapper wrapper_fd(
  1112. open_output_file(image_path.c_str(), true /*recreate*/, 0600 /*permissions*/),
  1113. [image_path]() { unlink(image_path.c_str()); });
  1114. if (wrapper_fd.get() < 0) {
  1115. // Could not create application image file. Go on since we can compile without it.
  1116. LOG(ERROR) << "installd could not create '" << image_path
  1117. << "' for image file during dexopt";
  1118. // If we have a valid image file path but no image fd, explicitly erase the image file.
  1119. if (unlink(image_path.c_str()) < 0) {
  1120. if (errno != ENOENT) {
  1121. PLOG(ERROR) << "Couldn't unlink image file " << image_path;
  1122. }
  1123. }
  1124. } else if (!set_permissions_and_ownership(
  1125. wrapper_fd.get(), is_public, uid, image_path.c_str(), is_secondary_dex)) {
  1126. ALOGE("installd cannot set owner '%s' for image during dexopt\n", image_path.c_str());
  1127. wrapper_fd.reset(-1);
  1128. }
  1129. return wrapper_fd;
  1130. }
  1131. // Creates the dexopt swap file if necessary and return its fd.
  1132. // Returns -1 if there's no need for a swap or in case of errors.
  1133. unique_fd maybe_open_dexopt_swap_file(const char* out_oat_path) {
  1134. if (!ShouldUseSwapFileForDexopt()) {
  1135. return invalid_unique_fd();
  1136. }
  1137. auto swap_file_name = std::string(out_oat_path) + ".swap";
  1138. unique_fd swap_fd(open_output_file(
  1139. swap_file_name.c_str(), /*recreate*/true, /*permissions*/0600));
  1140. if (swap_fd.get() < 0) {
  1141. // Could not create swap file. Optimistically go on and hope that we can compile
  1142. // without it.
  1143. ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name.c_str());
  1144. } else {
  1145. // Immediately unlink. We don't really want to hit flash.
  1146. if (unlink(swap_file_name.c_str()) < 0) {
  1147. PLOG(ERROR) << "Couldn't unlink swap file " << swap_file_name;
  1148. }
  1149. }
  1150. return swap_fd;
  1151. }
  1152. // Opens the reference profiles if needed.
  1153. // Note that the reference profile might not exist so it's OK if the fd will be -1.
  1154. Dex2oatFileWrapper maybe_open_reference_profile(const std::string& pkgname,
  1155. const std::string& dex_path, const char* profile_name, bool profile_guided,
  1156. bool is_public, int uid, bool is_secondary_dex) {
  1157. // If we are not profile guided compilation, or we are compiling system server
  1158. // do not bother to open the profiles; we won't be using them.
  1159. if (!profile_guided || (pkgname[0] == '*')) {
  1160. return Dex2oatFileWrapper();
  1161. }
  1162. // If this is a secondary dex path which is public do not open the profile.
  1163. // We cannot compile public secondary dex paths with profiles. That's because
  1164. // it will expose how the dex files are used by their owner.
  1165. //
  1166. // Note that the PackageManager is responsible to set the is_public flag for
  1167. // primary apks and we do not check it here. In some cases, e.g. when
  1168. // compiling with a public profile from the .dm file the PackageManager will
  1169. // set is_public toghether with the profile guided compilation.
  1170. if (is_secondary_dex && is_public) {
  1171. return Dex2oatFileWrapper();
  1172. }
  1173. // Open reference profile in read only mode as dex2oat does not get write permissions.
  1174. std::string location;
  1175. if (is_secondary_dex) {
  1176. location = dex_path;
  1177. } else {
  1178. if (profile_name == nullptr) {
  1179. // This path is taken for system server re-compilation lunched from ZygoteInit.
  1180. return Dex2oatFileWrapper();
  1181. } else {
  1182. location = profile_name;
  1183. }
  1184. }
  1185. unique_fd ufd = open_reference_profile(uid, pkgname, location, /*read_write*/false,
  1186. is_secondary_dex);
  1187. const auto& cleanup = [pkgname, location, is_secondary_dex]() {
  1188. clear_reference_profile(pkgname, location, is_secondary_dex);
  1189. };
  1190. return Dex2oatFileWrapper(ufd.release(), cleanup);
  1191. }
  1192. // Opens the vdex files and assigns the input fd to in_vdex_wrapper_fd and the output fd to
  1193. // out_vdex_wrapper_fd. Returns true for success or false in case of errors.
  1194. bool open_vdex_files_for_dex2oat(const char* apk_path, const char* out_oat_path, int dexopt_needed,
  1195. const char* instruction_set, bool is_public, int uid, bool is_secondary_dex,
  1196. bool profile_guided, Dex2oatFileWrapper* in_vdex_wrapper_fd,
  1197. Dex2oatFileWrapper* out_vdex_wrapper_fd) {
  1198. CHECK(in_vdex_wrapper_fd != nullptr);
  1199. CHECK(out_vdex_wrapper_fd != nullptr);
  1200. // Open the existing VDEX. We do this before creating the new output VDEX, which will
  1201. // unlink the old one.
  1202. char in_odex_path[PKG_PATH_MAX];
  1203. int dexopt_action = abs(dexopt_needed);
  1204. bool is_odex_location = dexopt_needed < 0;
  1205. std::string in_vdex_path_str;
  1206. // Infer the name of the output VDEX.
  1207. const std::string out_vdex_path_str = create_vdex_filename(out_oat_path);
  1208. if (out_vdex_path_str.empty()) {
  1209. return false;
  1210. }
  1211. bool update_vdex_in_place = false;
  1212. if (dexopt_action != DEX2OAT_FROM_SCRATCH) {
  1213. // Open the possibly existing vdex. If none exist, we pass -1 to dex2oat for input-vdex-fd.
  1214. const char* path = nullptr;
  1215. if (is_odex_location) {
  1216. if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
  1217. path = in_odex_path;
  1218. } else {
  1219. ALOGE("installd cannot compute input vdex location for '%s'\n", apk_path);
  1220. return false;
  1221. }
  1222. } else {
  1223. path = out_oat_path;
  1224. }
  1225. in_vdex_path_str = create_vdex_filename(path);
  1226. if (in_vdex_path_str.empty()) {
  1227. ALOGE("installd cannot compute input vdex location for '%s'\n", path);
  1228. return false;
  1229. }
  1230. // We can update in place when all these conditions are met:
  1231. // 1) The vdex location to write to is the same as the vdex location to read (vdex files
  1232. // on /system typically cannot be updated in place).
  1233. // 2) We dex2oat due to boot image change, because we then know the existing vdex file
  1234. // cannot be currently used by a running process.
  1235. // 3) We are not doing a profile guided compilation, because dexlayout requires two
  1236. // different vdex files to operate.
  1237. update_vdex_in_place =
  1238. (in_vdex_path_str == out_vdex_path_str) &&
  1239. (dexopt_action == DEX2OAT_FOR_BOOT_IMAGE) &&
  1240. !profile_guided;
  1241. if (update_vdex_in_place) {
  1242. // Open the file read-write to be able to update it.
  1243. in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDWR, 0));
  1244. if (in_vdex_wrapper_fd->get() == -1) {
  1245. // If we failed to open the file, we cannot update it in place.
  1246. update_vdex_in_place = false;
  1247. }
  1248. } else {
  1249. in_vdex_wrapper_fd->reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
  1250. }
  1251. }
  1252. // If we are updating the vdex in place, we do not need to recreate a vdex,
  1253. // and can use the same existing one.
  1254. if (update_vdex_in_place) {
  1255. // We unlink the file in case the invocation of dex2oat fails, to ensure we don't
  1256. // have bogus stale vdex files.
  1257. out_vdex_wrapper_fd->reset(
  1258. in_vdex_wrapper_fd->get(),
  1259. [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
  1260. // Disable auto close for the in wrapper fd (it will be done when destructing the out
  1261. // wrapper).
  1262. in_vdex_wrapper_fd->DisableAutoClose();
  1263. } else {
  1264. out_vdex_wrapper_fd->reset(
  1265. open_output_file(out_vdex_path_str.c_str(), /*recreate*/true, /*permissions*/0644),
  1266. [out_vdex_path_str]() { unlink(out_vdex_path_str.c_str()); });
  1267. if (out_vdex_wrapper_fd->get() < 0) {
  1268. ALOGE("installd cannot open vdex'%s' during dexopt\n", out_vdex_path_str.c_str());
  1269. return false;
  1270. }
  1271. }
  1272. if (!set_permissions_and_ownership(out_vdex_wrapper_fd->get(), is_public, uid,
  1273. out_vdex_path_str.c_str(), is_secondary_dex)) {
  1274. ALOGE("installd cannot set owner '%s' for vdex during dexopt\n", out_vdex_path_str.c_str());
  1275. return false;
  1276. }
  1277. // If we got here we successfully opened the vdex files.
  1278. return true;
  1279. }
  1280. // Opens the output oat file for the given apk.
  1281. // If successful it stores the output path into out_oat_path and returns true.
  1282. Dex2oatFileWrapper open_oat_out_file(const char* apk_path, const char* oat_dir,
  1283. bool is_public, int uid, const char* instruction_set, bool is_secondary_dex,
  1284. char* out_oat_path) {
  1285. if (!create_oat_out_path(apk_path, instruction_set, oat_dir, is_secondary_dex, out_oat_path)) {
  1286. return Dex2oatFileWrapper();
  1287. }
  1288. const std::string out_oat_path_str(out_oat_path);
  1289. Dex2oatFileWrapper wrapper_fd(
  1290. open_output_file(out_oat_path, /*recreate*/true, /*permissions*/0644),
  1291. [out_oat_path_str]() { unlink(out_oat_path_str.c_str()); });
  1292. if (wrapper_fd.get() < 0) {
  1293. PLOG(ERROR) << "installd cannot open output during dexopt" << out_oat_path;
  1294. } else if (!set_permissions_and_ownership(
  1295. wrapper_fd.get(), is_public, uid, out_oat_path, is_secondary_dex)) {
  1296. ALOGE("installd cannot set owner '%s' for output during dexopt\n", out_oat_path);
  1297. wrapper_fd.reset(-1);
  1298. }
  1299. return wrapper_fd;
  1300. }
  1301. // Creates RDONLY fds for oat and vdex files, if exist.
  1302. // Returns false if it fails to create oat out path for the given apk path.
  1303. // Note that the method returns true even if the files could not be opened.
  1304. bool maybe_open_oat_and_vdex_file(const std::string& apk_path,
  1305. const std::string& oat_dir,
  1306. const std::string& instruction_set,
  1307. bool is_secondary_dex,
  1308. unique_fd* oat_file_fd,
  1309. unique_fd* vdex_file_fd) {
  1310. char oat_path[PKG_PATH_MAX];
  1311. if (!create_oat_out_path(apk_path.c_str(),
  1312. instruction_set.c_str(),
  1313. oat_dir.c_str(),
  1314. is_secondary_dex,
  1315. oat_path)) {
  1316. LOG(ERROR) << "Could not create oat out path for "
  1317. << apk_path << " with oat dir " << oat_dir;
  1318. return false;
  1319. }
  1320. oat_file_fd->reset(open(oat_path, O_RDONLY));
  1321. if (oat_file_fd->get() < 0) {
  1322. PLOG(INFO) << "installd cannot open oat file during dexopt" << oat_path;
  1323. }
  1324. std::string vdex_filename = create_vdex_filename(oat_path);
  1325. vdex_file_fd->reset(open(vdex_filename.c_str(), O_RDONLY));
  1326. if (vdex_file_fd->get() < 0) {
  1327. PLOG(INFO) << "installd cannot open vdex file during dexopt" << vdex_filename;
  1328. }
  1329. return true;
  1330. }
  1331. // Updates the access times of out_oat_path based on those from apk_path.
  1332. void update_out_oat_access_times(const char* apk_path, const char* out_oat_path) {
  1333. struct stat input_stat;
  1334. memset(&input_stat, 0, sizeof(input_stat));
  1335. if (stat(apk_path, &input_stat) != 0) {
  1336. PLOG(ERROR) << "Could not stat " << apk_path << " during dexopt";
  1337. return;
  1338. }
  1339. struct utimbuf ut;
  1340. ut.actime = input_stat.st_atime;
  1341. ut.modtime = input_stat.st_mtime;
  1342. if (utime(out_oat_path, &ut) != 0) {
  1343. PLOG(WARNING) << "Could not update access times for " << apk_path << " during dexopt";
  1344. }
  1345. }
  1346. // Runs (execv) dexoptanalyzer on the given arguments.
  1347. // The analyzer will check if the dex_file needs to be (re)compiled to match the compiler_filter.
  1348. // If this is for a profile guided compilation, profile_was_updated will tell whether or not
  1349. // the profile has changed.
  1350. class RunDexoptAnalyzer : public ExecVHelper {
  1351. public:
  1352. RunDexoptAnalyzer(const std::string& dex_file,
  1353. int vdex_fd,
  1354. int oat_fd,
  1355. int zip_fd,
  1356. const std::string& instruction_set,
  1357. const std::string& compiler_filter,
  1358. bool profile_was_updated,
  1359. bool downgrade,
  1360. const char* class_loader_context,
  1361. const std::string& class_loader_context_fds) {
  1362. CHECK_GE(zip_fd, 0);
  1363. // We always run the analyzer in the background job.
  1364. const char* dexoptanalyzer_bin = select_execution_binary(
  1365. kDexoptanalyzerPath, kDexoptanalyzerDebugPath, /*background_job_compile=*/ true);
  1366. std::string dex_file_arg = "--dex-file=" + dex_file;
  1367. std::string oat_fd_arg = "--oat-fd=" + std::to_string(oat_fd);
  1368. std::string vdex_fd_arg = "--vdex-fd=" + std::to_string(vdex_fd);
  1369. std::string zip_fd_arg = "--zip-fd=" + std::to_string(zip_fd);
  1370. std::string isa_arg = "--isa=" + instruction_set;
  1371. std::string compiler_filter_arg = "--compiler-filter=" + compiler_filter;
  1372. const char* assume_profile_changed = "--assume-profile-changed";
  1373. const char* downgrade_flag = "--downgrade";
  1374. std::string class_loader_context_arg = "--class-loader-context=";
  1375. if (class_loader_context != nullptr) {
  1376. class_loader_context_arg += class_loader_context;
  1377. }
  1378. std::string class_loader_context_fds_arg = "--class-loader-context-fds=";
  1379. if (!class_loader_context_fds.empty()) {
  1380. class_loader_context_fds_arg += class_loader_context_fds;
  1381. }
  1382. // program name, dex file, isa, filter
  1383. AddArg(dex_file_arg);
  1384. AddArg(isa_arg);
  1385. AddArg(compiler_filter_arg);
  1386. if (oat_fd >= 0) {
  1387. AddArg(oat_fd_arg);
  1388. }
  1389. if (vdex_fd >= 0) {
  1390. AddArg(vdex_fd_arg);
  1391. }
  1392. AddArg(zip_fd_arg);
  1393. if (profile_was_updated) {
  1394. AddArg(assume_profile_changed);
  1395. }
  1396. if (downgrade) {
  1397. AddArg(downgrade_flag);
  1398. }
  1399. if (class_loader_context != nullptr) {
  1400. AddArg(class_loader_context_arg);
  1401. if (!class_loader_context_fds.empty()) {
  1402. AddArg(class_loader_context_fds_arg);
  1403. }
  1404. }
  1405. PrepareArgs(dexoptanalyzer_bin);
  1406. }
  1407. // Dexoptanalyzer mode which flattens the given class loader context and
  1408. // prints a list of its dex files in that flattened order.
  1409. RunDexoptAnalyzer(const char* class_loader_context) {
  1410. CHECK(class_loader_context != nullptr);
  1411. // We always run the analyzer in the background job.
  1412. const char* dexoptanalyzer_bin = select_execution_binary(
  1413. kDexoptanalyzerPath, kDexoptanalyzerDebugPath, /*background_job_compile=*/ true);
  1414. AddArg("--flatten-class-loader-context");
  1415. AddArg(std::string("--class-loader-context=") + class_loader_context);
  1416. PrepareArgs(dexoptanalyzer_bin);
  1417. }
  1418. };
  1419. // Prepares the oat dir for the secondary dex files.
  1420. static bool prepare_secondary_dex_oat_dir(const std::string& dex_path, int uid,
  1421. const char* instruction_set) {
  1422. unsigned long dirIndex = dex_path.rfind('/');
  1423. if (dirIndex == std::string::npos) {
  1424. LOG(ERROR ) << "Unexpected dir structure for secondary dex " << dex_path;
  1425. return false;
  1426. }
  1427. std::string dex_dir = dex_path.substr(0, dirIndex);
  1428. // Create oat file output directory.
  1429. mode_t oat_dir_mode = S_IRWXU | S_IRWXG | S_IXOTH;
  1430. if (prepare_app_cache_dir(dex_dir, "oat", oat_dir_mode, uid, uid) != 0) {
  1431. LOG(ERROR) << "Could not prepare oat dir for secondary dex: " << dex_path;
  1432. return false;
  1433. }
  1434. char oat_dir[PKG_PATH_MAX];
  1435. snprintf(oat_dir, PKG_PATH_MAX, "%s/oat", dex_dir.c_str());
  1436. if (prepare_app_cache_dir(oat_dir, instruction_set, oat_dir_mode, uid, uid) != 0) {
  1437. LOG(ERROR) << "Could not prepare oat/isa dir for secondary dex: " << dex_path;
  1438. return false;
  1439. }
  1440. return true;
  1441. }
  1442. // Return codes for identifying the reason why dexoptanalyzer was not invoked when processing
  1443. // secondary dex files. This return codes are returned by the child process created for
  1444. // analyzing secondary dex files in process_secondary_dex_dexopt.
  1445. enum DexoptAnalyzerSkipCodes {
  1446. // The dexoptanalyzer was not invoked because of validation or IO errors.
  1447. // Specific errors are encoded in the name.
  1448. kSecondaryDexDexoptAnalyzerSkippedValidatePath = 200,
  1449. kSecondaryDexDexoptAnalyzerSkippedOpenZip = 201,
  1450. kSecondaryDexDexoptAnalyzerSkippedPrepareDir = 202,
  1451. kSecondaryDexDexoptAnalyzerSkippedOpenOutput = 203,
  1452. kSecondaryDexDexoptAnalyzerSkippedFailExec = 204,
  1453. // The dexoptanalyzer was not invoked because the dex file does not exist anymore.
  1454. kSecondaryDexDexoptAnalyzerSkippedNoFile = 205,
  1455. };
  1456. // Verifies the result of analyzing secondary dex files from process_secondary_dex_dexopt.
  1457. // If the result is valid returns true and sets dexopt_needed_out to a valid value.
  1458. // Returns false for errors or unexpected result values.
  1459. // The result is expected to be either one of SECONDARY_DEX_* codes or a valid exit code
  1460. // of dexoptanalyzer.
  1461. static bool process_secondary_dexoptanalyzer_result(const std::string& dex_path, int result,
  1462. int* dexopt_needed_out, std::string* error_msg) {
  1463. // The result values are defined in dexoptanalyzer.
  1464. switch (result) {
  1465. case 0: // dexoptanalyzer: no_dexopt_needed
  1466. *dexopt_needed_out = NO_DEXOPT_NEEDED; return true;
  1467. case 1: // dexoptanalyzer: dex2oat_from_scratch
  1468. *dexopt_needed_out = DEX2OAT_FROM_SCRATCH; return true;
  1469. case 4: // dexoptanalyzer: dex2oat_for_bootimage_odex
  1470. *dexopt_needed_out = -DEX2OAT_FOR_BOOT_IMAGE; return true;
  1471. case 5: // dexoptanalyzer: dex2oat_for_filter_odex
  1472. *dexopt_needed_out = -DEX2OAT_FOR_FILTER; return true;
  1473. case 2: // dexoptanalyzer: dex2oat_for_bootimage_oat
  1474. case 3: // dexoptanalyzer: dex2oat_for_filter_oat
  1475. *error_msg = StringPrintf("Dexoptanalyzer return the status of an oat file."
  1476. " Expected odex file status for secondary dex %s"
  1477. " : dexoptanalyzer result=%d",
  1478. dex_path.c_str(),
  1479. result);
  1480. return false;
  1481. }
  1482. // Use a second switch for enum switch-case analysis.
  1483. switch (static_cast<DexoptAnalyzerSkipCodes>(result)) {
  1484. case kSecondaryDexDexoptAnalyzerSkippedNoFile:
  1485. // If the file does not exist there's no need for dexopt.
  1486. *dexopt_needed_out = NO_DEXOPT_NEEDED;
  1487. return true;
  1488. case kSecondaryDexDexoptAnalyzerSkippedValidatePath:
  1489. *error_msg = "Dexoptanalyzer path validation failed";
  1490. return false;
  1491. case kSecondaryDexDexoptAnalyzerSkippedOpenZip:
  1492. *error_msg = "Dexoptanalyzer open zip failed";
  1493. return false;
  1494. case kSecondaryDexDexoptAnalyzerSkippedPrepareDir:
  1495. *error_msg = "Dexoptanalyzer dir preparation failed";
  1496. return false;
  1497. case kSecondaryDexDexoptAnalyzerSkippedOpenOutput:
  1498. *error_msg = "Dexoptanalyzer open output failed";
  1499. return false;
  1500. case kSecondaryDexDexoptAnalyzerSkippedFailExec:
  1501. *error_msg = "Dexoptanalyzer failed to execute";
  1502. return false;
  1503. }
  1504. *error_msg = StringPrintf("Unexpected result from analyzing secondary dex %s result=%d",
  1505. dex_path.c_str(),
  1506. result);
  1507. return false;
  1508. }
  1509. enum SecondaryDexAccess {
  1510. kSecondaryDexAccessReadOk = 0,
  1511. kSecondaryDexAccessDoesNotExist = 1,
  1512. kSecondaryDexAccessPermissionError = 2,
  1513. kSecondaryDexAccessIOError = 3
  1514. };
  1515. static SecondaryDexAccess check_secondary_dex_access(const std::string& dex_path) {
  1516. // Check if the path exists and can be read. If not, there's nothing to do.
  1517. if (access(dex_path.c_str(), R_OK) == 0) {
  1518. return kSecondaryDexAccessReadOk;
  1519. } else {
  1520. if (errno == ENOENT) {
  1521. LOG(INFO) << "Secondary dex does not exist: " << dex_path;
  1522. return kSecondaryDexAccessDoesNotExist;
  1523. } else {
  1524. PLOG(ERROR) << "Could not access secondary dex " << dex_path;
  1525. return errno == EACCES
  1526. ? kSecondaryDexAccessPermissionError
  1527. : kSecondaryDexAccessIOError;
  1528. }
  1529. }
  1530. }
  1531. static bool is_file_public(const std::string& filename) {
  1532. struct stat file_stat;
  1533. if (stat(filename.c_str(), &file_stat) == 0) {
  1534. return (file_stat.st_mode & S_IROTH) != 0;
  1535. }
  1536. return false;
  1537. }
  1538. // Create the oat file structure for the secondary dex 'dex_path' and assign
  1539. // the individual path component to the 'out_' parameters.
  1540. static bool create_secondary_dex_oat_layout(const std::string& dex_path, const std::string& isa,
  1541. char* out_oat_dir, char* out_oat_isa_dir, char* out_oat_path, std::string* error_msg) {
  1542. size_t dirIndex = dex_path.rfind('/');
  1543. if (dirIndex == std::string::npos) {
  1544. *error_msg = std::string("Unexpected dir structure for dex file ").append(dex_path);
  1545. return false;
  1546. }
  1547. // TODO(calin): we have similar computations in at lest 3 other places
  1548. // (InstalldNativeService, otapropt and dexopt). Unify them and get rid of snprintf by
  1549. // using string append.
  1550. std::string apk_dir = dex_path.substr(0, dirIndex);
  1551. snprintf(out_oat_dir, PKG_PATH_MAX, "%s/oat", apk_dir.c_str());
  1552. snprintf(out_oat_isa_dir, PKG_PATH_MAX, "%s/%s", out_oat_dir, isa.c_str());
  1553. if (!create_oat_out_path(dex_path.c_str(), isa.c_str(), out_oat_dir,
  1554. /*is_secondary_dex*/true, out_oat_path)) {
  1555. *error_msg = std::string("Could not create oat path for secondary dex ").append(dex_path);
  1556. return false;
  1557. }
  1558. return true;
  1559. }
  1560. // Validate that the dexopt_flags contain a valid storage flag and convert that to an installd
  1561. // recognized storage flags (FLAG_STORAGE_CE or FLAG_STORAGE_DE).
  1562. static bool validate_dexopt_storage_flags(int dexopt_flags,
  1563. int* out_storage_flag,
  1564. std::string* error_msg) {
  1565. if ((dexopt_flags & DEXOPT_STORAGE_CE) != 0) {
  1566. *out_storage_flag = FLAG_STORAGE_CE;
  1567. if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
  1568. *error_msg = "Ambiguous secondary dex storage flag. Both, CE and DE, flags are set";
  1569. return false;
  1570. }
  1571. } else if ((dexopt_flags & DEXOPT_STORAGE_DE) != 0) {
  1572. *out_storage_flag = FLAG_STORAGE_DE;
  1573. } else {
  1574. *error_msg = "Secondary dex storage flag must be set";
  1575. return false;
  1576. }
  1577. return true;
  1578. }
  1579. static bool get_class_loader_context_dex_paths(const char* class_loader_context, int uid,
  1580. /* out */ std::vector<std::string>* context_dex_paths) {
  1581. if (class_loader_context == nullptr) {
  1582. return true;
  1583. }
  1584. LOG(DEBUG) << "Getting dex paths for context " << class_loader_context;
  1585. // Pipe to get the hash result back from our child process.
  1586. unique_fd pipe_read, pipe_write;
  1587. if (!Pipe(&pipe_read, &pipe_write)) {
  1588. PLOG(ERROR) << "Failed to create pipe";
  1589. return false;
  1590. }
  1591. pid_t pid = fork();
  1592. if (pid == 0) {
  1593. // child -- drop privileges before continuing.
  1594. drop_capabilities(uid);
  1595. // Route stdout to `pipe_write`
  1596. while ((dup2(pipe_write, STDOUT_FILENO) == -1) && (errno == EINTR)) {}
  1597. pipe_write.reset();
  1598. pipe_read.reset();
  1599. RunDexoptAnalyzer run_dexopt_analyzer(class_loader_context);
  1600. run_dexopt_analyzer.Exec(kSecondaryDexDexoptAnalyzerSkippedFailExec);
  1601. }
  1602. /* parent */
  1603. pipe_write.reset();
  1604. std::string str_dex_paths;
  1605. if (!ReadFdToString(pipe_read, &str_dex_paths)) {
  1606. PLOG(ERROR) << "Failed to read from pipe";
  1607. return false;
  1608. }
  1609. pipe_read.reset();
  1610. int return_code = wait_child(pid);
  1611. if (!WIFEXITED(return_code)) {
  1612. PLOG(ERROR) << "Error waiting for child dexoptanalyzer process";
  1613. return false;
  1614. }
  1615. constexpr int kFlattenClassLoaderContextSuccess = 50;
  1616. return_code = WEXITSTATUS(return_code);
  1617. if (return_code != kFlattenClassLoaderContextSuccess) {
  1618. LOG(ERROR) << "Dexoptanalyzer could not flatten class loader context, code=" << return_code;
  1619. return false;
  1620. }
  1621. if (!str_dex_paths.empty()) {
  1622. *context_dex_paths = android::base::Split(str_dex_paths, ":");
  1623. }
  1624. return true;
  1625. }
  1626. static int open_dex_paths(const std::vector<std::string>& dex_paths,
  1627. /* out */ std::vector<unique_fd>* zip_fds, /* out */ std::string* error_msg) {
  1628. for (const std::string& dex_path : dex_paths) {
  1629. zip_fds->emplace_back(open(dex_path.c_str(), O_RDONLY));
  1630. if (zip_fds->back().get() < 0) {
  1631. *error_msg = StringPrintf(
  1632. "installd cannot open '%s' for input during dexopt", dex_path.c_str());
  1633. if (errno == ENOENT) {
  1634. return kSecondaryDexDexoptAnalyzerSkippedNoFile;
  1635. } else {
  1636. return kSecondaryDexDexoptAnalyzerSkippedOpenZip;
  1637. }
  1638. }
  1639. }
  1640. return 0;
  1641. }
  1642. static std::string join_fds(const std::vector<unique_fd>& fds) {
  1643. std::stringstream ss;
  1644. bool is_first = true;
  1645. for (const unique_fd& fd : fds) {
  1646. if (is_first) {
  1647. is_first = false;
  1648. } else {
  1649. ss << ":";
  1650. }
  1651. ss << fd.get();
  1652. }
  1653. return ss.str();
  1654. }
  1655. // Processes the dex_path as a secondary dex files and return true if the path dex file should
  1656. // be compiled. Returns false for errors (logged) or true if the secondary dex path was process
  1657. // successfully.
  1658. // When returning true, the output parameters will be:
  1659. // - is_public_out: whether or not the oat file should not be made public
  1660. // - dexopt_needed_out: valid OatFileAsssitant::DexOptNeeded
  1661. // - oat_dir_out: the oat dir path where the oat file should be stored
  1662. static bool process_secondary_dex_dexopt(const std::string& dex_path, const char* pkgname,
  1663. int dexopt_flags, const char* volume_uuid, int uid, const char* instruction_set,
  1664. const char* compiler_filter, bool* is_public_out, int* dexopt_needed_out,
  1665. std::string* oat_dir_out, bool downgrade, const char* class_loader_context,
  1666. const std::vector<std::string>& context_dex_paths, /* out */ std::string* error_msg) {
  1667. LOG(DEBUG) << "Processing secondary dex path " << dex_path;
  1668. int storage_flag;
  1669. if (!validate_dexopt_storage_flags(dexopt_flags, &storage_flag, error_msg)) {
  1670. LOG(ERROR) << *error_msg;
  1671. return false;
  1672. }
  1673. // Compute the oat dir as it's not easy to extract it from the child computation.
  1674. char oat_path[PKG_PATH_MAX];
  1675. char oat_dir[PKG_PATH_MAX];
  1676. char oat_isa_dir[PKG_PATH_MAX];
  1677. if (!create_secondary_dex_oat_layout(
  1678. dex_path, instruction_set, oat_dir, oat_isa_dir, oat_path, error_msg)) {
  1679. LOG(ERROR) << "Could not create secondary odex layout: " << *error_msg;
  1680. return false;
  1681. }
  1682. oat_dir_out->assign(oat_dir);
  1683. pid_t pid = fork();
  1684. if (pid == 0) {
  1685. // child -- drop privileges before continuing.
  1686. drop_capabilities(uid);
  1687. // Validate the path structure.
  1688. if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid, uid, storage_flag)) {
  1689. LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
  1690. _exit(kSecondaryDexDexoptAnalyzerSkippedValidatePath);
  1691. }
  1692. // Open the dex file.
  1693. unique_fd zip_fd;
  1694. zip_fd.reset(open(dex_path.c_str(), O_RDONLY));
  1695. if (zip_fd.get() < 0) {
  1696. if (errno == ENOENT) {
  1697. _exit(kSecondaryDexDexoptAnalyzerSkippedNoFile);
  1698. } else {
  1699. _exit(kSecondaryDexDexoptAnalyzerSkippedOpenZip);
  1700. }
  1701. }
  1702. // Open class loader context dex files.
  1703. std::vector<unique_fd> context_zip_fds;
  1704. int open_dex_paths_rc = open_dex_paths(context_dex_paths, &context_zip_fds, error_msg);
  1705. if (open_dex_paths_rc != 0) {
  1706. _exit(open_dex_paths_rc);
  1707. }
  1708. // Prepare the oat directories.
  1709. if (!prepare_secondary_dex_oat_dir(dex_path, uid, instruction_set)) {
  1710. _exit(kSecondaryDexDexoptAnalyzerSkippedPrepareDir);
  1711. }
  1712. // Open the vdex/oat files if any.
  1713. unique_fd oat_file_fd;
  1714. unique_fd vdex_file_fd;
  1715. if (!maybe_open_oat_and_vdex_file(dex_path,
  1716. *oat_dir_out,
  1717. instruction_set,
  1718. true /* is_secondary_dex */,
  1719. &oat_file_fd,
  1720. &vdex_file_fd)) {
  1721. _exit(kSecondaryDexDexoptAnalyzerSkippedOpenOutput);
  1722. }
  1723. // Analyze profiles.
  1724. bool profile_was_updated = analyze_profiles(uid, pkgname, dex_path,
  1725. /*is_secondary_dex*/true);
  1726. // Run dexoptanalyzer to get dexopt_needed code. This is not expected to return.
  1727. // Note that we do not do it before the fork since opening the files is required to happen
  1728. // after forking.
  1729. RunDexoptAnalyzer run_dexopt_analyzer(dex_path,
  1730. vdex_file_fd.get(),
  1731. oat_file_fd.get(),
  1732. zip_fd.get(),
  1733. instruction_set,
  1734. compiler_filter, profile_was_updated,
  1735. downgrade,
  1736. class_loader_context,
  1737. join_fds(context_zip_fds));
  1738. run_dexopt_analyzer.Exec(kSecondaryDexDexoptAnalyzerSkippedFailExec);
  1739. }
  1740. /* parent */
  1741. int result = wait_child(pid);
  1742. if (!WIFEXITED(result)) {
  1743. *error_msg = StringPrintf("dexoptanalyzer failed for path %s: 0x%04x",
  1744. dex_path.c_str(),
  1745. result);
  1746. LOG(ERROR) << *error_msg;
  1747. return false;
  1748. }
  1749. result = WEXITSTATUS(result);
  1750. // Check that we successfully executed dexoptanalyzer.
  1751. bool success = process_secondary_dexoptanalyzer_result(dex_path,
  1752. result,
  1753. dexopt_needed_out,
  1754. error_msg);
  1755. if (!success) {
  1756. LOG(ERROR) << *error_msg;
  1757. }
  1758. LOG(DEBUG) << "Processed secondary dex file " << dex_path << " result=" << result;
  1759. // Run dexopt only if needed or forced.
  1760. // Note that dexoptanalyzer is executed even if force compilation is enabled (because it
  1761. // makes the code simpler; force compilation is only needed during tests).
  1762. if (success &&
  1763. (result != kSecondaryDexDexoptAnalyzerSkippedNoFile) &&
  1764. ((dexopt_flags & DEXOPT_FORCE) != 0)) {
  1765. *dexopt_needed_out = DEX2OAT_FROM_SCRATCH;
  1766. }
  1767. // Check if we should make the oat file public.
  1768. // Note that if the dex file is not public the compiled code cannot be made public.
  1769. // It is ok to check this flag outside in the parent process.
  1770. *is_public_out = ((dexopt_flags & DEXOPT_PUBLIC) != 0) && is_file_public(dex_path);
  1771. return success;
  1772. }
  1773. static std::string format_dexopt_error(int status, const char* dex_path) {
  1774. if (WIFEXITED(status)) {
  1775. int int_code = WEXITSTATUS(status);
  1776. const char* code_name = get_return_code_name(static_cast<DexoptReturnCodes>(int_code));
  1777. if (code_name != nullptr) {
  1778. return StringPrintf("Dex2oat invocation for %s failed: %s", dex_path, code_name);
  1779. }
  1780. }
  1781. return StringPrintf("Dex2oat invocation for %s failed with 0x%04x", dex_path, status);
  1782. }
  1783. int dexopt(const char* dex_path, uid_t uid, const char* pkgname, const char* instruction_set,
  1784. int dexopt_needed, const char* oat_dir, int dexopt_flags, const char* compiler_filter,
  1785. const char* volume_uuid, const char* class_loader_context, const char* se_info,
  1786. bool downgrade, int target_sdk_version, const char* profile_name,
  1787. const char* dex_metadata_path, const char* compilation_reason, std::string* error_msg) {
  1788. CHECK(pkgname != nullptr);
  1789. CHECK(pkgname[0] != 0);
  1790. CHECK(error_msg != nullptr);
  1791. CHECK_EQ(dexopt_flags & ~DEXOPT_MASK, 0)
  1792. << "dexopt flags contains unknown fields: " << dexopt_flags;
  1793. if (!validate_dex_path_size(dex_path)) {
  1794. *error_msg = StringPrintf("Failed to validate %s", dex_path);
  1795. return -1;
  1796. }
  1797. if (class_loader_context != nullptr && strlen(class_loader_context) > PKG_PATH_MAX) {
  1798. *error_msg = StringPrintf("Class loader context exceeds the allowed size: %s",
  1799. class_loader_context);
  1800. LOG(ERROR) << *error_msg;
  1801. return -1;
  1802. }
  1803. bool is_public = (dexopt_flags & DEXOPT_PUBLIC) != 0;
  1804. bool debuggable = (dexopt_flags & DEXOPT_DEBUGGABLE) != 0;
  1805. bool boot_complete = (dexopt_flags & DEXOPT_BOOTCOMPLETE) != 0;
  1806. bool profile_guided = (dexopt_flags & DEXOPT_PROFILE_GUIDED) != 0;
  1807. bool is_secondary_dex = (dexopt_flags & DEXOPT_SECONDARY_DEX) != 0;
  1808. bool background_job_compile = (dexopt_flags & DEXOPT_IDLE_BACKGROUND_JOB) != 0;
  1809. bool enable_hidden_api_checks = (dexopt_flags & DEXOPT_ENABLE_HIDDEN_API_CHECKS) != 0;
  1810. bool generate_compact_dex = (dexopt_flags & DEXOPT_GENERATE_COMPACT_DEX) != 0;
  1811. bool generate_app_image = (dexopt_flags & DEXOPT_GENERATE_APP_IMAGE) != 0;
  1812. // Check if we're dealing with a secondary dex file and if we need to compile it.
  1813. std::string oat_dir_str;
  1814. std::vector<std::string> context_dex_paths;
  1815. if (is_secondary_dex) {
  1816. if (!get_class_loader_context_dex_paths(class_loader_context, uid, &context_dex_paths)) {
  1817. *error_msg = "Failed acquiring context dex paths";
  1818. return -1; // We had an error, logged in the process method.
  1819. }
  1820. if (process_secondary_dex_dexopt(dex_path, pkgname, dexopt_flags, volume_uuid, uid,
  1821. instruction_set, compiler_filter, &is_public, &dexopt_needed, &oat_dir_str,
  1822. downgrade, class_loader_context, context_dex_paths, error_msg)) {
  1823. oat_dir = oat_dir_str.c_str();
  1824. if (dexopt_needed == NO_DEXOPT_NEEDED) {
  1825. return 0; // Nothing to do, report success.
  1826. }
  1827. } else {
  1828. if (error_msg->empty()) { // TODO: Make this a CHECK.
  1829. *error_msg = "Failed processing secondary.";
  1830. }
  1831. return -1; // We had an error, logged in the process method.
  1832. }
  1833. } else {
  1834. // Currently these flags are only used for secondary dex files.
  1835. // Verify that they are not set for primary apks.
  1836. CHECK((dexopt_flags & DEXOPT_STORAGE_CE) == 0);
  1837. CHECK((dexopt_flags & DEXOPT_STORAGE_DE) == 0);
  1838. }
  1839. // Open the input file.
  1840. unique_fd input_fd(open(dex_path, O_RDONLY, 0));
  1841. if (input_fd.get() < 0) {
  1842. *error_msg = StringPrintf("installd cannot open '%s' for input during dexopt", dex_path);
  1843. LOG(ERROR) << *error_msg;
  1844. return -1;
  1845. }
  1846. // Open class loader context dex files.
  1847. std::vector<unique_fd> context_input_fds;
  1848. if (open_dex_paths(context_dex_paths, &context_input_fds, error_msg) != 0) {
  1849. LOG(ERROR) << *error_msg;
  1850. return -1;
  1851. }
  1852. // Create the output OAT file.
  1853. char out_oat_path[PKG_PATH_MAX];
  1854. Dex2oatFileWrapper out_oat_fd = open_oat_out_file(dex_path, oat_dir, is_public, uid,
  1855. instruction_set, is_secondary_dex, out_oat_path);
  1856. if (out_oat_fd.get() < 0) {
  1857. *error_msg = "Could not open out oat file.";
  1858. return -1;
  1859. }
  1860. // Open vdex files.
  1861. Dex2oatFileWrapper in_vdex_fd;
  1862. Dex2oatFileWrapper out_vdex_fd;
  1863. if (!open_vdex_files_for_dex2oat(dex_path, out_oat_path, dexopt_needed, instruction_set,
  1864. is_public, uid, is_secondary_dex, profile_guided, &in_vdex_fd, &out_vdex_fd)) {
  1865. *error_msg = "Could not open vdex files.";
  1866. return -1;
  1867. }
  1868. // Ensure that the oat dir and the compiler artifacts of secondary dex files have the correct
  1869. // selinux context (we generate them on the fly during the dexopt invocation and they don't
  1870. // fully inherit their parent context).
  1871. // Note that for primary apk the oat files are created before, in a separate installd
  1872. // call which also does the restorecon. TODO(calin): unify the paths.
  1873. if (is_secondary_dex) {
  1874. if (selinux_android_restorecon_pkgdir(oat_dir, se_info, uid,
  1875. SELINUX_ANDROID_RESTORECON_RECURSE)) {
  1876. *error_msg = std::string("Failed to restorecon ").append(oat_dir);
  1877. LOG(ERROR) << *error_msg;
  1878. return -1;
  1879. }
  1880. }
  1881. // Create a swap file if necessary.
  1882. unique_fd swap_fd = maybe_open_dexopt_swap_file(out_oat_path);
  1883. // Create the app image file if needed.
  1884. Dex2oatFileWrapper image_fd = maybe_open_app_image(
  1885. out_oat_path, generate_app_image, is_public, uid, is_secondary_dex);
  1886. // Open the reference profile if needed.
  1887. Dex2oatFileWrapper reference_profile_fd = maybe_open_reference_profile(
  1888. pkgname, dex_path, profile_name, profile_guided, is_public, uid, is_secondary_dex);
  1889. unique_fd dex_metadata_fd;
  1890. if (dex_metadata_path != nullptr) {
  1891. dex_metadata_fd.reset(TEMP_FAILURE_RETRY(open(dex_metadata_path, O_RDONLY | O_NOFOLLOW)));
  1892. if (dex_metadata_fd.get() < 0) {
  1893. PLOG(ERROR) << "Failed to open dex metadata file " << dex_metadata_path;
  1894. }
  1895. }
  1896. LOG(VERBOSE) << "DexInv: --- BEGIN '" << dex_path << "' ---";
  1897. RunDex2Oat runner(input_fd.get(),
  1898. out_oat_fd.get(),
  1899. in_vdex_fd.get(),
  1900. out_vdex_fd.get(),
  1901. image_fd.get(),
  1902. dex_path,
  1903. out_oat_path,
  1904. swap_fd.get(),
  1905. instruction_set,
  1906. compiler_filter,
  1907. debuggable,
  1908. boot_complete,
  1909. background_job_compile,
  1910. reference_profile_fd.get(),
  1911. class_loader_context,
  1912. join_fds(context_input_fds),
  1913. target_sdk_version,
  1914. enable_hidden_api_checks,
  1915. generate_compact_dex,
  1916. dex_metadata_fd.get(),
  1917. compilation_reason);
  1918. pid_t pid = fork();
  1919. if (pid == 0) {
  1920. /* child -- drop privileges before continuing */
  1921. drop_capabilities(uid);
  1922. SetDex2OatScheduling(boot_complete);
  1923. if (flock(out_oat_fd.get(), LOCK_EX | LOCK_NB) != 0) {
  1924. PLOG(ERROR) << "flock(" << out_oat_path << ") failed";
  1925. _exit(DexoptReturnCodes::kFlock);
  1926. }
  1927. runner.Exec(DexoptReturnCodes::kDex2oatExec);
  1928. } else {
  1929. int res = wait_child(pid);
  1930. if (res == 0) {
  1931. LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' (success) ---";
  1932. } else {
  1933. LOG(VERBOSE) << "DexInv: --- END '" << dex_path << "' --- status=0x"
  1934. << std::hex << std::setw(4) << res << ", process failed";
  1935. *error_msg = format_dexopt_error(res, dex_path);
  1936. return res;
  1937. }
  1938. }
  1939. update_out_oat_access_times(dex_path, out_oat_path);
  1940. // We've been successful, don't delete output.
  1941. out_oat_fd.SetCleanup(false);
  1942. out_vdex_fd.SetCleanup(false);
  1943. image_fd.SetCleanup(false);
  1944. reference_profile_fd.SetCleanup(false);
  1945. return 0;
  1946. }
  1947. // Try to remove the given directory. Log an error if the directory exists
  1948. // and is empty but could not be removed.
  1949. static bool rmdir_if_empty(const char* dir) {
  1950. if (rmdir(dir) == 0) {
  1951. return true;
  1952. }
  1953. if (errno == ENOENT || errno == ENOTEMPTY) {
  1954. return true;
  1955. }
  1956. PLOG(ERROR) << "Failed to remove dir: " << dir;
  1957. return false;
  1958. }
  1959. // Try to unlink the given file. Log an error if the file exists and could not
  1960. // be unlinked.
  1961. static bool unlink_if_exists(const std::string& file) {
  1962. if (unlink(file.c_str()) == 0) {
  1963. return true;
  1964. }
  1965. if (errno == ENOENT) {
  1966. return true;
  1967. }
  1968. PLOG(ERROR) << "Could not unlink: " << file;
  1969. return false;
  1970. }
  1971. enum ReconcileSecondaryDexResult {
  1972. kReconcileSecondaryDexExists = 0,
  1973. kReconcileSecondaryDexCleanedUp = 1,
  1974. kReconcileSecondaryDexValidationError = 2,
  1975. kReconcileSecondaryDexCleanUpError = 3,
  1976. kReconcileSecondaryDexAccessIOError = 4,
  1977. };
  1978. // Reconcile the secondary dex 'dex_path' and its generated oat files.
  1979. // Return true if all the parameters are valid and the secondary dex file was
  1980. // processed successfully (i.e. the dex_path either exists, or if not, its corresponding
  1981. // oat/vdex/art files where deleted successfully). In this case, out_secondary_dex_exists
  1982. // will be true if the secondary dex file still exists. If the secondary dex file does not exist,
  1983. // the method cleans up any previously generated compiler artifacts (oat, vdex, art).
  1984. // Return false if there were errors during processing. In this case
  1985. // out_secondary_dex_exists will be set to false.
  1986. bool reconcile_secondary_dex_file(const std::string& dex_path,
  1987. const std::string& pkgname, int uid, const std::vector<std::string>& isas,
  1988. const std::unique_ptr<std::string>& volume_uuid, int storage_flag,
  1989. /*out*/bool* out_secondary_dex_exists) {
  1990. *out_secondary_dex_exists = false; // start by assuming the file does not exist.
  1991. if (isas.size() == 0) {
  1992. LOG(ERROR) << "reconcile_secondary_dex_file called with empty isas vector";
  1993. return false;
  1994. }
  1995. if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
  1996. LOG(ERROR) << "reconcile_secondary_dex_file called with invalid storage_flag: "
  1997. << storage_flag;
  1998. return false;
  1999. }
  2000. // As a security measure we want to unlink art artifacts with the reduced capabilities
  2001. // of the package user id. So we fork and drop capabilities in the child.
  2002. pid_t pid = fork();
  2003. if (pid == 0) {
  2004. /* child -- drop privileges before continuing */
  2005. drop_capabilities(uid);
  2006. const char* volume_uuid_cstr = volume_uuid == nullptr ? nullptr : volume_uuid->c_str();
  2007. if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr,
  2008. uid, storage_flag)) {
  2009. LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
  2010. _exit(kReconcileSecondaryDexValidationError);
  2011. }
  2012. SecondaryDexAccess access_check = check_secondary_dex_access(dex_path);
  2013. switch (access_check) {
  2014. case kSecondaryDexAccessDoesNotExist:
  2015. // File does not exist. Proceed with cleaning.
  2016. break;
  2017. case kSecondaryDexAccessReadOk: _exit(kReconcileSecondaryDexExists);
  2018. case kSecondaryDexAccessIOError: _exit(kReconcileSecondaryDexAccessIOError);
  2019. case kSecondaryDexAccessPermissionError: _exit(kReconcileSecondaryDexValidationError);
  2020. default:
  2021. LOG(ERROR) << "Unexpected result from check_secondary_dex_access: " << access_check;
  2022. _exit(kReconcileSecondaryDexValidationError);
  2023. }
  2024. // The secondary dex does not exist anymore or it's. Clear any generated files.
  2025. char oat_path[PKG_PATH_MAX];
  2026. char oat_dir[PKG_PATH_MAX];
  2027. char oat_isa_dir[PKG_PATH_MAX];
  2028. bool result = true;
  2029. for (size_t i = 0; i < isas.size(); i++) {
  2030. std::string error_msg;
  2031. if (!create_secondary_dex_oat_layout(
  2032. dex_path,isas[i], oat_dir, oat_isa_dir, oat_path, &error_msg)) {
  2033. LOG(ERROR) << error_msg;
  2034. _exit(kReconcileSecondaryDexValidationError);
  2035. }
  2036. // Delete oat/vdex/art files.
  2037. result = unlink_if_exists(oat_path) && result;
  2038. result = unlink_if_exists(create_vdex_filename(oat_path)) && result;
  2039. result = unlink_if_exists(create_image_filename(oat_path)) && result;
  2040. // Delete profiles.
  2041. std::string current_profile = create_current_profile_path(
  2042. multiuser_get_user_id(uid), pkgname, dex_path, /*is_secondary*/true);
  2043. std::string reference_profile = create_reference_profile_path(
  2044. pkgname, dex_path, /*is_secondary*/true);
  2045. result = unlink_if_exists(current_profile) && result;
  2046. result = unlink_if_exists(reference_profile) && result;
  2047. // We upgraded once the location of current profile for secondary dex files.
  2048. // Check for any previous left-overs and remove them as well.
  2049. std::string old_current_profile = dex_path + ".prof";
  2050. result = unlink_if_exists(old_current_profile);
  2051. // Try removing the directories as well, they might be empty.
  2052. result = rmdir_if_empty(oat_isa_dir) && result;
  2053. result = rmdir_if_empty(oat_dir) && result;
  2054. }
  2055. if (!result) {
  2056. PLOG(ERROR) << "Failed to clean secondary dex artifacts for location " << dex_path;
  2057. }
  2058. _exit(result ? kReconcileSecondaryDexCleanedUp : kReconcileSecondaryDexAccessIOError);
  2059. }
  2060. int return_code = wait_child(pid);
  2061. if (!WIFEXITED(return_code)) {
  2062. LOG(WARNING) << "reconcile dex failed for location " << dex_path << ": " << return_code;
  2063. } else {
  2064. return_code = WEXITSTATUS(return_code);
  2065. }
  2066. LOG(DEBUG) << "Reconcile secondary dex path " << dex_path << " result=" << return_code;
  2067. switch (return_code) {
  2068. case kReconcileSecondaryDexCleanedUp:
  2069. case kReconcileSecondaryDexValidationError:
  2070. // If we couldn't validate assume the dex file does not exist.
  2071. // This will purge the entry from the PM records.
  2072. *out_secondary_dex_exists = false;
  2073. return true;
  2074. case kReconcileSecondaryDexExists:
  2075. *out_secondary_dex_exists = true;
  2076. return true;
  2077. case kReconcileSecondaryDexAccessIOError:
  2078. // We had an access IO error.
  2079. // Return false so that we can try again.
  2080. // The value of out_secondary_dex_exists does not matter in this case and by convention
  2081. // is set to false.
  2082. *out_secondary_dex_exists = false;
  2083. return false;
  2084. default:
  2085. LOG(ERROR) << "Unexpected code from reconcile_secondary_dex_file: " << return_code;
  2086. *out_secondary_dex_exists = false;
  2087. return false;
  2088. }
  2089. }
  2090. // Compute and return the hash (SHA-256) of the secondary dex file at dex_path.
  2091. // Returns true if all parameters are valid and the hash successfully computed and stored in
  2092. // out_secondary_dex_hash.
  2093. // Also returns true with an empty hash if the file does not currently exist or is not accessible to
  2094. // the app.
  2095. // For any other errors (e.g. if any of the parameters are invalid) returns false.
  2096. bool hash_secondary_dex_file(const std::string& dex_path, const std::string& pkgname, int uid,
  2097. const std::unique_ptr<std::string>& volume_uuid, int storage_flag,
  2098. std::vector<uint8_t>* out_secondary_dex_hash) {
  2099. out_secondary_dex_hash->clear();
  2100. const char* volume_uuid_cstr = volume_uuid == nullptr ? nullptr : volume_uuid->c_str();
  2101. if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
  2102. LOG(ERROR) << "hash_secondary_dex_file called with invalid storage_flag: "
  2103. << storage_flag;
  2104. return false;
  2105. }
  2106. // Pipe to get the hash result back from our child process.
  2107. unique_fd pipe_read, pipe_write;
  2108. if (!Pipe(&pipe_read, &pipe_write)) {
  2109. PLOG(ERROR) << "Failed to create pipe";
  2110. return false;
  2111. }
  2112. // Fork so that actual access to the files is done in the app's own UID, to ensure we only
  2113. // access data the app itself can access.
  2114. pid_t pid = fork();
  2115. if (pid == 0) {
  2116. // child -- drop privileges before continuing
  2117. drop_capabilities(uid);
  2118. pipe_read.reset();
  2119. if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr, uid, storage_flag)) {
  2120. LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
  2121. _exit(DexoptReturnCodes::kHashValidatePath);
  2122. }
  2123. unique_fd fd(TEMP_FAILURE_RETRY(open(dex_path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW)));
  2124. if (fd == -1) {
  2125. if (errno == EACCES || errno == ENOENT) {
  2126. // Not treated as an error.
  2127. _exit(0);
  2128. }
  2129. PLOG(ERROR) << "Failed to open secondary dex " << dex_path;
  2130. _exit(DexoptReturnCodes::kHashOpenPath);
  2131. }
  2132. SHA256_CTX ctx;
  2133. SHA256_Init(&ctx);
  2134. std::vector<uint8_t> buffer(65536);
  2135. while (true) {
  2136. ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer.data(), buffer.size()));
  2137. if (bytes_read == 0) {
  2138. break;
  2139. } else if (bytes_read == -1) {
  2140. PLOG(ERROR) << "Failed to read secondary dex " << dex_path;
  2141. _exit(DexoptReturnCodes::kHashReadDex);
  2142. }
  2143. SHA256_Update(&ctx, buffer.data(), bytes_read);
  2144. }
  2145. std::array<uint8_t, SHA256_DIGEST_LENGTH> hash;
  2146. SHA256_Final(hash.data(), &ctx);
  2147. if (!WriteFully(pipe_write, hash.data(), hash.size())) {
  2148. _exit(DexoptReturnCodes::kHashWrite);
  2149. }
  2150. _exit(0);
  2151. }
  2152. // parent
  2153. pipe_write.reset();
  2154. out_secondary_dex_hash->resize(SHA256_DIGEST_LENGTH);
  2155. if (!ReadFully(pipe_read, out_secondary_dex_hash->data(), out_secondary_dex_hash->size())) {
  2156. out_secondary_dex_hash->clear();
  2157. }
  2158. return wait_child(pid) == 0;
  2159. }
  2160. // Helper for move_ab, so that we can have common failure-case cleanup.
  2161. static bool unlink_and_rename(const char* from, const char* to) {
  2162. // Check whether "from" exists, and if so whether it's regular. If it is, unlink. Otherwise,
  2163. // return a failure.
  2164. struct stat s;
  2165. if (stat(to, &s) == 0) {
  2166. if (!S_ISREG(s.st_mode)) {
  2167. LOG(ERROR) << from << " is not a regular file to replace for A/B.";
  2168. return false;
  2169. }
  2170. if (unlink(to) != 0) {
  2171. LOG(ERROR) << "Could not unlink " << to << " to move A/B.";
  2172. return false;
  2173. }
  2174. } else {
  2175. // This may be a permission problem. We could investigate the error code, but we'll just
  2176. // let the rename failure do the work for us.
  2177. }
  2178. // Try to rename "to" to "from."
  2179. if (rename(from, to) != 0) {
  2180. PLOG(ERROR) << "Could not rename " << from << " to " << to;
  2181. return false;
  2182. }
  2183. return true;
  2184. }
  2185. // Move/rename a B artifact (from) to an A artifact (to).
  2186. static bool move_ab_path(const std::string& b_path, const std::string& a_path) {
  2187. // Check whether B exists.
  2188. {
  2189. struct stat s;
  2190. if (stat(b_path.c_str(), &s) != 0) {
  2191. // Silently ignore for now. The service calling this isn't smart enough to understand
  2192. // lack of artifacts at the moment.
  2193. return false;
  2194. }
  2195. if (!S_ISREG(s.st_mode)) {
  2196. LOG(ERROR) << "A/B artifact " << b_path << " is not a regular file.";
  2197. // Try to unlink, but swallow errors.
  2198. unlink(b_path.c_str());
  2199. return false;
  2200. }
  2201. }
  2202. // Rename B to A.
  2203. if (!unlink_and_rename(b_path.c_str(), a_path.c_str())) {
  2204. // Delete the b_path so we don't try again (or fail earlier).
  2205. if (unlink(b_path.c_str()) != 0) {
  2206. PLOG(ERROR) << "Could not unlink " << b_path;
  2207. }
  2208. return false;
  2209. }
  2210. return true;
  2211. }
  2212. bool move_ab(const char* apk_path, const char* instruction_set, const char* oat_dir) {
  2213. // Get the current slot suffix. No suffix, no A/B.
  2214. const std::string slot_suffix = GetProperty("ro.boot.slot_suffix", "");
  2215. if (slot_suffix.empty()) {
  2216. return false;
  2217. }
  2218. if (!ValidateTargetSlotSuffix(slot_suffix)) {
  2219. LOG(ERROR) << "Target slot suffix not legal: " << slot_suffix;
  2220. return false;
  2221. }
  2222. // Validate other inputs.
  2223. if (validate_apk_path(apk_path) != 0) {
  2224. LOG(ERROR) << "Invalid apk_path: " << apk_path;
  2225. return false;
  2226. }
  2227. if (validate_apk_path(oat_dir) != 0) {
  2228. LOG(ERROR) << "Invalid oat_dir: " << oat_dir;
  2229. return false;
  2230. }
  2231. char a_path[PKG_PATH_MAX];
  2232. if (!calculate_oat_file_path(a_path, oat_dir, apk_path, instruction_set)) {
  2233. return false;
  2234. }
  2235. const std::string a_vdex_path = create_vdex_filename(a_path);
  2236. const std::string a_image_path = create_image_filename(a_path);
  2237. // B path = A path + slot suffix.
  2238. const std::string b_path = StringPrintf("%s.%s", a_path, slot_suffix.c_str());
  2239. const std::string b_vdex_path = StringPrintf("%s.%s", a_vdex_path.c_str(), slot_suffix.c_str());
  2240. const std::string b_image_path = StringPrintf("%s.%s",
  2241. a_image_path.c_str(),
  2242. slot_suffix.c_str());
  2243. bool success = true;
  2244. if (move_ab_path(b_path, a_path)) {
  2245. if (move_ab_path(b_vdex_path, a_vdex_path)) {
  2246. // Note: we can live without an app image. As such, ignore failure to move the image file.
  2247. // If we decide to require the app image, or the app image being moved correctly,
  2248. // then change accordingly.
  2249. constexpr bool kIgnoreAppImageFailure = true;
  2250. if (!a_image_path.empty()) {
  2251. if (!move_ab_path(b_image_path, a_image_path)) {
  2252. unlink(a_image_path.c_str());
  2253. if (!kIgnoreAppImageFailure) {
  2254. success = false;
  2255. }
  2256. }
  2257. }
  2258. } else {
  2259. // Cleanup: delete B image, ignore errors.
  2260. unlink(b_image_path.c_str());
  2261. success = false;
  2262. }
  2263. } else {
  2264. // Cleanup: delete B image, ignore errors.
  2265. unlink(b_vdex_path.c_str());
  2266. unlink(b_image_path.c_str());
  2267. success = false;
  2268. }
  2269. return success;
  2270. }
  2271. bool delete_odex(const char* apk_path, const char* instruction_set, const char* oat_dir) {
  2272. // Delete the oat/odex file.
  2273. char out_path[PKG_PATH_MAX];
  2274. if (!create_oat_out_path(apk_path, instruction_set, oat_dir,
  2275. /*is_secondary_dex*/false, out_path)) {
  2276. return false;
  2277. }
  2278. // In case of a permission failure report the issue. Otherwise just print a warning.
  2279. auto unlink_and_check = [](const char* path) -> bool {
  2280. int result = unlink(path);
  2281. if (result != 0) {
  2282. if (errno == EACCES || errno == EPERM) {
  2283. PLOG(ERROR) << "Could not unlink " << path;
  2284. return false;
  2285. }
  2286. PLOG(WARNING) << "Could not unlink " << path;
  2287. }
  2288. return true;
  2289. };
  2290. // Delete the oat/odex file.
  2291. bool return_value_oat = unlink_and_check(out_path);
  2292. // Derive and delete the app image.
  2293. bool return_value_art = unlink_and_check(create_image_filename(out_path).c_str());
  2294. // Derive and delete the vdex file.
  2295. bool return_value_vdex = unlink_and_check(create_vdex_filename(out_path).c_str());
  2296. // Report success.
  2297. return return_value_oat && return_value_art && return_value_vdex;
  2298. }
  2299. static bool is_absolute_path(const std::string& path) {
  2300. if (path.find('/') != 0 || path.find("..") != std::string::npos) {
  2301. LOG(ERROR) << "Invalid absolute path " << path;
  2302. return false;
  2303. } else {
  2304. return true;
  2305. }
  2306. }
  2307. static bool is_valid_instruction_set(const std::string& instruction_set) {
  2308. // TODO: add explicit whitelisting of instruction sets
  2309. if (instruction_set.find('/') != std::string::npos) {
  2310. LOG(ERROR) << "Invalid instruction set " << instruction_set;
  2311. return false;
  2312. } else {
  2313. return true;
  2314. }
  2315. }
  2316. bool calculate_oat_file_path_default(char path[PKG_PATH_MAX], const char *oat_dir,
  2317. const char *apk_path, const char *instruction_set) {
  2318. std::string oat_dir_ = oat_dir;
  2319. std::string apk_path_ = apk_path;
  2320. std::string instruction_set_ = instruction_set;
  2321. if (!is_absolute_path(oat_dir_)) return false;
  2322. if (!is_absolute_path(apk_path_)) return false;
  2323. if (!is_valid_instruction_set(instruction_set_)) return false;
  2324. std::string::size_type end = apk_path_.rfind('.');
  2325. std::string::size_type start = apk_path_.rfind('/', end);
  2326. if (end == std::string::npos || start == std::string::npos) {
  2327. LOG(ERROR) << "Invalid apk_path " << apk_path_;
  2328. return false;
  2329. }
  2330. std::string res_ = oat_dir_ + '/' + instruction_set + '/'
  2331. + apk_path_.substr(start + 1, end - start - 1) + ".odex";
  2332. const char* res = res_.c_str();
  2333. if (strlen(res) >= PKG_PATH_MAX) {
  2334. LOG(ERROR) << "Result too large";
  2335. return false;
  2336. } else {
  2337. strlcpy(path, res, PKG_PATH_MAX);
  2338. return true;
  2339. }
  2340. }
  2341. bool calculate_odex_file_path_default(char path[PKG_PATH_MAX], const char *apk_path,
  2342. const char *instruction_set) {
  2343. std::string apk_path_ = apk_path;
  2344. std::string instruction_set_ = instruction_set;
  2345. if (!is_absolute_path(apk_path_)) return false;
  2346. if (!is_valid_instruction_set(instruction_set_)) return false;
  2347. std::string::size_type end = apk_path_.rfind('.');
  2348. std::string::size_type start = apk_path_.rfind('/', end);
  2349. if (end == std::string::npos || start == std::string::npos) {
  2350. LOG(ERROR) << "Invalid apk_path " << apk_path_;
  2351. return false;
  2352. }
  2353. std::string oat_dir = apk_path_.substr(0, start + 1) + "oat";
  2354. return calculate_oat_file_path_default(path, oat_dir.c_str(), apk_path, instruction_set);
  2355. }
  2356. bool create_cache_path_default(char path[PKG_PATH_MAX], const char *src,
  2357. const char *instruction_set) {
  2358. std::string src_ = src;
  2359. std::string instruction_set_ = instruction_set;
  2360. if (!is_absolute_path(src_)) return false;
  2361. if (!is_valid_instruction_set(instruction_set_)) return false;
  2362. for (auto it = src_.begin() + 1; it < src_.end(); ++it) {
  2363. if (*it == '/') {
  2364. *it = '@';
  2365. }
  2366. }
  2367. std::string res_ = android_data_dir + DALVIK_CACHE + '/' + instruction_set_ + src_
  2368. + DALVIK_CACHE_POSTFIX;
  2369. const char* res = res_.c_str();
  2370. if (strlen(res) >= PKG_PATH_MAX) {
  2371. LOG(ERROR) << "Result too large";
  2372. return false;
  2373. } else {
  2374. strlcpy(path, res, PKG_PATH_MAX);
  2375. return true;
  2376. }
  2377. }
  2378. bool open_classpath_files(const std::string& classpath, std::vector<unique_fd>* apk_fds,
  2379. std::vector<std::string>* dex_locations) {
  2380. std::vector<std::string> classpaths_elems = base::Split(classpath, ":");
  2381. for (const std::string& elem : classpaths_elems) {
  2382. unique_fd fd(TEMP_FAILURE_RETRY(open(elem.c_str(), O_RDONLY)));
  2383. if (fd < 0) {
  2384. PLOG(ERROR) << "Could not open classpath elem " << elem;
  2385. return false;
  2386. } else {
  2387. apk_fds->push_back(std::move(fd));
  2388. dex_locations->push_back(elem);
  2389. }
  2390. }
  2391. return true;
  2392. }
  2393. static bool create_app_profile_snapshot(int32_t app_id,
  2394. const std::string& package_name,
  2395. const std::string& profile_name,
  2396. const std::string& classpath) {
  2397. int app_shared_gid = multiuser_get_shared_gid(/*user_id*/ 0, app_id);
  2398. unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
  2399. if (snapshot_fd < 0) {
  2400. return false;
  2401. }
  2402. std::vector<unique_fd> profiles_fd;
  2403. unique_fd reference_profile_fd;
  2404. open_profile_files(app_shared_gid, package_name, profile_name, /*is_secondary_dex*/ false,
  2405. &profiles_fd, &reference_profile_fd);
  2406. if (profiles_fd.empty() || (reference_profile_fd.get() < 0)) {
  2407. return false;
  2408. }
  2409. profiles_fd.push_back(std::move(reference_profile_fd));
  2410. // Open the class paths elements. These will be used to filter out profile data that does
  2411. // not belong to the classpath during merge.
  2412. std::vector<unique_fd> apk_fds;
  2413. std::vector<std::string> dex_locations;
  2414. if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
  2415. return false;
  2416. }
  2417. RunProfman args;
  2418. args.SetupMerge(profiles_fd, snapshot_fd, apk_fds, dex_locations);
  2419. pid_t pid = fork();
  2420. if (pid == 0) {
  2421. /* child -- drop privileges before continuing */
  2422. drop_capabilities(app_shared_gid);
  2423. args.Exec();
  2424. }
  2425. /* parent */
  2426. int return_code = wait_child(pid);
  2427. if (!WIFEXITED(return_code)) {
  2428. LOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
  2429. return false;
  2430. }
  2431. return true;
  2432. }
  2433. static bool create_boot_image_profile_snapshot(const std::string& package_name,
  2434. const std::string& profile_name,
  2435. const std::string& classpath) {
  2436. // The reference profile directory for the android package might not be prepared. Do it now.
  2437. const std::string ref_profile_dir =
  2438. create_primary_reference_profile_package_dir_path(package_name);
  2439. if (fs_prepare_dir(ref_profile_dir.c_str(), 0770, AID_SYSTEM, AID_SYSTEM) != 0) {
  2440. PLOG(ERROR) << "Failed to prepare " << ref_profile_dir;
  2441. return false;
  2442. }
  2443. // Return false for empty class path since it may otherwise return true below if profiles is
  2444. // empty.
  2445. if (classpath.empty()) {
  2446. PLOG(ERROR) << "Class path is empty";
  2447. return false;
  2448. }
  2449. // Open and create the snapshot profile.
  2450. unique_fd snapshot_fd = open_spnashot_profile(AID_SYSTEM, package_name, profile_name);
  2451. // Collect all non empty profiles.
  2452. // The collection will traverse all applications profiles and find the non empty files.
  2453. // This has the potential of inspecting a large number of files and directories (depending
  2454. // on the number of applications and users). So there is a slight increase in the chance
  2455. // to get get occasionally I/O errors (e.g. for opening the file). When that happens do not
  2456. // fail the snapshot and aggregate whatever profile we could open.
  2457. //
  2458. // The profile snapshot is a best effort based on available data it's ok if some data
  2459. // from some apps is missing. It will be counter productive for the snapshot to fail
  2460. // because we could not open or read some of the files.
  2461. std::vector<std::string> profiles;
  2462. if (!collect_profiles(&profiles)) {
  2463. LOG(WARNING) << "There were errors while collecting the profiles for the boot image.";
  2464. }
  2465. // If we have no profiles return early.
  2466. if (profiles.empty()) {
  2467. return true;
  2468. }
  2469. // Open the classpath elements. These will be used to filter out profile data that does
  2470. // not belong to the classpath during merge.
  2471. std::vector<unique_fd> apk_fds;
  2472. std::vector<std::string> dex_locations;
  2473. if (!open_classpath_files(classpath, &apk_fds, &dex_locations)) {
  2474. return false;
  2475. }
  2476. // If we could not open any files from the classpath return an error.
  2477. if (apk_fds.empty()) {
  2478. LOG(ERROR) << "Could not open any of the classpath elements.";
  2479. return false;
  2480. }
  2481. // Aggregate the profiles in batches of kAggregationBatchSize.
  2482. // We do this to avoid opening a huge a amount of files.
  2483. static constexpr size_t kAggregationBatchSize = 10;
  2484. std::vector<unique_fd> profiles_fd;
  2485. for (size_t i = 0; i < profiles.size(); ) {
  2486. for (size_t k = 0; k < kAggregationBatchSize && i < profiles.size(); k++, i++) {
  2487. unique_fd fd = open_profile(AID_SYSTEM, profiles[i], O_RDONLY);
  2488. if (fd.get() >= 0) {
  2489. profiles_fd.push_back(std::move(fd));
  2490. }
  2491. }
  2492. RunProfman args;
  2493. args.SetupMerge(profiles_fd,
  2494. snapshot_fd,
  2495. apk_fds,
  2496. dex_locations,
  2497. /*store_aggregation_counters=*/true);
  2498. pid_t pid = fork();
  2499. if (pid == 0) {
  2500. /* child -- drop privileges before continuing */
  2501. drop_capabilities(AID_SYSTEM);
  2502. // The introduction of new access flags into boot jars causes them to
  2503. // fail dex file verification.
  2504. args.Exec();
  2505. }
  2506. /* parent */
  2507. int return_code = wait_child(pid);
  2508. if (!WIFEXITED(return_code)) {
  2509. PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
  2510. return false;
  2511. }
  2512. return true;
  2513. }
  2514. return true;
  2515. }
  2516. bool create_profile_snapshot(int32_t app_id, const std::string& package_name,
  2517. const std::string& profile_name, const std::string& classpath) {
  2518. if (app_id == -1) {
  2519. return create_boot_image_profile_snapshot(package_name, profile_name, classpath);
  2520. } else {
  2521. return create_app_profile_snapshot(app_id, package_name, profile_name, classpath);
  2522. }
  2523. }
  2524. bool prepare_app_profile(const std::string& package_name,
  2525. userid_t user_id,
  2526. appid_t app_id,
  2527. const std::string& profile_name,
  2528. const std::string& code_path,
  2529. const std::unique_ptr<std::string>& dex_metadata) {
  2530. // Prepare the current profile.
  2531. std::string cur_profile = create_current_profile_path(user_id, package_name, profile_name,
  2532. /*is_secondary_dex*/ false);
  2533. uid_t uid = multiuser_get_uid(user_id, app_id);
  2534. if (fs_prepare_file_strict(cur_profile.c_str(), 0600, uid, uid) != 0) {
  2535. PLOG(ERROR) << "Failed to prepare " << cur_profile;
  2536. return false;
  2537. }
  2538. // Check if we need to install the profile from the dex metadata.
  2539. if (dex_metadata == nullptr) {
  2540. return true;
  2541. }
  2542. // We have a dex metdata. Merge the profile into the reference profile.
  2543. unique_fd ref_profile_fd = open_reference_profile(uid, package_name, profile_name,
  2544. /*read_write*/ true, /*is_secondary_dex*/ false);
  2545. unique_fd dex_metadata_fd(TEMP_FAILURE_RETRY(
  2546. open(dex_metadata->c_str(), O_RDONLY | O_NOFOLLOW)));
  2547. unique_fd apk_fd(TEMP_FAILURE_RETRY(open(code_path.c_str(), O_RDONLY | O_NOFOLLOW)));
  2548. if (apk_fd < 0) {
  2549. PLOG(ERROR) << "Could not open code path " << code_path;
  2550. return false;
  2551. }
  2552. RunProfman args;
  2553. args.SetupCopyAndUpdate(std::move(dex_metadata_fd),
  2554. std::move(ref_profile_fd),
  2555. std::move(apk_fd),
  2556. code_path);
  2557. pid_t pid = fork();
  2558. if (pid == 0) {
  2559. /* child -- drop privileges before continuing */
  2560. gid_t app_shared_gid = multiuser_get_shared_gid(user_id, app_id);
  2561. drop_capabilities(app_shared_gid);
  2562. // The copy and update takes ownership over the fds.
  2563. args.Exec();
  2564. }
  2565. /* parent */
  2566. int return_code = wait_child(pid);
  2567. if (!WIFEXITED(return_code)) {
  2568. PLOG(WARNING) << "profman failed for " << package_name << ":" << profile_name;
  2569. return false;
  2570. }
  2571. return true;
  2572. }
  2573. } // namespace installd
  2574. } // namespace android