request.rs 159 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915
  1. //! # [`BuildRequest`] - the core of the build process
  2. //!
  3. //! The [`BuildRequest`] object is the core of the build process. It contains all the resolved arguments
  4. //! flowing in from the CLI, dioxus.toml, env vars, and the workspace.
  5. //!
  6. //! Every BuildRequest is tied to a given workspace and BuildArgs. For simplicity's sake, the BuildArgs
  7. //! struct is used to represent the CLI arguments and all other configuration is basically just
  8. //! extra CLI arguments, but in a configuration format.
  9. //!
  10. //! When [`BuildRequest::build`] is called, it will prepare its work directory in the target folder
  11. //! and then start running the build process. A [`BuildContext`] is required to customize this
  12. //! build process, containing a channel for progress updates and the build mode.
  13. //!
  14. //! The [`BuildMode`] is extremely important since it influences how the build is performed. Most
  15. //! "normal" builds just use [`BuildMode::Base`], but we also support [`BuildMode::Fat`] and
  16. //! [`BuildMode::Thin`]. These builds are used together to power the hot-patching and fast-linking
  17. //! engine.
  18. //! - BuildMode::Base: A normal build generated using `cargo rustc`
  19. //! - BuildMode::Fat: A "fat" build where all dependency rlibs are merged into a static library
  20. //! - BuildMode::Thin: A "thin" build that dynamically links against the artifacts produced by the "fat" build
  21. //!
  22. //! The BuildRequest is also responsible for writing the final build artifacts to disk. This includes
  23. //!
  24. //! - Writing the executable
  25. //! - Processing assets from the artifact
  26. //! - Writing any metadata or configuration files (Info.plist, AndroidManifest.xml)
  27. //! - Bundle splitting (for wasm) and wasm-bindgen
  28. //!
  29. //! In some cases, the BuildRequest also handles the linking of the final executable. Specifically,
  30. //! - For Android, we use `dx` as an opaque linker to dynamically find the true android linker
  31. //! - For hotpatching, the CLI manually links the final executable with a stub file
  32. //!
  33. //! ## Build formats:
  34. //!
  35. //! We support building for the most popular platforms:
  36. //! - Web via wasm-bindgen
  37. //! - macOS via app-bundle
  38. //! - iOS via app-bundle
  39. //! - Android via gradle
  40. //! - Linux via app-image
  41. //! - Windows via exe, msi/msix
  42. //!
  43. //! Note that we are missing some setups that we *should* support:
  44. //! - PWAs, WebWorkers, ServiceWorkers
  45. //! - Web Extensions
  46. //! - Linux via flatpak/snap
  47. //!
  48. //! There are some less popular formats that we might want to support eventually:
  49. //! - TVOS, watchOS
  50. //! - OpenHarmony
  51. //!
  52. //! Also, some deploy platforms have their own bespoke formats:
  53. //! - Cloudflare workers
  54. //! - AWS Lambda
  55. //!
  56. //! Currently, we defer most of our deploy-based bundling to Tauri bundle, though we should migrate
  57. //! to just bundling everything ourselves. This would require us to implement code-signing which
  58. //! is a bit of a pain, but fortunately a solved process (https://github.com/rust-mobile/xbuild).
  59. //!
  60. //! ## Build Structure
  61. //!
  62. //! Builds generally follow the same structure everywhere:
  63. //! - A main executable
  64. //! - Sidecars (alternate entrypoints, framewrok plugins, etc)
  65. //! - Assets (images, fonts, etc)
  66. //! - Metadata (Info.plist, AndroidManifest.xml)
  67. //! - Glue code (java, kotlin, javascript etc)
  68. //! - Entitlements for code-signing and verification
  69. //!
  70. //! We need to be careful to not try and put a "round peg in a square hole," but most platforms follow
  71. //! the same pattern.
  72. //!
  73. //! As such, we try to assemble a build directory that's somewhat sensible:
  74. //! - A main "staging" dir for a given app
  75. //! - Per-profile dirs (debug/release)
  76. //! - A platform dir (ie web/desktop/android/ios)
  77. //! - The "bundle" dir which is basically the `.app` format or `wwww` dir.
  78. //! - The "executable" dir where the main exe is housed
  79. //! - The "assets" dir where the assets are housed
  80. //! - The "meta" dir where stuff like Info.plist, AndroidManifest.xml, etc are housed
  81. //!
  82. //! There's also some "quirky" folders that need to be stable between builds but don't influence the
  83. //! bundle itself:
  84. //! - session_cache_dir which stores stuff like window position
  85. //!
  86. //! ### Web:
  87. //!
  88. //! Create a folder that is somewhat similar to an app-image (exe + asset)
  89. //! The server is dropped into the `web` folder, even if there's no `public` folder.
  90. //! If there's no server (SPA), we still use the `web` folder, but it only contains the
  91. //! public folder.
  92. //!
  93. //! ```
  94. //! web/
  95. //! server
  96. //! assets/
  97. //! public/
  98. //! index.html
  99. //! wasm/
  100. //! app.wasm
  101. //! glue.js
  102. //! snippets/
  103. //! ...
  104. //! assets/
  105. //! logo.png
  106. //! ```
  107. //!
  108. //! ### Linux:
  109. //!
  110. //! https://docs.appimage.org/reference/appdir.html#ref-appdir
  111. //! current_exe.join("Assets")
  112. //! ```
  113. //! app.appimage/
  114. //! AppRun
  115. //! app.desktop
  116. //! package.json
  117. //! assets/
  118. //! logo.png
  119. //! ```
  120. //!
  121. //! ### Macos
  122. //!
  123. //! We simply use the macos format where binaries are in `Contents/MacOS` and assets are in `Contents/Resources`
  124. //! We put assets in an assets dir such that it generally matches every other platform and we can
  125. //! output `/assets/blah` from manganis.
  126. //! ```
  127. //! App.app/
  128. //! Contents/
  129. //! Info.plist
  130. //! MacOS/
  131. //! Frameworks/
  132. //! Resources/
  133. //! assets/
  134. //! blah.icns
  135. //! blah.png
  136. //! CodeResources
  137. //! _CodeSignature/
  138. //! ```
  139. //!
  140. //! ### iOS
  141. //!
  142. //! Not the same as mac! ios apps are a bit "flattened" in comparison. simpler format, presumably
  143. //! since most ios apps don't ship frameworks/plugins and such.
  144. //!
  145. //! todo(jon): include the signing and entitlements in this format diagram.
  146. //! ```
  147. //! App.app/
  148. //! main
  149. //! assets/
  150. //! ```
  151. //!
  152. //! ### Android:
  153. //!
  154. //! Currently we need to generate a `src` type structure, not a pre-packaged apk structure, since
  155. //! we need to compile kotlin and java. This pushes us into using gradle and following a structure
  156. //! similar to that of cargo mobile2. Eventually I'd like to slim this down (drop buildSrc) and
  157. //! drive the kotlin build ourselves. This would let us drop gradle (yay! no plugins!) but requires
  158. //! us to manage dependencies (like kotlinc) ourselves (yuck!).
  159. //!
  160. //! https://github.com/WanghongLin/miscellaneous/blob/master/tools/build-apk-manually.sh
  161. //!
  162. //! Unfortunately, it seems that while we can drop the `android` build plugin, we still will need
  163. //! gradle since kotlin is basically gradle-only.
  164. //!
  165. //! Pre-build:
  166. //! ```
  167. //! app.apk/
  168. //! .gradle
  169. //! app/
  170. //! src/
  171. //! main/
  172. //! assets/
  173. //! jniLibs/
  174. //! java/
  175. //! kotlin/
  176. //! res/
  177. //! AndroidManifest.xml
  178. //! build.gradle.kts
  179. //! proguard-rules.pro
  180. //! buildSrc/
  181. //! build.gradle.kts
  182. //! src/
  183. //! main/
  184. //! kotlin/
  185. //! BuildTask.kt
  186. //! build.gradle.kts
  187. //! gradle.properties
  188. //! gradlew
  189. //! gradlew.bat
  190. //! settings.gradle
  191. //! ```
  192. //!
  193. //! Final build:
  194. //! ```
  195. //! app.apk/
  196. //! AndroidManifest.xml
  197. //! classes.dex
  198. //! assets/
  199. //! logo.png
  200. //! lib/
  201. //! armeabi-v7a/
  202. //! libmyapp.so
  203. //! arm64-v8a/
  204. //! libmyapp.so
  205. //! ```
  206. //! Notice that we *could* feasibly build this ourselves :)
  207. //!
  208. //! ### Windows:
  209. //! <https://superuser.com/questions/749447/creating-a-single-file-executable-from-a-directory-in-windows>
  210. //! Windows does not provide an AppImage format, so instead we're going build the same folder
  211. //! structure as an AppImage, but when distributing, we'll create a .exe that embeds the resources
  212. //! as an embedded .zip file. When the app runs, it will implicitly unzip its resources into the
  213. //! Program Files folder. Any subsequent launches of the parent .exe will simply call the AppRun.exe
  214. //! entrypoint in the associated Program Files folder.
  215. //!
  216. //! This is, in essence, the same as an installer, so we might eventually just support something like msi/msix
  217. //! which functionally do the same thing but with a sleeker UI.
  218. //!
  219. //! This means no installers are required and we can bake an updater into the host exe.
  220. //!
  221. //! ## Handling asset lookups:
  222. //! current_exe.join("assets")
  223. //! ```
  224. //! app.appimage/
  225. //! main.exe
  226. //! main.desktop
  227. //! package.json
  228. //! assets/
  229. //! logo.png
  230. //! ```
  231. //!
  232. //! Since we support just a few locations, we could just search for the first that exists
  233. //! - usr
  234. //! - ../Resources
  235. //! - assets
  236. //! - Assets
  237. //! - $cwd/assets
  238. //!
  239. //! ```
  240. //! assets::root() ->
  241. //! mac -> ../Resources/
  242. //! ios -> ../Resources/
  243. //! android -> assets/
  244. //! server -> assets/
  245. //! liveview -> assets/
  246. //! web -> /assets/
  247. //! root().join(bundled)
  248. //! ```
  249. //!
  250. //! Every dioxus app can have an optional server executable which will influence the final bundle.
  251. //! This is built in parallel with the app executable during the `build` phase and the progres/status
  252. //! of the build is aggregated.
  253. //!
  254. //! The server will *always* be dropped into the `web` folder since it is considered "web" in nature,
  255. //! and will likely need to be combined with the public dir to be useful.
  256. //!
  257. //! We do our best to assemble read-to-go bundles here, such that the "bundle" step for each platform
  258. //! can just use the build dir
  259. //!
  260. //! When we write the AppBundle to a folder, it'll contain each bundle for each platform under the app's name:
  261. //! ```
  262. //! dog-app/
  263. //! build/
  264. //! web/
  265. //! server.exe
  266. //! assets/
  267. //! some-secret-asset.txt (a server-side asset)
  268. //! public/
  269. //! index.html
  270. //! assets/
  271. //! logo.png
  272. //! desktop/
  273. //! App.app
  274. //! App.appimage
  275. //! App.exe
  276. //! server/
  277. //! server
  278. //! assets/
  279. //! some-secret-asset.txt (a server-side asset)
  280. //! ios/
  281. //! App.app
  282. //! App.ipa
  283. //! android/
  284. //! App.apk
  285. //! bundle/
  286. //! build.json
  287. //! Desktop.app
  288. //! Mobile_x64.ipa
  289. //! Mobile_arm64.ipa
  290. //! Mobile_rosetta.ipa
  291. //! web.appimage
  292. //! web/
  293. //! server.exe
  294. //! assets/
  295. //! some-secret-asset.txt
  296. //! public/
  297. //! index.html
  298. //! assets/
  299. //! logo.png
  300. //! style.css
  301. //! ```
  302. //!
  303. //! When deploying, the build.json file will provide all the metadata that dx-deploy will use to
  304. //! push the app to stores, set up infra, manage versions, etc.
  305. //!
  306. //! The format of each build will follow the name plus some metadata such that when distributing you
  307. //! can easily trim off the metadata.
  308. //!
  309. //! The idea here is that we can run any of the programs in the same way that they're deployed.
  310. //!
  311. //! ## Bundle structure links
  312. //! - apple: <https>://developer.apple.com/documentation/bundleresources/placing_content_in_a_bundle>
  313. //! - appimage: <https>://docs.appimage.org/packaging-guide/manual.html#ref-manual>
  314. //!
  315. //! ## Extra links
  316. //! - xbuild: <https://github.com/rust-mobile/xbuild/blob/master/xbuild/src/command/build.rs>
  317. use crate::{
  318. AndroidTools, BuildContext, DioxusConfig, Error, LinkAction, Platform, Result, RustcArgs,
  319. TargetArgs, TraceSrc, WasmBindgen, WasmOptConfig, Workspace, DX_RUSTC_WRAPPER_ENV_VAR,
  320. };
  321. use anyhow::Context;
  322. use dioxus_cli_config::format_base_path_meta_element;
  323. use dioxus_cli_config::{APP_TITLE_ENV, ASSET_ROOT_ENV};
  324. use dioxus_cli_opt::{process_file_to, AssetManifest};
  325. use itertools::Itertools;
  326. use krates::{cm::TargetKind, NodeId};
  327. use manganis::{AssetOptions, JsAssetOptions};
  328. use rayon::prelude::{IntoParallelRefIterator, ParallelIterator};
  329. use serde::{Deserialize, Serialize};
  330. use std::{
  331. collections::{BTreeMap, HashSet},
  332. io::Write,
  333. path::{Path, PathBuf},
  334. process::Stdio,
  335. sync::{
  336. atomic::{AtomicUsize, Ordering},
  337. Arc,
  338. },
  339. time::{SystemTime, UNIX_EPOCH},
  340. };
  341. use target_lexicon::{OperatingSystem, Triple};
  342. use tempfile::{NamedTempFile, TempDir};
  343. use tokio::{io::AsyncBufReadExt, process::Command};
  344. use toml_edit::Item;
  345. use uuid::Uuid;
  346. use super::HotpatchModuleCache;
  347. /// This struct is used to plan the build process.
  348. ///
  349. /// The point here is to be able to take in the user's config from the CLI without modifying the
  350. /// arguments in place. Creating a buildplan "resolves" their config into a build plan that can be
  351. /// introspected. For example, the users might not specify a "Triple" in the CLI but the triple will
  352. /// be guaranteed to be resolved here.
  353. ///
  354. /// Creating a buildplan also lets us introspect build requests and modularize our build process.
  355. /// This will, however, lead to duplicate fields between the CLI and the build engine. This is fine
  356. /// since we have the freedom to evolve the schema internally without breaking the API.
  357. ///
  358. /// All updates from the build will be sent on a global "BuildProgress" channel.
  359. #[derive(Clone)]
  360. pub(crate) struct BuildRequest {
  361. pub(crate) workspace: Arc<Workspace>,
  362. pub(crate) config: DioxusConfig,
  363. pub(crate) crate_package: NodeId,
  364. pub(crate) crate_target: krates::cm::Target,
  365. pub(crate) profile: String,
  366. pub(crate) release: bool,
  367. pub(crate) platform: Platform,
  368. pub(crate) enabled_platforms: Vec<Platform>,
  369. pub(crate) triple: Triple,
  370. pub(crate) device: bool,
  371. pub(crate) package: String,
  372. pub(crate) features: Vec<String>,
  373. pub(crate) extra_cargo_args: Vec<String>,
  374. pub(crate) extra_rustc_args: Vec<String>,
  375. pub(crate) no_default_features: bool,
  376. pub(crate) custom_target_dir: Option<PathBuf>,
  377. pub(crate) skip_assets: bool,
  378. pub(crate) wasm_split: bool,
  379. pub(crate) debug_symbols: bool,
  380. pub(crate) inject_loading_scripts: bool,
  381. pub(crate) custom_linker: Option<PathBuf>,
  382. pub(crate) session_cache_dir: Arc<TempDir>,
  383. pub(crate) link_args_file: Arc<NamedTempFile>,
  384. pub(crate) link_err_file: Arc<NamedTempFile>,
  385. pub(crate) rustc_wrapper_args_file: Arc<NamedTempFile>,
  386. }
  387. /// dx can produce different "modes" of a build. A "regular" build is a "base" build. The Fat and Thin
  388. /// modes are used together to achieve binary patching and linking.
  389. ///
  390. /// Guide:
  391. /// ----------
  392. /// - Base: A normal build generated using `cargo rustc`, intended for production use cases
  393. ///
  394. /// - Fat: A "fat" build with -Wl,-all_load and no_dead_strip, keeping *every* symbol in the binary.
  395. /// Intended for development for larger up-front builds with faster link times and the ability
  396. /// to binary patch the final binary. On WASM, this also forces wasm-bindgen to generate all
  397. /// JS-WASM bindings, saving us the need to re-wasmbindgen the final binary.
  398. ///
  399. /// - Thin: A "thin" build that dynamically links against the dependencies produced by the "fat" build.
  400. /// This is generated by calling rustc *directly* and might be more fragile to construct, but
  401. /// generates *much* faster than a regular base or fat build.
  402. #[derive(Clone, Debug, PartialEq)]
  403. pub enum BuildMode {
  404. /// A normal build generated using `cargo rustc`
  405. Base,
  406. /// A "Fat" build generated with cargo rustc and dx as a custom linker without -Wl,-dead-strip
  407. Fat,
  408. /// A "thin" build generated with `rustc` directly and dx as a custom linker
  409. Thin {
  410. rustc_args: RustcArgs,
  411. changed_files: Vec<PathBuf>,
  412. aslr_reference: u64,
  413. cache: Arc<HotpatchModuleCache>,
  414. },
  415. }
  416. /// The end result of a build.
  417. ///
  418. /// Contains the final asset manifest, the executable, and metadata about the build.
  419. /// Note that the `exe` might be stale and/or overwritten by the time you read it!
  420. ///
  421. /// The patch cache is only populated on fat builds and then used for thin builds (see `BuildMode::Thin`).
  422. #[derive(Clone, Debug)]
  423. pub struct BuildArtifacts {
  424. pub(crate) platform: Platform,
  425. pub(crate) exe: PathBuf,
  426. pub(crate) direct_rustc: RustcArgs,
  427. pub(crate) time_start: SystemTime,
  428. pub(crate) time_end: SystemTime,
  429. pub(crate) assets: AssetManifest,
  430. pub(crate) mode: BuildMode,
  431. pub(crate) patch_cache: Option<Arc<HotpatchModuleCache>>,
  432. }
  433. pub(crate) static PROFILE_WASM: &str = "wasm-dev";
  434. pub(crate) static PROFILE_ANDROID: &str = "android-dev";
  435. pub(crate) static PROFILE_SERVER: &str = "server-dev";
  436. impl BuildRequest {
  437. /// Create a new build request.
  438. ///
  439. /// This method consolidates various inputs into a single source of truth. It combines:
  440. /// - Command-line arguments provided by the user.
  441. /// - The crate's `Cargo.toml`.
  442. /// - The `dioxus.toml` configuration file.
  443. /// - User-specific CLI settings.
  444. /// - The workspace metadata.
  445. /// - Host-specific details (e.g., Android tools, installed frameworks).
  446. /// - The intended target platform.
  447. ///
  448. /// Fields may be duplicated from the inputs to allow for autodetection and resolution.
  449. ///
  450. /// Autodetection is performed for unspecified fields where possible.
  451. ///
  452. /// Note: Build requests are typically created only when the CLI is invoked or when significant
  453. /// changes are detected in the `Cargo.toml` (e.g., features added or removed).
  454. pub(crate) async fn new(args: &TargetArgs, workspace: Arc<Workspace>) -> Result<Self> {
  455. let crate_package = workspace.find_main_package(args.package.clone())?;
  456. let config = workspace
  457. .load_dioxus_config(crate_package)?
  458. .unwrap_or_default();
  459. let target_kind = match args.example.is_some() {
  460. true => TargetKind::Example,
  461. false => TargetKind::Bin,
  462. };
  463. let main_package = &workspace.krates[crate_package];
  464. let target_name = args
  465. .example
  466. .clone()
  467. .or(args.bin.clone())
  468. .or_else(|| {
  469. if let Some(default_run) = &main_package.default_run {
  470. return Some(default_run.to_string());
  471. }
  472. let bin_count = main_package
  473. .targets
  474. .iter()
  475. .filter(|x| x.kind.contains(&target_kind))
  476. .count();
  477. if bin_count != 1 {
  478. return None;
  479. }
  480. main_package.targets.iter().find_map(|x| {
  481. if x.kind.contains(&target_kind) {
  482. Some(x.name.clone())
  483. } else {
  484. None
  485. }
  486. })
  487. })
  488. .unwrap_or(workspace.krates[crate_package].name.clone());
  489. let crate_target = main_package
  490. .targets
  491. .iter()
  492. .find(|target| {
  493. target_name == target.name.as_str() && target.kind.contains(&target_kind)
  494. })
  495. .with_context(|| {
  496. let target_of_kind = |kind|-> String {
  497. let filtered_packages = main_package
  498. .targets
  499. .iter()
  500. .filter_map(|target| {
  501. target.kind.contains(kind).then_some(target.name.as_str())
  502. }).collect::<Vec<_>>();
  503. filtered_packages.join(", ")};
  504. if let Some(example) = &args.example {
  505. let examples = target_of_kind(&TargetKind::Example);
  506. format!("Failed to find example {example}. \nAvailable examples are:\n{}", examples)
  507. } else if let Some(bin) = &args.bin {
  508. let binaries = target_of_kind(&TargetKind::Bin);
  509. format!("Failed to find binary {bin}. \nAvailable binaries are:\n{}", binaries)
  510. } else {
  511. format!("Failed to find target {target_name}. \nIt looks like you are trying to build dioxus in a library crate. \
  512. You either need to run dx from inside a binary crate or build a specific example with the `--example` flag. \
  513. Available examples are:\n{}", target_of_kind(&TargetKind::Example))
  514. }
  515. })?
  516. .clone();
  517. // The crate might enable multiple platforms or no platforms at
  518. // We collect all the platforms it enables first and then select based on the --platform arg
  519. let enabled_platforms =
  520. Self::enabled_cargo_toml_platforms(main_package, args.no_default_features);
  521. let using_dioxus_explicitly = main_package
  522. .dependencies
  523. .iter()
  524. .any(|dep| dep.name == "dioxus");
  525. let mut features = args.features.clone();
  526. let mut no_default_features = args.no_default_features;
  527. let platform: Platform = match args.platform {
  528. Some(platform) => match enabled_platforms.len() {
  529. 0 => platform,
  530. // The user passed --platform XYZ but already has `default = ["ABC"]` in their Cargo.toml or dioxus = { features = ["abc"] }
  531. // We want to strip out the default platform and use the one they passed, setting no-default-features
  532. _ => {
  533. features.extend(Self::platformless_features(main_package));
  534. no_default_features = true;
  535. platform
  536. }
  537. },
  538. None if !using_dioxus_explicitly => Platform::autodetect_from_cargo_feature("desktop").unwrap(),
  539. None => match enabled_platforms.len() {
  540. 0 => return Err(anyhow::anyhow!("No platform specified and no platform marked as default in Cargo.toml. Try specifying a platform with `--platform`").into()),
  541. 1 => enabled_platforms[0],
  542. _ => {
  543. return Err(anyhow::anyhow!(
  544. "Multiple platforms enabled in Cargo.toml. Please specify a platform with `--platform` or set a default platform in Cargo.toml"
  545. )
  546. .into())
  547. }
  548. },
  549. };
  550. // Add any features required to turn on the client
  551. if using_dioxus_explicitly {
  552. features.push(Self::feature_for_platform(main_package, platform));
  553. }
  554. // Set the profile of the build if it's not already set
  555. // This is mostly used for isolation of builds (preventing thrashing) but also useful to have multiple performance profiles
  556. // We might want to move some of these profiles into dioxus.toml and make them "virtual".
  557. let profile = match args.profile.clone() {
  558. Some(profile) => profile,
  559. None if args.release => "release".to_string(),
  560. None => match platform {
  561. Platform::Android => PROFILE_ANDROID.to_string(),
  562. Platform::Web => PROFILE_WASM.to_string(),
  563. Platform::Server => PROFILE_SERVER.to_string(),
  564. _ => "dev".to_string(),
  565. },
  566. };
  567. // Determining release mode is based on the profile, actually, so we need to check that
  568. let release = workspace.is_release_profile(&profile);
  569. // Determine the --package we'll pass to cargo.
  570. // todo: I think this might be wrong - we don't want to use main_package necessarily...
  571. let package = args
  572. .package
  573. .clone()
  574. .unwrap_or_else(|| main_package.name.clone());
  575. // We usually use the simulator unless --device is passed *or* a device is detected by probing.
  576. // For now, though, since we don't have probing, it just defaults to false
  577. // Tools like xcrun/adb can detect devices
  578. let device = args.device.unwrap_or(false);
  579. // We want a real triple to build with, so we'll autodetect it if it's not provided
  580. // The triple ends up being a source of truth for us later hence all this work to figure it out
  581. let triple = match args.target.clone() {
  582. Some(target) => target,
  583. None => match platform {
  584. // Generally just use the host's triple for native executables unless specified otherwise
  585. Platform::MacOS
  586. | Platform::Windows
  587. | Platform::Linux
  588. | Platform::Server
  589. | Platform::Liveview => target_lexicon::HOST,
  590. // We currently assume unknown-unknown for web, but we might want to eventually
  591. // support emscripten
  592. Platform::Web => "wasm32-unknown-unknown".parse().unwrap(),
  593. // For iOS we should prefer the actual architecture for the simulator, but in lieu of actually
  594. // figuring that out, we'll assume aarch64 on m-series and x86_64 otherwise
  595. Platform::Ios => {
  596. // use the host's architecture and sim if --device is passed
  597. use target_lexicon::{Architecture, HOST};
  598. match HOST.architecture {
  599. Architecture::Aarch64(_) if device => "aarch64-apple-ios".parse().unwrap(),
  600. Architecture::Aarch64(_) => "aarch64-apple-ios-sim".parse().unwrap(),
  601. _ if device => "x86_64-apple-ios".parse().unwrap(),
  602. _ => "x86_64-apple-ios-sim".parse().unwrap(),
  603. }
  604. }
  605. // Same idea with android but we figure out the connected device using adb
  606. Platform::Android => {
  607. workspace
  608. .android_tools()?
  609. .autodetect_android_device_triple()
  610. .await
  611. }
  612. },
  613. };
  614. let custom_linker = if platform == Platform::Android {
  615. Some(workspace.android_tools()?.android_cc(&triple))
  616. } else {
  617. None
  618. };
  619. // Set up some tempfiles so we can do some IPC between us and the linker/rustc wrapper (which is occasionally us!)
  620. let link_args_file = Arc::new(
  621. NamedTempFile::with_suffix(".txt")
  622. .context("Failed to create temporary file for linker args")?,
  623. );
  624. let link_err_file = Arc::new(
  625. NamedTempFile::with_suffix(".txt")
  626. .context("Failed to create temporary file for linker args")?,
  627. );
  628. let rustc_wrapper_args_file = Arc::new(
  629. NamedTempFile::with_suffix(".json")
  630. .context("Failed to create temporary file for rustc wrapper args")?,
  631. );
  632. let session_cache_dir = Arc::new(
  633. TempDir::new().context("Failed to create temporary directory for session cache")?,
  634. );
  635. let extra_rustc_args = shell_words::split(&args.rustc_args.clone().unwrap_or_default())
  636. .context("Failed to parse rustc args")?;
  637. let extra_cargo_args = shell_words::split(&args.cargo_args.clone().unwrap_or_default())
  638. .context("Failed to parse cargo args")?;
  639. tracing::debug!(
  640. r#"Log Files:
  641. • link_args_file: {},
  642. • link_err_file: {},
  643. • rustc_wrapper_args_file: {},
  644. • session_cache_dir: {}"#,
  645. link_args_file.path().display(),
  646. link_err_file.path().display(),
  647. rustc_wrapper_args_file.path().display(),
  648. session_cache_dir.path().display(),
  649. );
  650. Ok(Self {
  651. platform,
  652. features,
  653. no_default_features,
  654. crate_package,
  655. crate_target,
  656. profile,
  657. triple,
  658. device,
  659. workspace,
  660. config,
  661. enabled_platforms,
  662. custom_target_dir: None,
  663. custom_linker,
  664. link_args_file,
  665. link_err_file,
  666. session_cache_dir,
  667. rustc_wrapper_args_file,
  668. extra_rustc_args,
  669. extra_cargo_args,
  670. release,
  671. package,
  672. skip_assets: args.skip_assets,
  673. wasm_split: args.wasm_split,
  674. debug_symbols: args.debug_symbols,
  675. inject_loading_scripts: args.inject_loading_scripts,
  676. })
  677. }
  678. pub(crate) async fn build(&self, ctx: &BuildContext) -> Result<BuildArtifacts> {
  679. // If we forget to do this, then we won't get the linker args since rust skips the full build
  680. // We need to make sure to not react to this though, so the filemap must cache it
  681. _ = self.bust_fingerprint(ctx);
  682. // Run the cargo build to produce our artifacts
  683. let mut artifacts = self.cargo_build(ctx).await?;
  684. // Write the build artifacts to the bundle on the disk
  685. match &ctx.mode {
  686. BuildMode::Thin {
  687. aslr_reference,
  688. cache,
  689. ..
  690. } => {
  691. self.write_patch(ctx, *aslr_reference, &mut artifacts, cache)
  692. .await?;
  693. }
  694. BuildMode::Base | BuildMode::Fat => {
  695. ctx.status_start_bundle();
  696. self.write_executable(ctx, &artifacts.exe, &mut artifacts.assets)
  697. .await
  698. .context("Failed to write main executable")?;
  699. self.write_assets(ctx, &artifacts.assets)
  700. .await
  701. .context("Failed to write assets")?;
  702. self.write_metadata().await?;
  703. self.optimize(ctx).await?;
  704. self.assemble(ctx)
  705. .await
  706. .context("Failed to assemble app bundle")?;
  707. tracing::debug!("Bundle created at {}", self.root_dir().display());
  708. }
  709. }
  710. // Populate the patch cache if we're in fat mode
  711. if matches!(ctx.mode, BuildMode::Fat) {
  712. artifacts.patch_cache = Some(Arc::new(self.create_patch_cache(&artifacts.exe).await?));
  713. }
  714. Ok(artifacts)
  715. }
  716. /// Run the cargo build by assembling the build command and executing it.
  717. ///
  718. /// This method needs to be very careful with processing output since errors being swallowed will
  719. /// be very confusing to the user.
  720. async fn cargo_build(&self, ctx: &BuildContext) -> Result<BuildArtifacts> {
  721. let time_start = SystemTime::now();
  722. // Extract the unit count of the crate graph so build_cargo has more accurate data
  723. // "Thin" builds only build the final exe, so we only need to build one crate
  724. let crate_count = match ctx.mode {
  725. BuildMode::Thin { .. } => 1,
  726. _ => self.get_unit_count_estimate(ctx).await,
  727. };
  728. // Update the status to show that we're starting the build and how many crates we expect to build
  729. ctx.status_starting_build(crate_count);
  730. let mut cmd = self.build_command(ctx)?;
  731. tracing::debug!(dx_src = ?TraceSrc::Build, "Executing cargo for {} using {}", self.platform, self.triple);
  732. let mut child = cmd
  733. .stdout(Stdio::piped())
  734. .stderr(Stdio::piped())
  735. .spawn()
  736. .context("Failed to spawn cargo build")?;
  737. let stdout = tokio::io::BufReader::new(child.stdout.take().unwrap());
  738. let stderr = tokio::io::BufReader::new(child.stderr.take().unwrap());
  739. let mut output_location: Option<PathBuf> = None;
  740. let mut stdout = stdout.lines();
  741. let mut stderr = stderr.lines();
  742. let mut units_compiled = 0;
  743. let mut emitting_error = false;
  744. loop {
  745. use cargo_metadata::Message;
  746. let line = tokio::select! {
  747. Ok(Some(line)) = stdout.next_line() => line,
  748. Ok(Some(line)) = stderr.next_line() => line,
  749. else => break,
  750. };
  751. let Some(Ok(message)) = Message::parse_stream(std::io::Cursor::new(line)).next() else {
  752. continue;
  753. };
  754. match message {
  755. Message::BuildScriptExecuted(_) => units_compiled += 1,
  756. Message::CompilerMessage(msg) => ctx.status_build_diagnostic(msg),
  757. Message::TextLine(line) => {
  758. // Handle the case where we're getting lines directly from rustc.
  759. // These are in a different format than the normal cargo output, though I imagine
  760. // this parsing code is quite fragile/sensitive to changes in cargo, cargo_metadata, rustc, etc.
  761. #[derive(Deserialize)]
  762. struct RustcArtifact {
  763. artifact: PathBuf,
  764. emit: String,
  765. }
  766. // These outputs look something like:
  767. //
  768. // { "artifact":"target/debug/deps/libdioxus_core-4f2a0b3c1e5f8b7c.rlib", "emit":"link" }
  769. //
  770. // There are other outputs like depinfo that we might be interested in in the future.
  771. if let Ok(artifact) = serde_json::from_str::<RustcArtifact>(&line) {
  772. if artifact.emit == "link" {
  773. output_location = Some(artifact.artifact);
  774. }
  775. }
  776. // For whatever reason, if there's an error while building, we still receive the TextLine
  777. // instead of an "error" message. However, the following messages *also* tend to
  778. // be the error message, and don't start with "error:". So we'll check if we've already
  779. // emitted an error message and if so, we'll emit all following messages as errors too.
  780. //
  781. // todo: This can lead to some really ugly output though, so we might want to look
  782. // into a more reliable way to detect errors propagating out of the compiler. If
  783. // we always wrapped rustc, then we could store this data somewhere in a much more
  784. // reliable format.
  785. if line.trim_start().starts_with("error:") {
  786. emitting_error = true;
  787. }
  788. // Note that previous text lines might have set emitting_error to true
  789. match emitting_error {
  790. true => ctx.status_build_error(line),
  791. false => ctx.status_build_message(line),
  792. }
  793. }
  794. Message::CompilerArtifact(artifact) => {
  795. units_compiled += 1;
  796. ctx.status_build_progress(units_compiled, crate_count, artifact.target.name);
  797. output_location = artifact.executable.map(Into::into);
  798. }
  799. // todo: this can occasionally swallow errors, so we should figure out what exactly is going wrong
  800. // since that is a really bad user experience.
  801. Message::BuildFinished(finished) => {
  802. if !finished.success {
  803. return Err(anyhow::anyhow!(
  804. "Cargo build failed, signaled by the compiler. Toggle tracing mode (press `t`) for more information."
  805. )
  806. .into());
  807. }
  808. }
  809. _ => {}
  810. }
  811. }
  812. let exe = output_location.context("Cargo build failed - no output location. Toggle tracing mode (press `t`) for more information.")?;
  813. // Accumulate the rustc args from the wrapper, if they exist and can be parsed.
  814. let mut direct_rustc = RustcArgs::default();
  815. if let Ok(res) = std::fs::read_to_string(self.rustc_wrapper_args_file.path()) {
  816. if let Ok(res) = serde_json::from_str(&res) {
  817. direct_rustc = res;
  818. }
  819. }
  820. // If there's any warnings from the linker, we should print them out
  821. if let Ok(linker_warnings) = std::fs::read_to_string(self.link_err_file.path()) {
  822. if !linker_warnings.is_empty() {
  823. tracing::warn!("Linker warnings: {}", linker_warnings);
  824. }
  825. }
  826. // Fat builds need to be linked with the fat linker. Would also like to link here for thin builds
  827. if matches!(ctx.mode, BuildMode::Fat) {
  828. self.run_fat_link(ctx, &exe).await?;
  829. }
  830. let assets = self.collect_assets(&exe, ctx)?;
  831. let time_end = SystemTime::now();
  832. let mode = ctx.mode.clone();
  833. let platform = self.platform;
  834. tracing::debug!("Build completed successfully: {:?}", exe);
  835. Ok(BuildArtifacts {
  836. time_end,
  837. platform,
  838. exe,
  839. direct_rustc,
  840. time_start,
  841. assets,
  842. mode,
  843. patch_cache: None,
  844. })
  845. }
  846. /// Traverse the target directory and collect all assets from the incremental cache
  847. ///
  848. /// This uses "known paths" that have stayed relatively stable during cargo's lifetime.
  849. /// One day this system might break and we might need to go back to using the linker approach.
  850. fn collect_assets(&self, exe: &Path, ctx: &BuildContext) -> Result<AssetManifest> {
  851. // walk every file in the incremental cache dir, reading and inserting items into the manifest.
  852. let mut manifest = AssetManifest::default();
  853. // And then add from the exe directly, just in case it's LTO compiled and has no incremental cache
  854. if !self.skip_assets {
  855. ctx.status_extracting_assets();
  856. _ = manifest.add_from_object_path(exe);
  857. }
  858. Ok(manifest)
  859. }
  860. /// Take the output of rustc and make it into the main exe of the bundle
  861. ///
  862. /// For wasm, we'll want to run `wasm-bindgen` to make it a wasm binary along with some other optimizations
  863. /// Other platforms we might do some stripping or other optimizations
  864. /// Move the executable to the workdir
  865. async fn write_executable(
  866. &self,
  867. ctx: &BuildContext,
  868. exe: &Path,
  869. assets: &mut AssetManifest,
  870. ) -> Result<()> {
  871. match self.platform {
  872. // Run wasm-bindgen on the wasm binary and set its output to be in the bundle folder
  873. // Also run wasm-opt on the wasm binary, and sets the index.html since that's also the "executable".
  874. //
  875. // The wasm stuff will be in a folder called "wasm" in the workdir.
  876. //
  877. // Final output format:
  878. // ```
  879. // dx/
  880. // app/
  881. // web/
  882. // bundle/
  883. // build/
  884. // server.exe
  885. // public/
  886. // index.html
  887. // wasm/
  888. // app.wasm
  889. // glue.js
  890. // snippets/
  891. // ...
  892. // assets/
  893. // logo.png
  894. // ```
  895. Platform::Web => {
  896. self.bundle_web(ctx, exe, assets).await?;
  897. }
  898. // this will require some extra oomf to get the multi architecture builds...
  899. // for now, we just copy the exe into the current arch (which, sorry, is hardcoded for my m1)
  900. // we'll want to do multi-arch builds in the future, so there won't be *one* exe dir to worry about
  901. // eventually `exe_dir` and `main_exe` will need to take in an arch and return the right exe path
  902. //
  903. // todo(jon): maybe just symlink this rather than copy it?
  904. // we might want to eventually use the objcopy logic to handle this
  905. //
  906. // https://github.com/rust-mobile/xbuild/blob/master/xbuild/template/lib.rs
  907. // https://github.com/rust-mobile/xbuild/blob/master/apk/src/lib.rs#L19
  908. //
  909. // These are all super simple, just copy the exe into the folder
  910. // eventually, perhaps, maybe strip + encrypt the exe?
  911. Platform::Android
  912. | Platform::MacOS
  913. | Platform::Windows
  914. | Platform::Linux
  915. | Platform::Ios
  916. | Platform::Liveview
  917. | Platform::Server => {
  918. // We wipe away the dir completely, which is not great behavior :/
  919. // Don't wipe server since web will need this folder too.
  920. if self.platform != Platform::Server {
  921. _ = std::fs::remove_dir_all(self.exe_dir());
  922. }
  923. std::fs::create_dir_all(self.exe_dir())?;
  924. std::fs::copy(exe, self.main_exe())?;
  925. }
  926. }
  927. Ok(())
  928. }
  929. /// Copy the assets out of the manifest and into the target location
  930. ///
  931. /// Should be the same on all platforms - just copy over the assets from the manifest into the output directory
  932. async fn write_assets(&self, ctx: &BuildContext, assets: &AssetManifest) -> Result<()> {
  933. // Server doesn't need assets - web will provide them
  934. if self.platform == Platform::Server {
  935. return Ok(());
  936. }
  937. let asset_dir = self.asset_dir();
  938. // First, clear the asset dir of any files that don't exist in the new manifest
  939. _ = std::fs::create_dir_all(&asset_dir);
  940. // Create a set of all the paths that new files will be bundled to
  941. let mut keep_bundled_output_paths: HashSet<_> = assets
  942. .assets
  943. .values()
  944. .map(|a| asset_dir.join(a.bundled_path()))
  945. .collect();
  946. // The CLI creates a .version file in the asset dir to keep track of what version of the optimizer
  947. // the asset was processed. If that version doesn't match the CLI version, we need to re-optimize
  948. // all assets.
  949. let version_file = self.asset_optimizer_version_file();
  950. let clear_cache = std::fs::read_to_string(&version_file)
  951. .ok()
  952. .filter(|s| s == crate::VERSION.as_str())
  953. .is_none();
  954. if clear_cache {
  955. keep_bundled_output_paths.clear();
  956. }
  957. tracing::trace!(
  958. "Keeping bundled output paths: {:#?}",
  959. keep_bundled_output_paths
  960. );
  961. // use walkdir::WalkDir;
  962. // for item in WalkDir::new(&asset_dir).into_iter().flatten() {
  963. // // If this asset is in the manifest, we don't need to remove it
  964. // let canonicalized = dunce::canonicalize(item.path())?;
  965. // if !keep_bundled_output_paths.contains(canonicalized.as_path()) {
  966. // // Remove empty dirs, remove files not in the manifest
  967. // if item.file_type().is_dir() && item.path().read_dir()?.next().is_none() {
  968. // std::fs::remove_dir(item.path())?;
  969. // } else {
  970. // std::fs::remove_file(item.path())?;
  971. // }
  972. // }
  973. // }
  974. // todo(jon): we also want to eventually include options for each asset's optimization and compression, which we currently aren't
  975. let mut assets_to_transfer = vec![];
  976. // Queue the bundled assets
  977. for (asset, bundled) in &assets.assets {
  978. let from = asset.clone();
  979. let to = asset_dir.join(bundled.bundled_path());
  980. // prefer to log using a shorter path relative to the workspace dir by trimming the workspace dir
  981. let from_ = from
  982. .strip_prefix(self.workspace_dir())
  983. .unwrap_or(from.as_path());
  984. let to_ = from
  985. .strip_prefix(self.workspace_dir())
  986. .unwrap_or(to.as_path());
  987. tracing::debug!("Copying asset {from_:?} to {to_:?}");
  988. assets_to_transfer.push((from, to, *bundled.options()));
  989. }
  990. let asset_count = assets_to_transfer.len();
  991. let started_processing = AtomicUsize::new(0);
  992. let copied = AtomicUsize::new(0);
  993. // Parallel Copy over the assets and keep track of progress with an atomic counter
  994. let progress = ctx.tx.clone();
  995. let ws_dir = self.workspace_dir();
  996. // Optimizing assets is expensive and blocking, so we do it in a tokio spawn blocking task
  997. tokio::task::spawn_blocking(move || {
  998. assets_to_transfer
  999. .par_iter()
  1000. .try_for_each(|(from, to, options)| {
  1001. let processing = started_processing.fetch_add(1, Ordering::SeqCst);
  1002. let from_ = from.strip_prefix(&ws_dir).unwrap_or(from);
  1003. tracing::trace!(
  1004. "Starting asset copy {processing}/{asset_count} from {from_:?}"
  1005. );
  1006. let res = process_file_to(options, from, to);
  1007. if let Err(err) = res.as_ref() {
  1008. tracing::error!("Failed to copy asset {from:?}: {err}");
  1009. }
  1010. let finished = copied.fetch_add(1, Ordering::SeqCst);
  1011. BuildContext::status_copied_asset(
  1012. &progress,
  1013. finished,
  1014. asset_count,
  1015. from.to_path_buf(),
  1016. );
  1017. res.map(|_| ())
  1018. })
  1019. })
  1020. .await
  1021. .map_err(|e| anyhow::anyhow!("A task failed while trying to copy assets: {e}"))??;
  1022. // // Remove the wasm bindgen output directory if it exists
  1023. // _ = std::fs::remove_dir_all(self.wasm_bindgen_out_dir());
  1024. // Write the version file so we know what version of the optimizer we used
  1025. std::fs::write(self.asset_optimizer_version_file(), crate::VERSION.as_str())?;
  1026. Ok(())
  1027. }
  1028. /// Run our custom linker setup to generate a patch file in the right location
  1029. ///
  1030. /// This should be the only case where the cargo output is a "dummy" file and requires us to
  1031. /// manually do any linking.
  1032. ///
  1033. /// We also run some post processing steps here, like extracting out any new assets.
  1034. async fn write_patch(
  1035. &self,
  1036. ctx: &BuildContext,
  1037. aslr_reference: u64,
  1038. artifacts: &mut BuildArtifacts,
  1039. cache: &Arc<HotpatchModuleCache>,
  1040. ) -> Result<()> {
  1041. ctx.status_hotpatching();
  1042. tracing::debug!(
  1043. "Original builds for patch: {}",
  1044. self.link_args_file.path().display()
  1045. );
  1046. let raw_args = std::fs::read_to_string(self.link_args_file.path())
  1047. .context("Failed to read link args from file")?;
  1048. let args = raw_args.lines().collect::<Vec<_>>();
  1049. // Extract out the incremental object files.
  1050. //
  1051. // This is sadly somewhat of a hack, but it might be a moderately reliable hack.
  1052. //
  1053. // When rustc links your project, it passes the args as how a linker would expect, but with
  1054. // a somewhat reliable ordering. These are all internal details to cargo/rustc, so we can't
  1055. // rely on them *too* much, but the *are* fundamental to how rust compiles your projects, and
  1056. // linker interfaces probably won't change drastically for another 40 years.
  1057. //
  1058. // We need to tear apart this command and only pass the args that are relevant to our thin link.
  1059. // Mainly, we don't want any rlibs to be linked. Occasionally some libraries like objc_exception
  1060. // export a folder with their artifacts - unsure if we actually need to include them. Generally
  1061. // you can err on the side that most *libraries* don't need to be linked here since dlopen
  1062. // satisfies those symbols anyways when the binary is loaded.
  1063. //
  1064. // Many args are passed twice, too, which can be confusing, but generally don't have any real
  1065. // effect. Note that on macos/ios, there's a special macho header that needs to be set, otherwise
  1066. // dyld will complain.
  1067. //
  1068. // Also, some flags in darwin land might become deprecated, need to be super conservative:
  1069. // - https://developer.apple.com/forums/thread/773907
  1070. //
  1071. // The format of this command roughly follows:
  1072. // ```
  1073. // clang
  1074. // /dioxus/target/debug/subsecond-cli
  1075. // /var/folders/zs/gvrfkj8x33d39cvw2p06yc700000gn/T/rustcAqQ4p2/symbols.o
  1076. // /dioxus/target/subsecond-dev/deps/subsecond_harness-acfb69cb29ffb8fa.05stnb4bovskp7a00wyyf7l9s.rcgu.o
  1077. // /dioxus/target/subsecond-dev/deps/subsecond_harness-acfb69cb29ffb8fa.08rgcutgrtj2mxoogjg3ufs0g.rcgu.o
  1078. // /dioxus/target/subsecond-dev/deps/subsecond_harness-acfb69cb29ffb8fa.0941bd8fa2bydcv9hfmgzzne9.rcgu.o
  1079. // /dioxus/target/subsecond-dev/deps/libbincode-c215feeb7886f81b.rlib
  1080. // /dioxus/target/subsecond-dev/deps/libanyhow-e69ac15c094daba6.rlib
  1081. // /dioxus/target/subsecond-dev/deps/libratatui-c3364579b86a1dfc.rlib
  1082. // /.rustup/toolchains/stable-aarch64-apple-darwin/lib/rustlib/aarch64-apple-darwin/lib/libstd-019f0f6ae6e6562b.rlib
  1083. // /.rustup/toolchains/stable-aarch64-apple-darwin/lib/rustlib/aarch64-apple-darwin/lib/libpanic_unwind-7387d38173a2eb37.rlib
  1084. // /.rustup/toolchains/stable-aarch64-apple-darwin/lib/rustlib/aarch64-apple-darwin/lib/libobject-2b03cf6ece171d21.rlib
  1085. // -framework AppKit
  1086. // -lc
  1087. // -framework Foundation
  1088. // -framework Carbon
  1089. // -lSystem
  1090. // -framework CoreFoundation
  1091. // -lobjc
  1092. // -liconv
  1093. // -lm
  1094. // -arch arm64
  1095. // -mmacosx-version-min=11.0.0
  1096. // -L /dioxus/target/subsecond-dev/build/objc_exception-dc226cad0480ea65/out
  1097. // -o /dioxus/target/subsecond-dev/deps/subsecond_harness-acfb69cb29ffb8fa
  1098. // -nodefaultlibs
  1099. // -Wl,-all_load
  1100. // ```
  1101. let mut object_files = args
  1102. .iter()
  1103. .filter(|arg| arg.ends_with(".rcgu.o"))
  1104. .sorted()
  1105. .map(PathBuf::from)
  1106. .collect::<Vec<_>>();
  1107. // On non-wasm platforms, we generate a special shim object file which converts symbols from
  1108. // fat binary into direct addresses from the running process.
  1109. //
  1110. // Our wasm approach is quite specific to wasm. We don't need to resolve any missing symbols
  1111. // there since wasm is relocatable, but there is considerable pre and post processing work to
  1112. // satisfy undefined symbols that we do by munging the binary directly.
  1113. //
  1114. // todo: can we adjust our wasm approach to also use a similar system?
  1115. // todo: don't require the aslr reference and just patch the got when loading.
  1116. //
  1117. // Requiring the ASLR offset here is necessary but unfortunately might be flakey in practice.
  1118. // Android apps can take a long time to open, and a hot patch might've been issued in the interim,
  1119. // making this hotpatch a failure.
  1120. if self.platform != Platform::Web {
  1121. let stub_bytes = crate::build::create_undefined_symbol_stub(
  1122. cache,
  1123. &object_files,
  1124. &self.triple,
  1125. aslr_reference,
  1126. )
  1127. .expect("failed to resolve patch symbols");
  1128. // Currently we're dropping stub.o in the exe dir, but should probably just move to a tempfile?
  1129. let patch_file = self.main_exe().with_file_name("stub.o");
  1130. std::fs::write(&patch_file, stub_bytes)?;
  1131. object_files.push(patch_file);
  1132. }
  1133. // And now we can run the linker with our new args
  1134. let linker = self.select_linker()?;
  1135. let out_exe = self.patch_exe(artifacts.time_start);
  1136. let out_arg = match self.triple.operating_system {
  1137. OperatingSystem::Windows => vec![format!("/OUT:{}", out_exe.display())],
  1138. _ => vec!["-o".to_string(), out_exe.display().to_string()],
  1139. };
  1140. tracing::trace!("Linking with {:?} using args: {:#?}", linker, object_files);
  1141. // Run the linker directly!
  1142. //
  1143. // We dump its output directly into the patch exe location which is different than how rustc
  1144. // does it since it uses llvm-objcopy into the `target/debug/` folder.
  1145. let res = Command::new(linker)
  1146. .args(object_files.iter())
  1147. .args(self.thin_link_args(&args)?)
  1148. .args(out_arg)
  1149. .output()
  1150. .await?;
  1151. if !res.stderr.is_empty() {
  1152. let errs = String::from_utf8_lossy(&res.stderr);
  1153. if !self.patch_exe(artifacts.time_start).exists() || !res.status.success() {
  1154. tracing::error!("Failed to generate patch: {}", errs.trim());
  1155. } else {
  1156. tracing::trace!("Linker output during thin linking: {}", errs.trim());
  1157. }
  1158. }
  1159. // For some really weird reason that I think is because of dlopen caching, future loads of the
  1160. // jump library will fail if we don't remove the original fat file. I think this could be
  1161. // because of library versioning and namespaces, but really unsure.
  1162. //
  1163. // The errors if you forget to do this are *extremely* cryptic - missing symbols that never existed.
  1164. //
  1165. // Fortunately, this binary exists in two places - the deps dir and the target out dir. We
  1166. // can just remove the one in the deps dir and the problem goes away.
  1167. if let Some(idx) = args.iter().position(|arg| *arg == "-o") {
  1168. _ = std::fs::remove_file(PathBuf::from(args[idx + 1]));
  1169. }
  1170. // Now extract the assets from the fat binary
  1171. artifacts
  1172. .assets
  1173. .add_from_object_path(&self.patch_exe(artifacts.time_start))?;
  1174. // Clean up the temps manually
  1175. // todo: we might want to keep them around for debugging purposes
  1176. for file in object_files {
  1177. _ = std::fs::remove_file(file);
  1178. }
  1179. Ok(())
  1180. }
  1181. /// Take the original args passed to the "fat" build and then create the "thin" variant.
  1182. ///
  1183. /// This is basically just stripping away the rlibs and other libraries that will be satisfied
  1184. /// by our stub step.
  1185. fn thin_link_args(&self, original_args: &[&str]) -> Result<Vec<String>> {
  1186. use target_lexicon::OperatingSystem;
  1187. let triple = self.triple.clone();
  1188. let mut out_args = vec![];
  1189. match triple.operating_system {
  1190. // wasm32-unknown-unknown -> use wasm-ld (gnu-lld)
  1191. //
  1192. // We need to import a few things - namely the memory and ifunc table.
  1193. //
  1194. // We can safely export everything, I believe, though that led to issues with the "fat"
  1195. // binaries that also might lead to issues here too. wasm-bindgen chokes on some symbols
  1196. // and the resulting JS has issues.
  1197. //
  1198. // We turn on both --pie and --experimental-pic but I think we only need --pie.
  1199. //
  1200. // We don't use *any* of the original linker args since they do lots of custom exports
  1201. // and other things that we don't need.
  1202. //
  1203. // The trickiest one here is -Crelocation-model=pic, which forces data symbols
  1204. // into a GOT, making it possible to import them from the main module.
  1205. //
  1206. // I think we can make relocation-model=pic work for non-wasm platforms, enabling
  1207. // fully relocatable modules with no host coordination in lieu of sending out
  1208. // the aslr slide at runtime.
  1209. OperatingSystem::Unknown if self.platform == Platform::Web => {
  1210. out_args.extend([
  1211. "--fatal-warnings".to_string(),
  1212. "--verbose".to_string(),
  1213. "--import-memory".to_string(),
  1214. "--import-table".to_string(),
  1215. "--growable-table".to_string(),
  1216. "--export".to_string(),
  1217. "main".to_string(),
  1218. "--allow-undefined".to_string(),
  1219. "--no-demangle".to_string(),
  1220. "--no-entry".to_string(),
  1221. "--pie".to_string(),
  1222. "--experimental-pic".to_string(),
  1223. ]);
  1224. }
  1225. // This uses "cc" and these args need to be ld compatible
  1226. //
  1227. // Most importantly, we want to pass `-dylib` to both CC and the linker to indicate that
  1228. // we want to generate the shared library instead of an executable.
  1229. OperatingSystem::IOS(_) | OperatingSystem::MacOSX(_) | OperatingSystem::Darwin(_) => {
  1230. out_args.extend(["-Wl,-dylib".to_string()]);
  1231. // Preserve the original args. We only preserve:
  1232. // -framework
  1233. // -arch
  1234. // -lxyz
  1235. // There might be more, but some flags might break our setup.
  1236. for (idx, arg) in original_args.iter().enumerate() {
  1237. if *arg == "-framework" || *arg == "-arch" || *arg == "-L" {
  1238. out_args.push(arg.to_string());
  1239. out_args.push(original_args[idx + 1].to_string());
  1240. }
  1241. if arg.starts_with("-l") || arg.starts_with("-m") {
  1242. out_args.push(arg.to_string());
  1243. }
  1244. }
  1245. }
  1246. // android/linux need to be compatible with lld
  1247. //
  1248. // android currently drags along its own libraries and other zany flags
  1249. OperatingSystem::Linux => {
  1250. out_args.extend([
  1251. "-shared".to_string(),
  1252. "-Wl,--eh-frame-hdr".to_string(),
  1253. "-Wl,-z,noexecstack".to_string(),
  1254. "-Wl,-z,relro,-z,now".to_string(),
  1255. "-nodefaultlibs".to_string(),
  1256. "-Wl,-Bdynamic".to_string(),
  1257. ]);
  1258. // Preserve the original args. We only preserve:
  1259. // -L <path>
  1260. // -arch
  1261. // -lxyz
  1262. // There might be more, but some flags might break our setup.
  1263. for (idx, arg) in original_args.iter().enumerate() {
  1264. if *arg == "-L" {
  1265. out_args.push(arg.to_string());
  1266. out_args.push(original_args[idx + 1].to_string());
  1267. }
  1268. if arg.starts_with("-l")
  1269. || arg.starts_with("-m")
  1270. || arg.starts_with("-Wl,--target=")
  1271. {
  1272. out_args.push(arg.to_string());
  1273. }
  1274. }
  1275. }
  1276. OperatingSystem::Windows => {
  1277. out_args.extend([
  1278. "shlwapi.lib".to_string(),
  1279. "kernel32.lib".to_string(),
  1280. "advapi32.lib".to_string(),
  1281. "ntdll.lib".to_string(),
  1282. "userenv.lib".to_string(),
  1283. "ws2_32.lib".to_string(),
  1284. "dbghelp.lib".to_string(),
  1285. "/defaultlib:msvcrt".to_string(),
  1286. "/DLL".to_string(),
  1287. "/DEBUG".to_string(),
  1288. "/PDBALTPATH:%_PDB%".to_string(),
  1289. "/EXPORT:main".to_string(),
  1290. "/HIGHENTROPYVA:NO".to_string(),
  1291. ]);
  1292. }
  1293. _ => return Err(anyhow::anyhow!("Unsupported platform for thin linking").into()),
  1294. }
  1295. let extract_value = |arg: &str| -> Option<String> {
  1296. original_args
  1297. .iter()
  1298. .position(|a| *a == arg)
  1299. .map(|i| original_args[i + 1].to_string())
  1300. };
  1301. if let Some(vale) = extract_value("-target") {
  1302. out_args.push("-target".to_string());
  1303. out_args.push(vale);
  1304. }
  1305. if let Some(vale) = extract_value("-isysroot") {
  1306. out_args.push("-isysroot".to_string());
  1307. out_args.push(vale);
  1308. }
  1309. Ok(out_args)
  1310. }
  1311. /// Patches are stored in the same directory as the main executable, but with a name based on the
  1312. /// time the patch started compiling.
  1313. ///
  1314. /// - lib{name}-patch-{time}.(so/dll/dylib) (next to the main exe)
  1315. ///
  1316. /// Note that weirdly enough, the name of dylibs can actually matter. In some environments, libs
  1317. /// can override each other with symbol interposition.
  1318. ///
  1319. /// Also, on Android - and some Linux, we *need* to start the lib name with `lib` for the dynamic
  1320. /// loader to consider it a shared library.
  1321. ///
  1322. /// todo: the time format might actually be problematic if two platforms share the same build folder.
  1323. pub(crate) fn patch_exe(&self, time_start: SystemTime) -> PathBuf {
  1324. let path = self.main_exe().with_file_name(format!(
  1325. "lib{}-patch-{}",
  1326. self.executable_name(),
  1327. time_start
  1328. .duration_since(UNIX_EPOCH)
  1329. .map(|f| f.as_millis())
  1330. .unwrap_or(0),
  1331. ));
  1332. let extension = match self.triple.operating_system {
  1333. OperatingSystem::Darwin(_) => "dylib",
  1334. OperatingSystem::MacOSX(_) => "dylib",
  1335. OperatingSystem::IOS(_) => "dylib",
  1336. OperatingSystem::Windows => "dll",
  1337. OperatingSystem::Linux => "so",
  1338. OperatingSystem::Wasi => "wasm",
  1339. OperatingSystem::Unknown if self.platform == Platform::Web => "wasm",
  1340. _ => "",
  1341. };
  1342. path.with_extension(extension)
  1343. }
  1344. /// When we link together the fat binary, we need to make sure every `.o` file in *every* rlib
  1345. /// is taken into account. This is the same work that the rust compiler does when assembling
  1346. /// staticlibs.
  1347. ///
  1348. /// <https://github.com/rust-lang/rust/blob/191df20fcad9331d3a948aa8e8556775ec3fe69d/compiler/rustc_codegen_ssa/src/back/link.rs#L448>
  1349. ///
  1350. /// Since we're going to be passing these to the linker, we need to make sure and not provide any
  1351. /// weird files (like the rmeta) file that rustc generates.
  1352. ///
  1353. /// We discovered the need for this after running into issues with wasm-ld not being able to
  1354. /// handle the rmeta file.
  1355. ///
  1356. /// <https://github.com/llvm/llvm-project/issues/55786>
  1357. ///
  1358. /// Also, crates might not drag in all their dependent code. The monorphizer won't lift trait-based generics:
  1359. ///
  1360. /// <https://github.com/rust-lang/rust/blob/191df20fcad9331d3a948aa8e8556775ec3fe69d/compiler/rustc_monomorphize/src/collector.rs>
  1361. ///
  1362. /// When Rust normally handles this, it uses the +whole-archive directive which adjusts how the rlib
  1363. /// is written to disk.
  1364. ///
  1365. /// Since creating this object file can be a lot of work, we cache it in the target dir by hashing
  1366. /// the names of the rlibs in the command and storing it in the target dir. That way, when we run
  1367. /// this command again, we can just used the cached object file.
  1368. ///
  1369. /// In theory, we only need to do this for every crate accessible by the current crate, but that's
  1370. /// hard acquire without knowing the exported symbols from each crate.
  1371. ///
  1372. /// todo: I think we can traverse our immediate dependencies and inspect their symbols, unless they `pub use` a crate
  1373. /// todo: we should try and make this faster with memmapping
  1374. pub(crate) async fn run_fat_link(&self, ctx: &BuildContext, exe: &Path) -> Result<()> {
  1375. ctx.status_starting_link();
  1376. let raw_args = std::fs::read_to_string(self.link_args_file.path())
  1377. .context("Failed to read link args from file")?;
  1378. let args = raw_args.lines().collect::<Vec<_>>();
  1379. // Filter out the rlib files from the arguments
  1380. let rlibs = args
  1381. .iter()
  1382. .filter(|arg| arg.ends_with(".rlib"))
  1383. .map(PathBuf::from)
  1384. .collect::<Vec<_>>();
  1385. // Acquire a hash from the rlib names
  1386. let hash_id = Uuid::new_v5(
  1387. &Uuid::NAMESPACE_OID,
  1388. rlibs
  1389. .iter()
  1390. .map(|p| p.file_name().unwrap().to_string_lossy())
  1391. .collect::<String>()
  1392. .as_bytes(),
  1393. );
  1394. // Check if we already have a cached object file
  1395. let out_ar_path = exe.with_file_name(format!("libfatdependencies-{hash_id}.a"));
  1396. let mut compiler_rlibs = vec![];
  1397. // Create it by dumping all the rlibs into it
  1398. // This will include the std rlibs too, which can severely bloat the size of the archive
  1399. //
  1400. // The nature of this process involves making extremely fat archives, so we should try and
  1401. // speed up the future linking process by caching the archive.
  1402. if !crate::devcfg::should_cache_dep_lib(&out_ar_path) {
  1403. let mut bytes = vec![];
  1404. let mut out_ar = ar::Builder::new(&mut bytes);
  1405. for rlib in &rlibs {
  1406. // Skip compiler rlibs since they're missing bitcode
  1407. //
  1408. // https://github.com/rust-lang/rust/issues/94232#issuecomment-1048342201
  1409. //
  1410. // if the rlib is not in the target directory, we skip it.
  1411. if !rlib.starts_with(self.workspace_dir()) {
  1412. compiler_rlibs.push(rlib.clone());
  1413. tracing::trace!("Skipping rlib: {:?}", rlib);
  1414. continue;
  1415. }
  1416. tracing::trace!("Adding rlib to staticlib: {:?}", rlib);
  1417. let rlib_contents = std::fs::read(rlib)?;
  1418. let mut reader = ar::Archive::new(std::io::Cursor::new(rlib_contents));
  1419. while let Some(Ok(object_file)) = reader.next_entry() {
  1420. let name = std::str::from_utf8(object_file.header().identifier()).unwrap();
  1421. if name.ends_with(".rmeta") {
  1422. continue;
  1423. }
  1424. if object_file.header().size() == 0 {
  1425. continue;
  1426. }
  1427. // rlibs might contain dlls/sos/lib files which we don't want to include
  1428. if name.ends_with(".dll") || name.ends_with(".so") || name.ends_with(".lib") {
  1429. compiler_rlibs.push(rlib.to_owned());
  1430. continue;
  1431. }
  1432. if !(name.ends_with(".o") || name.ends_with(".obj")) {
  1433. tracing::debug!("Unknown object file in rlib: {:?}", name);
  1434. }
  1435. out_ar
  1436. .append(&object_file.header().clone(), object_file)
  1437. .context("Failed to add object file to archive")?;
  1438. }
  1439. }
  1440. let bytes = out_ar.into_inner().context("Failed to finalize archive")?;
  1441. std::fs::write(&out_ar_path, bytes).context("Failed to write archive")?;
  1442. tracing::debug!("Wrote fat archive to {:?}", out_ar_path);
  1443. }
  1444. compiler_rlibs.dedup();
  1445. // We're going to replace the first rlib in the args with our fat archive
  1446. // And then remove the rest of the rlibs
  1447. //
  1448. // We also need to insert the -force_load flag to force the linker to load the archive
  1449. let mut args = args.iter().map(|s| s.to_string()).collect::<Vec<_>>();
  1450. if let Some(first_rlib) = args.iter().position(|arg| arg.ends_with(".rlib")) {
  1451. match self.triple.operating_system {
  1452. OperatingSystem::Unknown if self.platform == Platform::Web => {
  1453. // We need to use the --whole-archive flag for wasm
  1454. args[first_rlib] = "--whole-archive".to_string();
  1455. args.insert(first_rlib + 1, out_ar_path.display().to_string());
  1456. args.insert(first_rlib + 2, "--no-whole-archive".to_string());
  1457. args.retain(|arg| !arg.ends_with(".rlib"));
  1458. // add back the compiler rlibs
  1459. for rlib in compiler_rlibs.iter().rev() {
  1460. args.insert(first_rlib + 3, rlib.display().to_string());
  1461. }
  1462. }
  1463. // Subtle difference - on linux and android we go through clang and thus pass `-Wl,` prefix
  1464. OperatingSystem::Linux => {
  1465. args[first_rlib] = "-Wl,--whole-archive".to_string();
  1466. args.insert(first_rlib + 1, out_ar_path.display().to_string());
  1467. args.insert(first_rlib + 2, "-Wl,--no-whole-archive".to_string());
  1468. args.retain(|arg| !arg.ends_with(".rlib"));
  1469. // add back the compiler rlibs
  1470. for rlib in compiler_rlibs.iter().rev() {
  1471. args.insert(first_rlib + 3, rlib.display().to_string());
  1472. }
  1473. }
  1474. OperatingSystem::Darwin(_) | OperatingSystem::IOS(_) => {
  1475. args[first_rlib] = "-Wl,-force_load".to_string();
  1476. args.insert(first_rlib + 1, out_ar_path.display().to_string());
  1477. args.retain(|arg| !arg.ends_with(".rlib"));
  1478. // add back the compiler rlibs
  1479. for rlib in compiler_rlibs.iter().rev() {
  1480. args.insert(first_rlib + 2, rlib.display().to_string());
  1481. }
  1482. args.insert(first_rlib + 3, "-Wl,-all_load".to_string());
  1483. }
  1484. OperatingSystem::Windows => {
  1485. args[first_rlib] = format!("/WHOLEARCHIVE:{}", out_ar_path.display());
  1486. args.retain(|arg| !arg.ends_with(".rlib"));
  1487. // add back the compiler rlibs
  1488. for rlib in compiler_rlibs.iter().rev() {
  1489. args.insert(first_rlib + 1, rlib.display().to_string());
  1490. }
  1491. args.insert(first_rlib, "/HIGHENTROPYVA:NO".to_string());
  1492. }
  1493. _ => {}
  1494. };
  1495. }
  1496. // We also need to remove the `-o` flag since we want the linker output to end up in the
  1497. // rust exe location, not in the deps dir as it normally would.
  1498. if let Some(idx) = args
  1499. .iter()
  1500. .position(|arg| *arg == "-o" || *arg == "--output")
  1501. {
  1502. args.remove(idx + 1);
  1503. args.remove(idx);
  1504. }
  1505. // same but windows support
  1506. if let Some(idx) = args.iter().position(|arg| arg.starts_with("/OUT")) {
  1507. args.remove(idx);
  1508. }
  1509. // We want to go through wasm-ld directly, so we need to remove the -flavor flag
  1510. if self.platform == Platform::Web {
  1511. let flavor_idx = args.iter().position(|arg| *arg == "-flavor").unwrap();
  1512. args.remove(flavor_idx + 1);
  1513. args.remove(flavor_idx);
  1514. }
  1515. // And now we can run the linker with our new args
  1516. let linker = self.select_linker()?;
  1517. tracing::trace!("Fat linking with args: {:?} {:#?}", linker, args);
  1518. // Run the linker directly!
  1519. let out_arg = match self.triple.operating_system {
  1520. OperatingSystem::Windows => vec![format!("/OUT:{}", exe.display())],
  1521. _ => vec!["-o".to_string(), exe.display().to_string()],
  1522. };
  1523. let res = Command::new(linker)
  1524. .args(args.iter().skip(1))
  1525. .args(out_arg)
  1526. .output()
  1527. .await?;
  1528. if !res.stderr.is_empty() {
  1529. let errs = String::from_utf8_lossy(&res.stderr);
  1530. if !res.status.success() {
  1531. tracing::error!("Failed to generate fat binary: {}", errs.trim());
  1532. } else {
  1533. tracing::trace!("Warnings during fat linking: {}", errs.trim());
  1534. }
  1535. }
  1536. if !res.stdout.is_empty() {
  1537. let out = String::from_utf8_lossy(&res.stdout);
  1538. tracing::trace!("Output from fat linking: {}", out.trim());
  1539. }
  1540. // Clean up the temps manually
  1541. for f in args.iter().filter(|arg| arg.ends_with(".rcgu.o")) {
  1542. _ = std::fs::remove_file(f);
  1543. }
  1544. Ok(())
  1545. }
  1546. /// Select the linker to use for this platform.
  1547. ///
  1548. /// We prefer to use the rust-lld linker when we can since it's usually there.
  1549. /// On macos, we use the system linker since macho files can be a bit finicky.
  1550. ///
  1551. /// This means we basically ignore the linker flavor that the user configured, which could
  1552. /// cause issues with a custom linker setup. In theory, rust translates most flags to the right
  1553. /// linker format.
  1554. fn select_linker(&self) -> Result<PathBuf, Error> {
  1555. let cc = match self.triple.operating_system {
  1556. OperatingSystem::Unknown if self.platform == Platform::Web => self.workspace.wasm_ld(),
  1557. // The android clang linker is *special* and has some android-specific flags that we need
  1558. //
  1559. // Note that this is *clang*, not `lld`.
  1560. OperatingSystem::Linux if self.platform == Platform::Android => {
  1561. self.workspace.android_tools()?.android_cc(&self.triple)
  1562. }
  1563. // On macOS, we use the system linker since it's usually there.
  1564. // We could also use `lld` here, but it might not be installed by default.
  1565. //
  1566. // Note that this is *clang*, not `lld`.
  1567. OperatingSystem::Darwin(_) | OperatingSystem::IOS(_) => self.workspace.cc(),
  1568. // On windows, instead of trying to find the system linker, we just go with the lld.link
  1569. // that rustup provides. It's faster and more stable then reyling on link.exe in path.
  1570. OperatingSystem::Windows => self.workspace.lld_link(),
  1571. // The rest of the platforms use `cc` as the linker which should be available in your path,
  1572. // provided you have build-tools setup. On mac/linux this is the default, but on Windows
  1573. // it requires msvc or gnu downloaded, which is a requirement to use rust anyways.
  1574. //
  1575. // The default linker might actually be slow though, so we could consider using lld or rust-lld
  1576. // since those are shipping by default on linux as of 1.86. Window's linker is the really slow one.
  1577. //
  1578. // https://blog.rust-lang.org/2024/05/17/enabling-rust-lld-on-linux.html
  1579. //
  1580. // Note that "cc" is *not* a linker. It's a compiler! The arguments we pass need to be in
  1581. // the form of `-Wl,<args>` for them to make it to the linker. This matches how rust does it
  1582. // which is confusing.
  1583. _ => self.workspace.cc(),
  1584. };
  1585. Ok(cc)
  1586. }
  1587. /// Assemble the `cargo rustc` / `rustc` command
  1588. ///
  1589. /// When building fat/base binaries, we use `cargo rustc`.
  1590. /// When building thin binaries, we use `rustc` directly.
  1591. ///
  1592. /// When processing the output of this command, you need to make sure to handle both cases which
  1593. /// both have different formats (but with json output for both).
  1594. fn build_command(&self, ctx: &BuildContext) -> Result<Command> {
  1595. match &ctx.mode {
  1596. // We're assembling rustc directly, so we need to be *very* careful. Cargo sets rustc's
  1597. // env up very particularly, and we want to match it 1:1 but with some changes.
  1598. //
  1599. // To do this, we reset the env completely, and then pass every env var that the original
  1600. // rustc process had 1:1.
  1601. //
  1602. // We need to unset a few things, like the RUSTC wrappers and then our special env var
  1603. // indicating that dx itself is the compiler. If we forget to do this, then the compiler
  1604. // ends up doing some recursive nonsense and dx is trying to link instead of compiling.
  1605. //
  1606. // todo: maybe rustc needs to be found on the FS instead of using the one in the path?
  1607. BuildMode::Thin { rustc_args, .. } => {
  1608. let mut cmd = Command::new("rustc");
  1609. cmd.current_dir(self.workspace_dir());
  1610. cmd.env_clear();
  1611. cmd.args(rustc_args.args[1..].iter());
  1612. cmd.env_remove("RUSTC_WORKSPACE_WRAPPER");
  1613. cmd.env_remove("RUSTC_WRAPPER");
  1614. cmd.env_remove(DX_RUSTC_WRAPPER_ENV_VAR);
  1615. cmd.envs(self.cargo_build_env_vars(ctx)?);
  1616. cmd.arg(format!("-Clinker={}", Workspace::path_to_dx()?.display()));
  1617. if self.platform == Platform::Web {
  1618. cmd.arg("-Crelocation-model=pic");
  1619. }
  1620. tracing::debug!("Direct rustc: {:#?}", cmd);
  1621. cmd.envs(rustc_args.envs.iter().cloned());
  1622. tracing::trace!("Setting env vars: {:#?}", rustc_args.envs);
  1623. Ok(cmd)
  1624. }
  1625. // For Base and Fat builds, we use a regular cargo setup, but we might need to intercept
  1626. // rustc itself in case we're hot-patching and need a reliable rustc environment to
  1627. // continuously recompile the top-level crate with.
  1628. //
  1629. // In the future, when we support hot-patching *all* workspace crates, we will need to
  1630. // make use of the RUSTC_WORKSPACE_WRAPPER environment variable instead of RUSTC_WRAPPER
  1631. // and then keep track of env and args on a per-crate basis.
  1632. //
  1633. // We've also had a number of issues with incorrect canonicalization when passing paths
  1634. // through envs on windows, hence the frequent use of dunce::canonicalize.
  1635. _ => {
  1636. let mut cmd = Command::new("cargo");
  1637. cmd.arg("rustc")
  1638. .current_dir(self.crate_dir())
  1639. .arg("--message-format")
  1640. .arg("json-diagnostic-rendered-ansi")
  1641. .args(self.cargo_build_arguments(ctx))
  1642. .envs(self.cargo_build_env_vars(ctx)?);
  1643. if ctx.mode == BuildMode::Fat {
  1644. cmd.env(
  1645. DX_RUSTC_WRAPPER_ENV_VAR,
  1646. dunce::canonicalize(self.rustc_wrapper_args_file.path())
  1647. .unwrap()
  1648. .display()
  1649. .to_string(),
  1650. );
  1651. cmd.env(
  1652. "RUSTC_WRAPPER",
  1653. Workspace::path_to_dx()?.display().to_string(),
  1654. );
  1655. }
  1656. tracing::debug!("Cargo: {:#?}", cmd);
  1657. Ok(cmd)
  1658. }
  1659. }
  1660. }
  1661. /// Create a list of arguments for cargo builds
  1662. ///
  1663. /// We always use `cargo rustc` *or* `rustc` directly. This means we can pass extra flags like
  1664. /// `-C` arguments directly to the compiler.
  1665. #[allow(clippy::vec_init_then_push)]
  1666. fn cargo_build_arguments(&self, ctx: &BuildContext) -> Vec<String> {
  1667. let mut cargo_args = Vec::with_capacity(4);
  1668. // Add required profile flags. --release overrides any custom profiles.
  1669. cargo_args.push("--profile".to_string());
  1670. cargo_args.push(self.profile.to_string());
  1671. // Pass the appropriate target to cargo. We *always* specify a target which is somewhat helpful for preventing thrashing
  1672. cargo_args.push("--target".to_string());
  1673. cargo_args.push(self.triple.to_string());
  1674. // We always run in verbose since the CLI itself is the one doing the presentation
  1675. cargo_args.push("--verbose".to_string());
  1676. if self.no_default_features {
  1677. cargo_args.push("--no-default-features".to_string());
  1678. }
  1679. if !self.features.is_empty() {
  1680. cargo_args.push("--features".to_string());
  1681. cargo_args.push(self.features.join(" "));
  1682. }
  1683. // We *always* set the package since that's discovered from cargo metadata
  1684. cargo_args.push(String::from("-p"));
  1685. cargo_args.push(self.package.clone());
  1686. // Set the executable
  1687. match self.executable_type() {
  1688. TargetKind::Bin => cargo_args.push("--bin".to_string()),
  1689. TargetKind::Lib => cargo_args.push("--lib".to_string()),
  1690. TargetKind::Example => cargo_args.push("--example".to_string()),
  1691. _ => {}
  1692. };
  1693. cargo_args.push(self.executable_name().to_string());
  1694. // Merge in extra args. Order shouldn't really matter.
  1695. cargo_args.extend(self.extra_cargo_args.clone());
  1696. cargo_args.push("--".to_string());
  1697. cargo_args.extend(self.extra_rustc_args.clone());
  1698. // The bundle splitter needs relocation data to create a call-graph.
  1699. // This will automatically be erased by wasm-opt during the optimization step.
  1700. if self.platform == Platform::Web && self.wasm_split {
  1701. cargo_args.push("-Clink-args=--emit-relocs".to_string());
  1702. }
  1703. // dx *always* links android and thin builds
  1704. if self.custom_linker.is_some()
  1705. || matches!(ctx.mode, BuildMode::Thin { .. } | BuildMode::Fat)
  1706. {
  1707. cargo_args.push(format!(
  1708. "-Clinker={}",
  1709. Workspace::path_to_dx().expect("can't find dx").display()
  1710. ));
  1711. }
  1712. // Our fancy hot-patching engine needs a lot of customization to work properly.
  1713. //
  1714. // These args are mostly intended to be passed when *fat* linking but are generally fine to
  1715. // pass for both fat and thin linking.
  1716. //
  1717. // We need save-temps and no-dead-strip in both cases though. When we run `cargo rustc` with
  1718. // these args, they will be captured and re-ran for the fast compiles in the future, so whatever
  1719. // we set here will be set for all future hot patches too.
  1720. if matches!(ctx.mode, BuildMode::Thin { .. } | BuildMode::Fat) {
  1721. // rustc gives us some portable flags required:
  1722. // - link-dead-code: prevents rust from passing -dead_strip to the linker since that's the default.
  1723. // - save-temps=true: keeps the incremental object files around, which we need for manually linking.
  1724. cargo_args.extend_from_slice(&[
  1725. "-Csave-temps=true".to_string(),
  1726. "-Clink-dead-code".to_string(),
  1727. ]);
  1728. // We need to set some extra args that ensure all symbols make it into the final output
  1729. // and that the linker doesn't strip them out.
  1730. //
  1731. // This basically amounts of -all_load or --whole-archive, depending on the linker.
  1732. // We just assume an ld-like interface on macos and a gnu-ld interface elsewhere.
  1733. //
  1734. // macOS/iOS use ld64 but through the `cc` interface.
  1735. // cargo_args.push("-Clink-args=-Wl,-all_load".to_string());
  1736. //
  1737. // Linux and Android fit under this umbrella, both with the same clang-like entrypoint
  1738. // and the gnu-ld interface.
  1739. //
  1740. // cargo_args.push("-Clink-args=-Wl,--whole-archive".to_string());
  1741. //
  1742. // If windows -Wl,--whole-archive is required since it follows gnu-ld convention.
  1743. // There might be other flags on windows - we haven't tested windows thoroughly.
  1744. //
  1745. // cargo_args.push("-Clink-args=-Wl,--whole-archive".to_string());
  1746. // https://learn.microsoft.com/en-us/cpp/build/reference/wholearchive-include-all-library-object-files?view=msvc-170
  1747. //
  1748. // ------------------------------------------------------------
  1749. //
  1750. // if web, -Wl,--whole-archive is required since it follows gnu-ld convention.
  1751. //
  1752. // We also use --no-gc-sections and --export-table and --export-memory to push
  1753. // said symbols into the export table.
  1754. //
  1755. // We use --emit-relocs to build up a solid call graph.
  1756. //
  1757. // rust uses its own wasm-ld linker which can be found here (it's just gcc-ld with a `-target wasm` flag):
  1758. // - ~/.rustup/toolchains/stable-aarch64-apple-darwin/lib/rustlib/aarch64-apple-darwin/bin/gcc-ld
  1759. // - ~/.rustup/toolchains/stable-aarch64-apple-darwin/lib/rustlib/aarch64-apple-darwin/bin/gcc-ld/wasm-ld
  1760. //
  1761. // Note that we can't use --export-all, unfortunately, since some symbols are internal
  1762. // to wasm-bindgen and exporting them causes the JS generation to fail.
  1763. //
  1764. // We are basically replicating what emscripten does here with its dynamic linking
  1765. // approach where the MAIN_MODULE is very "fat" and exports the necessary arguments
  1766. // for the side modules to be linked in. This guide is really helpful:
  1767. //
  1768. // https://github.com/WebAssembly/tool-conventions/blob/main/DynamicLinking.md
  1769. //
  1770. // The tricky one is -Ctarget-cpu=mvp, which prevents rustc from generating externref
  1771. // entries.
  1772. //
  1773. // https://blog.rust-lang.org/2024/09/24/webassembly-targets-change-in-default-target-features/#disabling-on-by-default-webassembly-proposals
  1774. //
  1775. // It's fine that these exist in the base module but not in the patch.
  1776. if self.platform == Platform::Web
  1777. || self.triple.operating_system == OperatingSystem::Wasi
  1778. {
  1779. cargo_args.push("-Ctarget-cpu=mvp".into());
  1780. cargo_args.push("-Clink-arg=--no-gc-sections".into());
  1781. cargo_args.push("-Clink-arg=--growable-table".into());
  1782. cargo_args.push("-Clink-arg=--export-table".into());
  1783. cargo_args.push("-Clink-arg=--export-memory".into());
  1784. cargo_args.push("-Clink-arg=--emit-relocs".into());
  1785. cargo_args.push("-Clink-arg=--export=__stack_pointer".into());
  1786. cargo_args.push("-Clink-arg=--export=__heap_base".into());
  1787. cargo_args.push("-Clink-arg=--export=__data_end".into());
  1788. }
  1789. }
  1790. cargo_args
  1791. }
  1792. fn cargo_build_env_vars(&self, ctx: &BuildContext) -> Result<Vec<(&'static str, String)>> {
  1793. let mut env_vars = vec![];
  1794. // Make sure to set all the crazy android flags. Cross-compiling is hard, man.
  1795. if self.platform == Platform::Android {
  1796. env_vars.extend(self.android_env_vars()?);
  1797. };
  1798. // If we're either zero-linking or using a custom linker, make `dx` itself do the linking.
  1799. if self.custom_linker.is_some()
  1800. || matches!(ctx.mode, BuildMode::Thin { .. } | BuildMode::Fat)
  1801. {
  1802. LinkAction {
  1803. triple: self.triple.clone(),
  1804. linker: self.custom_linker.clone(),
  1805. link_err_file: dunce::canonicalize(self.link_err_file.path())?,
  1806. link_args_file: dunce::canonicalize(self.link_args_file.path())?,
  1807. }
  1808. .write_env_vars(&mut env_vars)?;
  1809. }
  1810. // Disable reference types on wasm when using hotpatching
  1811. // https://blog.rust-lang.org/2024/09/24/webassembly-targets-change-in-default-target-features/#disabling-on-by-default-webassembly-proposals
  1812. if self.platform == Platform::Web
  1813. && matches!(ctx.mode, BuildMode::Thin { .. } | BuildMode::Fat)
  1814. {
  1815. env_vars.push(("RUSTFLAGS", {
  1816. let mut rust_flags = std::env::var("RUSTFLAGS").unwrap_or_default();
  1817. rust_flags.push_str(" -Ctarget-cpu=mvp");
  1818. rust_flags
  1819. }));
  1820. }
  1821. if let Some(target_dir) = self.custom_target_dir.as_ref() {
  1822. env_vars.push(("CARGO_TARGET_DIR", target_dir.display().to_string()));
  1823. }
  1824. // If this is a release build, bake the base path and title into the binary with env vars.
  1825. // todo: should we even be doing this? might be better being a build.rs or something else.
  1826. if self.release {
  1827. if let Some(base_path) = self.base_path() {
  1828. env_vars.push((ASSET_ROOT_ENV, base_path.to_string()));
  1829. }
  1830. env_vars.push((APP_TITLE_ENV, self.config.web.app.title.clone()));
  1831. }
  1832. Ok(env_vars)
  1833. }
  1834. fn android_env_vars(&self) -> Result<Vec<(&'static str, String)>> {
  1835. let mut env_vars = vec![];
  1836. let tools = self.workspace.android_tools()?;
  1837. let linker = tools.android_cc(&self.triple);
  1838. let min_sdk_version = tools.min_sdk_version();
  1839. let ar_path = tools.ar_path();
  1840. let target_cc = tools.target_cc();
  1841. let target_cxx = tools.target_cxx();
  1842. let java_home = tools.java_home();
  1843. let ndk = tools.ndk.clone();
  1844. tracing::debug!(
  1845. r#"Using android:
  1846. min_sdk_version: {min_sdk_version}
  1847. linker: {linker:?}
  1848. ar_path: {ar_path:?}
  1849. target_cc: {target_cc:?}
  1850. target_cxx: {target_cxx:?}
  1851. java_home: {java_home:?}
  1852. "#
  1853. );
  1854. env_vars.push(("ANDROID_NATIVE_API_LEVEL", min_sdk_version.to_string()));
  1855. env_vars.push(("TARGET_AR", ar_path.display().to_string()));
  1856. env_vars.push(("TARGET_CC", target_cc.display().to_string()));
  1857. env_vars.push(("TARGET_CXX", target_cxx.display().to_string()));
  1858. env_vars.push(("ANDROID_NDK_ROOT", ndk.display().to_string()));
  1859. if let Some(java_home) = java_home {
  1860. tracing::debug!("Setting JAVA_HOME to {java_home:?}");
  1861. env_vars.push(("JAVA_HOME", java_home.display().to_string()));
  1862. }
  1863. // Set the wry env vars - this is where wry will dump its kotlin files.
  1864. // Their setup is really annyoing and requires us to hardcode `dx` to specific versions of tao/wry.
  1865. env_vars.push(("WRY_ANDROID_PACKAGE", "dev.dioxus.main".to_string()));
  1866. env_vars.push(("WRY_ANDROID_LIBRARY", "dioxusmain".to_string()));
  1867. env_vars.push((
  1868. "WRY_ANDROID_KOTLIN_FILES_OUT_DIR",
  1869. self.wry_android_kotlin_files_out_dir()
  1870. .display()
  1871. .to_string(),
  1872. ));
  1873. // Set the rust flags for android which get passed to *every* crate in the graph.
  1874. env_vars.push(("RUSTFLAGS", {
  1875. let mut rust_flags = std::env::var("RUSTFLAGS").unwrap_or_default();
  1876. rust_flags.push_str(" -Clink-arg=-landroid");
  1877. rust_flags.push_str(" -Clink-arg=-llog");
  1878. rust_flags.push_str(" -Clink-arg=-lOpenSLES");
  1879. rust_flags.push_str(" -Clink-arg=-Wl,--export-dynamic");
  1880. rust_flags
  1881. }));
  1882. // todo(jon): the guide for openssl recommends extending the path to include the tools dir
  1883. // in practice I couldn't get this to work, but this might eventually become useful.
  1884. //
  1885. // https://github.com/openssl/openssl/blob/master/NOTES-ANDROID.md#configuration
  1886. //
  1887. // They recommend a configuration like this:
  1888. //
  1889. // // export ANDROID_NDK_ROOT=/home/whoever/Android/android-sdk/ndk/20.0.5594570
  1890. // PATH=$ANDROID_NDK_ROOT/toolchains/llvm/prebuilt/linux-x86_64/bin:$ANDROID_NDK_ROOT/toolchains/arm-linux-androideabi-4.9/prebuilt/linux-x86_64/bin:$PATH
  1891. // ./Configure android-arm64 -D__ANDROID_API__=29
  1892. // make
  1893. //
  1894. // let tools_dir = arch.android_tools_dir(&ndk);
  1895. // let extended_path = format!(
  1896. // "{}:{}",
  1897. // tools_dir.display(),
  1898. // std::env::var("PATH").unwrap_or_default()
  1899. // );
  1900. // env_vars.push(("PATH", extended_path));
  1901. Ok(env_vars)
  1902. }
  1903. /// Get an estimate of the number of units in the crate. If nightly rustc is not available, this
  1904. /// will return an estimate of the number of units in the crate based on cargo metadata.
  1905. ///
  1906. /// TODO: always use <https://doc.rust-lang.org/nightly/cargo/reference/unstable.html#unit-graph> once it is stable
  1907. async fn get_unit_count_estimate(&self, ctx: &BuildContext) -> usize {
  1908. // Try to get it from nightly
  1909. if let Ok(count) = self.get_unit_count(ctx).await {
  1910. return count;
  1911. }
  1912. // Otherwise, use cargo metadata
  1913. let units = self
  1914. .workspace
  1915. .krates
  1916. .krates_filtered(krates::DepKind::Dev)
  1917. .iter()
  1918. .map(|k| k.targets.len())
  1919. .sum::<usize>();
  1920. (units as f64 / 3.5) as usize
  1921. }
  1922. /// Try to get the unit graph for the crate. This is a nightly only feature which may not be
  1923. /// available with the current version of rustc the user has installed.
  1924. ///
  1925. /// It also might not be super reliable - I think in practice it occasionally returns 2x the units.
  1926. async fn get_unit_count(&self, ctx: &BuildContext) -> crate::Result<usize> {
  1927. #[derive(Debug, Deserialize)]
  1928. struct UnitGraph {
  1929. units: Vec<serde_json::Value>,
  1930. }
  1931. let output = tokio::process::Command::new("cargo")
  1932. .arg("+nightly")
  1933. .arg("build")
  1934. .arg("--unit-graph")
  1935. .arg("-Z")
  1936. .arg("unstable-options")
  1937. .args(self.cargo_build_arguments(ctx))
  1938. .envs(self.cargo_build_env_vars(ctx)?)
  1939. .output()
  1940. .await?;
  1941. if !output.status.success() {
  1942. return Err(anyhow::anyhow!("Failed to get unit count").into());
  1943. }
  1944. let output_text = String::from_utf8(output.stdout).context("Failed to get unit count")?;
  1945. let graph: UnitGraph =
  1946. serde_json::from_str(&output_text).context("Failed to get unit count")?;
  1947. Ok(graph.units.len())
  1948. }
  1949. pub(crate) fn all_target_features(&self) -> Vec<String> {
  1950. let mut features = self.features.clone();
  1951. if !self.no_default_features {
  1952. features.extend(
  1953. self.package()
  1954. .features
  1955. .get("default")
  1956. .cloned()
  1957. .unwrap_or_default(),
  1958. );
  1959. }
  1960. features.dedup();
  1961. features
  1962. }
  1963. /// returns the path to root build folder. This will be our working directory for the build.
  1964. ///
  1965. /// we only add an extension to the folders where it sorta matters that it's named with the extension.
  1966. /// for example, on mac, the `.app` indicates we can `open` it and it pulls in icons, dylibs, etc.
  1967. ///
  1968. /// for our simulator-based platforms, this is less important since they need to be zipped up anyways
  1969. /// to run in the simulator.
  1970. ///
  1971. /// For windows/linux, it's also not important since we're just running the exe directly out of the folder
  1972. ///
  1973. /// The idea of this folder is that we can run our top-level build command against it and we'll get
  1974. /// a final build output somewhere. Some platforms have basically no build command, and can simply
  1975. /// be ran by executing the exe directly.
  1976. pub(crate) fn root_dir(&self) -> PathBuf {
  1977. let platform_dir = self.platform_dir();
  1978. match self.platform {
  1979. Platform::Web => platform_dir.join("public"),
  1980. Platform::Server => platform_dir.clone(), // ends up *next* to the public folder
  1981. // These might not actually need to be called `.app` but it does let us run these with `open`
  1982. Platform::MacOS => platform_dir.join(format!("{}.app", self.bundled_app_name())),
  1983. Platform::Ios => platform_dir.join(format!("{}.app", self.bundled_app_name())),
  1984. // in theory, these all could end up directly in the root dir
  1985. Platform::Android => platform_dir.join("app"), // .apk (after bundling)
  1986. Platform::Linux => platform_dir.join("app"), // .appimage (after bundling)
  1987. Platform::Windows => platform_dir.join("app"), // .exe (after bundling)
  1988. Platform::Liveview => platform_dir.join("app"), // .exe (after bundling)
  1989. }
  1990. }
  1991. fn platform_dir(&self) -> PathBuf {
  1992. self.build_dir(self.platform, self.release)
  1993. }
  1994. fn platform_exe_name(&self) -> String {
  1995. match self.platform {
  1996. Platform::MacOS => self.executable_name().to_string(),
  1997. Platform::Ios => self.executable_name().to_string(),
  1998. Platform::Server => self.executable_name().to_string(),
  1999. Platform::Liveview => self.executable_name().to_string(),
  2000. Platform::Windows => format!("{}.exe", self.executable_name()),
  2001. // from the apk spec, the root exe is a shared library
  2002. // we include the user's rust code as a shared library with a fixed namespace
  2003. Platform::Android => "libdioxusmain.so".to_string(),
  2004. // this will be wrong, I think, but not important?
  2005. Platform::Web => format!("{}_bg.wasm", self.executable_name()),
  2006. // todo: maybe this should be called AppRun?
  2007. Platform::Linux => self.executable_name().to_string(),
  2008. }
  2009. }
  2010. /// Assemble the android app dir.
  2011. ///
  2012. /// This is a bit of a mess since we need to create a lot of directories and files. Other approaches
  2013. /// would be to unpack some zip folder or something stored via `include_dir!()`. However, we do
  2014. /// need to customize the whole setup a bit, so it's just simpler (though messier) to do it this way.
  2015. fn build_android_app_dir(&self) -> Result<()> {
  2016. use std::fs::{create_dir_all, write};
  2017. let root = self.root_dir();
  2018. // gradle
  2019. let wrapper = root.join("gradle").join("wrapper");
  2020. create_dir_all(&wrapper)?;
  2021. // app
  2022. let app = root.join("app");
  2023. let app_main = app.join("src").join("main");
  2024. let app_kotlin = app_main.join("kotlin");
  2025. let app_jnilibs = app_main.join("jniLibs");
  2026. let app_assets = app_main.join("assets");
  2027. let app_kotlin_out = self.wry_android_kotlin_files_out_dir();
  2028. create_dir_all(&app)?;
  2029. create_dir_all(&app_main)?;
  2030. create_dir_all(&app_kotlin)?;
  2031. create_dir_all(&app_jnilibs)?;
  2032. create_dir_all(&app_assets)?;
  2033. create_dir_all(&app_kotlin_out)?;
  2034. tracing::debug!(
  2035. r#"Initialized android dirs:
  2036. - gradle: {wrapper:?}
  2037. - app/ {app:?}
  2038. - app/src: {app_main:?}
  2039. - app/src/kotlin: {app_kotlin:?}
  2040. - app/src/jniLibs: {app_jnilibs:?}
  2041. - app/src/assets: {app_assets:?}
  2042. - app/src/kotlin/main: {app_kotlin_out:?}
  2043. "#
  2044. );
  2045. // handlebars
  2046. #[derive(Serialize)]
  2047. struct AndroidHandlebarsObjects {
  2048. application_id: String,
  2049. app_name: String,
  2050. android_bundle: Option<crate::AndroidSettings>,
  2051. }
  2052. let hbs_data = AndroidHandlebarsObjects {
  2053. application_id: self.full_mobile_app_name(),
  2054. app_name: self.bundled_app_name(),
  2055. android_bundle: self.config.bundle.android.clone(),
  2056. };
  2057. let hbs = handlebars::Handlebars::new();
  2058. // Top-level gradle config
  2059. write(
  2060. root.join("build.gradle.kts"),
  2061. include_bytes!("../../assets/android/gen/build.gradle.kts"),
  2062. )?;
  2063. write(
  2064. root.join("gradle.properties"),
  2065. include_bytes!("../../assets/android/gen/gradle.properties"),
  2066. )?;
  2067. write(
  2068. root.join("gradlew"),
  2069. include_bytes!("../../assets/android/gen/gradlew"),
  2070. )?;
  2071. write(
  2072. root.join("gradlew.bat"),
  2073. include_bytes!("../../assets/android/gen/gradlew.bat"),
  2074. )?;
  2075. write(
  2076. root.join("settings.gradle"),
  2077. include_bytes!("../../assets/android/gen/settings.gradle"),
  2078. )?;
  2079. // Then the wrapper and its properties
  2080. write(
  2081. wrapper.join("gradle-wrapper.properties"),
  2082. include_bytes!("../../assets/android/gen/gradle/wrapper/gradle-wrapper.properties"),
  2083. )?;
  2084. write(
  2085. wrapper.join("gradle-wrapper.jar"),
  2086. include_bytes!("../../assets/android/gen/gradle/wrapper/gradle-wrapper.jar"),
  2087. )?;
  2088. // Now the app directory
  2089. write(
  2090. app.join("build.gradle.kts"),
  2091. hbs.render_template(
  2092. include_str!("../../assets/android/gen/app/build.gradle.kts.hbs"),
  2093. &hbs_data,
  2094. )?,
  2095. )?;
  2096. write(
  2097. app.join("proguard-rules.pro"),
  2098. include_bytes!("../../assets/android/gen/app/proguard-rules.pro"),
  2099. )?;
  2100. let manifest_xml = match self.config.application.android_manifest.as_deref() {
  2101. Some(manifest) => std::fs::read_to_string(self.package_manifest_dir().join(manifest))
  2102. .context("Failed to locate custom AndroidManifest.xml")?,
  2103. _ => hbs.render_template(
  2104. include_str!("../../assets/android/gen/app/src/main/AndroidManifest.xml.hbs"),
  2105. &hbs_data,
  2106. )?,
  2107. };
  2108. write(
  2109. app.join("src").join("main").join("AndroidManifest.xml"),
  2110. manifest_xml,
  2111. )?;
  2112. // Write the main activity manually since tao dropped support for it
  2113. write(
  2114. self.wry_android_kotlin_files_out_dir()
  2115. .join("MainActivity.kt"),
  2116. hbs.render_template(
  2117. include_str!("../../assets/android/MainActivity.kt.hbs"),
  2118. &hbs_data,
  2119. )?,
  2120. )?;
  2121. // Write the res folder, containing stuff like default icons, colors, and menubars.
  2122. let res = app_main.join("res");
  2123. create_dir_all(&res)?;
  2124. create_dir_all(res.join("values"))?;
  2125. write(
  2126. res.join("values").join("strings.xml"),
  2127. hbs.render_template(
  2128. include_str!("../../assets/android/gen/app/src/main/res/values/strings.xml.hbs"),
  2129. &hbs_data,
  2130. )?,
  2131. )?;
  2132. write(
  2133. res.join("values").join("colors.xml"),
  2134. include_bytes!("../../assets/android/gen/app/src/main/res/values/colors.xml"),
  2135. )?;
  2136. write(
  2137. res.join("values").join("styles.xml"),
  2138. include_bytes!("../../assets/android/gen/app/src/main/res/values/styles.xml"),
  2139. )?;
  2140. create_dir_all(res.join("drawable"))?;
  2141. write(
  2142. res.join("drawable").join("ic_launcher_background.xml"),
  2143. include_bytes!(
  2144. "../../assets/android/gen/app/src/main/res/drawable/ic_launcher_background.xml"
  2145. ),
  2146. )?;
  2147. create_dir_all(res.join("drawable-v24"))?;
  2148. write(
  2149. res.join("drawable-v24").join("ic_launcher_foreground.xml"),
  2150. include_bytes!(
  2151. "../../assets/android/gen/app/src/main/res/drawable-v24/ic_launcher_foreground.xml"
  2152. ),
  2153. )?;
  2154. create_dir_all(res.join("mipmap-anydpi-v26"))?;
  2155. write(
  2156. res.join("mipmap-anydpi-v26").join("ic_launcher.xml"),
  2157. include_bytes!(
  2158. "../../assets/android/gen/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml"
  2159. ),
  2160. )?;
  2161. create_dir_all(res.join("mipmap-hdpi"))?;
  2162. write(
  2163. res.join("mipmap-hdpi").join("ic_launcher.webp"),
  2164. include_bytes!(
  2165. "../../assets/android/gen/app/src/main/res/mipmap-hdpi/ic_launcher.webp"
  2166. ),
  2167. )?;
  2168. create_dir_all(res.join("mipmap-mdpi"))?;
  2169. write(
  2170. res.join("mipmap-mdpi").join("ic_launcher.webp"),
  2171. include_bytes!(
  2172. "../../assets/android/gen/app/src/main/res/mipmap-mdpi/ic_launcher.webp"
  2173. ),
  2174. )?;
  2175. create_dir_all(res.join("mipmap-xhdpi"))?;
  2176. write(
  2177. res.join("mipmap-xhdpi").join("ic_launcher.webp"),
  2178. include_bytes!(
  2179. "../../assets/android/gen/app/src/main/res/mipmap-xhdpi/ic_launcher.webp"
  2180. ),
  2181. )?;
  2182. create_dir_all(res.join("mipmap-xxhdpi"))?;
  2183. write(
  2184. res.join("mipmap-xxhdpi").join("ic_launcher.webp"),
  2185. include_bytes!(
  2186. "../../assets/android/gen/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp"
  2187. ),
  2188. )?;
  2189. create_dir_all(res.join("mipmap-xxxhdpi"))?;
  2190. write(
  2191. res.join("mipmap-xxxhdpi").join("ic_launcher.webp"),
  2192. include_bytes!(
  2193. "../../assets/android/gen/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp"
  2194. ),
  2195. )?;
  2196. Ok(())
  2197. }
  2198. fn wry_android_kotlin_files_out_dir(&self) -> PathBuf {
  2199. let mut kotlin_dir = self
  2200. .root_dir()
  2201. .join("app")
  2202. .join("src")
  2203. .join("main")
  2204. .join("kotlin");
  2205. for segment in "dev.dioxus.main".split('.') {
  2206. kotlin_dir = kotlin_dir.join(segment);
  2207. }
  2208. kotlin_dir
  2209. }
  2210. /// Get the directory where this app can write to for this session that's guaranteed to be stable
  2211. /// for the same app. This is useful for emitting state like window position and size.
  2212. ///
  2213. /// The directory is specific for this app and might be
  2214. pub(crate) fn session_cache_dir(&self) -> PathBuf {
  2215. self.session_cache_dir.path().to_path_buf()
  2216. }
  2217. /// Get the outdir specified by the Dioxus.toml, relative to the crate directory.
  2218. /// We don't support workspaces yet since that would cause a collision of bundles per project.
  2219. pub(crate) fn crate_out_dir(&self) -> Option<PathBuf> {
  2220. self.config
  2221. .application
  2222. .out_dir
  2223. .as_ref()
  2224. .map(|out_dir| self.crate_dir().join(out_dir))
  2225. }
  2226. /// Compose an out directory. Represents the typical "dist" directory that
  2227. /// is "distributed" after building an application (configurable in the
  2228. /// `Dioxus.toml`).
  2229. fn internal_out_dir(&self) -> PathBuf {
  2230. let dir = self.workspace_dir().join("target").join("dx");
  2231. std::fs::create_dir_all(&dir).unwrap();
  2232. dir
  2233. }
  2234. /// Create a workdir for the given platform
  2235. /// This can be used as a temporary directory for the build, but in an observable way such that
  2236. /// you can see the files in the directory via `target`
  2237. ///
  2238. /// target/dx/build/app/web/
  2239. /// target/dx/build/app/web/public/
  2240. /// target/dx/build/app/web/server.exe
  2241. pub(crate) fn build_dir(&self, platform: Platform, release: bool) -> PathBuf {
  2242. self.internal_out_dir()
  2243. .join(self.executable_name())
  2244. .join(if release { "release" } else { "debug" })
  2245. .join(platform.build_folder_name())
  2246. }
  2247. /// target/dx/bundle/app/
  2248. /// target/dx/bundle/app/blah.app
  2249. /// target/dx/bundle/app/blah.exe
  2250. /// target/dx/bundle/app/public/
  2251. pub(crate) fn bundle_dir(&self, platform: Platform) -> PathBuf {
  2252. self.internal_out_dir()
  2253. .join(self.executable_name())
  2254. .join("bundle")
  2255. .join(platform.build_folder_name())
  2256. }
  2257. /// Get the workspace directory for the crate
  2258. pub(crate) fn workspace_dir(&self) -> PathBuf {
  2259. self.workspace
  2260. .krates
  2261. .workspace_root()
  2262. .as_std_path()
  2263. .to_path_buf()
  2264. }
  2265. /// Get the directory of the crate
  2266. pub(crate) fn crate_dir(&self) -> PathBuf {
  2267. self.package()
  2268. .manifest_path
  2269. .parent()
  2270. .unwrap()
  2271. .as_std_path()
  2272. .to_path_buf()
  2273. }
  2274. /// Get the package we are currently in
  2275. pub(crate) fn package(&self) -> &krates::cm::Package {
  2276. &self.workspace.krates[self.crate_package]
  2277. }
  2278. /// Get the name of the package we are compiling
  2279. pub(crate) fn executable_name(&self) -> &str {
  2280. &self.crate_target.name
  2281. }
  2282. /// Get the type of executable we are compiling
  2283. pub(crate) fn executable_type(&self) -> TargetKind {
  2284. self.crate_target.kind[0]
  2285. }
  2286. /// Get the features required to build for the given platform
  2287. fn feature_for_platform(package: &krates::cm::Package, platform: Platform) -> String {
  2288. // Try to find the feature that activates the dioxus feature for the given platform
  2289. let dioxus_feature = platform.feature_name();
  2290. let res = package.features.iter().find_map(|(key, features)| {
  2291. // if the feature is just the name of the platform, we use that
  2292. if key == dioxus_feature {
  2293. return Some(key.clone());
  2294. }
  2295. // Otherwise look for the feature that starts with dioxus/ or dioxus?/ and matches the platform
  2296. for feature in features {
  2297. if let Some((_, after_dioxus)) = feature.split_once("dioxus") {
  2298. if let Some(dioxus_feature_enabled) =
  2299. after_dioxus.trim_start_matches('?').strip_prefix('/')
  2300. {
  2301. // If that enables the feature we are looking for, return that feature
  2302. if dioxus_feature_enabled == dioxus_feature {
  2303. return Some(key.clone());
  2304. }
  2305. }
  2306. }
  2307. }
  2308. None
  2309. });
  2310. res.unwrap_or_else(|| {
  2311. let fallback = format!("dioxus/{}", platform.feature_name()) ;
  2312. tracing::debug!(
  2313. "Could not find explicit feature for platform {platform}, passing `fallback` instead"
  2314. );
  2315. fallback
  2316. })
  2317. }
  2318. // The `opt-level=1` increases build times, but can noticeably decrease time
  2319. // between saving changes and being able to interact with an app (for wasm/web). The "overall"
  2320. // time difference (between having and not having the optimization) can be
  2321. // almost imperceptible (~1 s) but also can be very noticeable (~6 s) — depends
  2322. // on setup (hardware, OS, browser, idle load).
  2323. //
  2324. // Find or create the client and server profiles in the top-level Cargo.toml file
  2325. // todo(jon): we should/could make these optional by placing some defaults somewhere
  2326. pub(crate) fn initialize_profiles(&self) -> crate::Result<()> {
  2327. let config_path = self.workspace_dir().join("Cargo.toml");
  2328. let mut config = match std::fs::read_to_string(&config_path) {
  2329. Ok(config) => config.parse::<toml_edit::DocumentMut>().map_err(|e| {
  2330. crate::Error::Other(anyhow::anyhow!("Failed to parse Cargo.toml: {}", e))
  2331. })?,
  2332. Err(_) => Default::default(),
  2333. };
  2334. if let Item::Table(table) = config
  2335. .as_table_mut()
  2336. .entry("profile")
  2337. .or_insert(Item::Table(Default::default()))
  2338. {
  2339. if let toml_edit::Entry::Vacant(entry) = table.entry(PROFILE_WASM) {
  2340. let mut client = toml_edit::Table::new();
  2341. client.insert("inherits", Item::Value("dev".into()));
  2342. client.insert("opt-level", Item::Value(1.into()));
  2343. entry.insert(Item::Table(client));
  2344. }
  2345. if let toml_edit::Entry::Vacant(entry) = table.entry(PROFILE_SERVER) {
  2346. let mut server = toml_edit::Table::new();
  2347. server.insert("inherits", Item::Value("dev".into()));
  2348. entry.insert(Item::Table(server));
  2349. }
  2350. if let toml_edit::Entry::Vacant(entry) = table.entry(PROFILE_ANDROID) {
  2351. let mut android = toml_edit::Table::new();
  2352. android.insert("inherits", Item::Value("dev".into()));
  2353. entry.insert(Item::Table(android));
  2354. }
  2355. }
  2356. std::fs::write(config_path, config.to_string())
  2357. .context("Failed to write profiles to Cargo.toml")?;
  2358. Ok(())
  2359. }
  2360. /// Return the version of the wasm-bindgen crate if it exists
  2361. fn wasm_bindgen_version(&self) -> Option<String> {
  2362. self.workspace
  2363. .krates
  2364. .krates_by_name("wasm-bindgen")
  2365. .next()
  2366. .map(|krate| krate.krate.version.to_string())
  2367. }
  2368. /// Return the platforms that are enabled for the package
  2369. ///
  2370. /// Ideally only one platform is enabled but we need to be able to
  2371. pub(crate) fn enabled_cargo_toml_platforms(
  2372. package: &krates::cm::Package,
  2373. no_default_features: bool,
  2374. ) -> Vec<Platform> {
  2375. let mut platforms = vec![];
  2376. // Attempt to discover the platform directly from the dioxus dependency
  2377. //
  2378. // [dependencies]
  2379. // dioxus = { features = ["web"] }
  2380. //
  2381. if let Some(dxs) = package.dependencies.iter().find(|dep| dep.name == "dioxus") {
  2382. for f in dxs.features.iter() {
  2383. if let Some(platform) = Platform::autodetect_from_cargo_feature(f) {
  2384. platforms.push(platform);
  2385. }
  2386. }
  2387. }
  2388. // Start searching through the default features
  2389. //
  2390. // [features]
  2391. // default = ["dioxus/web"]
  2392. //
  2393. // or
  2394. //
  2395. // [features]
  2396. // default = ["web"]
  2397. // web = ["dioxus/web"]
  2398. if no_default_features {
  2399. return platforms;
  2400. }
  2401. let Some(default) = package.features.get("default") else {
  2402. return platforms;
  2403. };
  2404. // we only trace features 1 level deep..
  2405. for feature in default.iter() {
  2406. // If the user directly specified a platform we can just use that.
  2407. if feature.starts_with("dioxus/") {
  2408. let dx_feature = feature.trim_start_matches("dioxus/");
  2409. let auto = Platform::autodetect_from_cargo_feature(dx_feature);
  2410. if let Some(auto) = auto {
  2411. platforms.push(auto);
  2412. }
  2413. }
  2414. // If the user is specifying an internal feature that points to a platform, we can use that
  2415. let internal_feature = package.features.get(feature);
  2416. if let Some(internal_feature) = internal_feature {
  2417. for feature in internal_feature {
  2418. if feature.starts_with("dioxus/") {
  2419. let dx_feature = feature.trim_start_matches("dioxus/");
  2420. let auto = Platform::autodetect_from_cargo_feature(dx_feature);
  2421. if let Some(auto) = auto {
  2422. platforms.push(auto);
  2423. }
  2424. }
  2425. }
  2426. }
  2427. }
  2428. platforms.sort();
  2429. platforms.dedup();
  2430. platforms
  2431. }
  2432. /// Gather the features that are enabled for the package
  2433. fn platformless_features(package: &krates::cm::Package) -> Vec<String> {
  2434. let Some(default) = package.features.get("default") else {
  2435. return Vec::new();
  2436. };
  2437. let mut kept_features = vec![];
  2438. // Only keep the top-level features in the default list that don't point to a platform directly
  2439. // IE we want to drop `web` if default = ["web"]
  2440. 'top: for feature in default {
  2441. // Don't keep features that point to a platform via dioxus/blah
  2442. if feature.starts_with("dioxus/") {
  2443. let dx_feature = feature.trim_start_matches("dioxus/");
  2444. if Platform::autodetect_from_cargo_feature(dx_feature).is_some() {
  2445. continue 'top;
  2446. }
  2447. }
  2448. // Don't keep features that point to a platform via an internal feature
  2449. if let Some(internal_feature) = package.features.get(feature) {
  2450. for feature in internal_feature {
  2451. if feature.starts_with("dioxus/") {
  2452. let dx_feature = feature.trim_start_matches("dioxus/");
  2453. if Platform::autodetect_from_cargo_feature(dx_feature).is_some() {
  2454. continue 'top;
  2455. }
  2456. }
  2457. }
  2458. }
  2459. // Otherwise we can keep it
  2460. kept_features.push(feature.to_string());
  2461. }
  2462. kept_features
  2463. }
  2464. pub(crate) fn mobile_org(&self) -> String {
  2465. let identifier = self.bundle_identifier();
  2466. let mut split = identifier.splitn(3, '.');
  2467. let sub = split
  2468. .next()
  2469. .expect("Identifier to have at least 3 periods like `com.example.app`");
  2470. let tld = split
  2471. .next()
  2472. .expect("Identifier to have at least 3 periods like `com.example.app`");
  2473. format!("{}.{}", sub, tld)
  2474. }
  2475. pub(crate) fn bundled_app_name(&self) -> String {
  2476. use convert_case::{Case, Casing};
  2477. self.executable_name().to_case(Case::Pascal)
  2478. }
  2479. pub(crate) fn full_mobile_app_name(&self) -> String {
  2480. format!("{}.{}", self.mobile_org(), self.bundled_app_name())
  2481. }
  2482. pub(crate) fn bundle_identifier(&self) -> String {
  2483. if let Some(identifier) = self.config.bundle.identifier.clone() {
  2484. return identifier.clone();
  2485. }
  2486. format!("com.example.{}", self.bundled_app_name())
  2487. }
  2488. /// The item that we'll try to run directly if we need to.
  2489. ///
  2490. /// todo(jon): we should name the app properly instead of making up the exe name. It's kinda okay for dev mode, but def not okay for prod
  2491. pub(crate) fn main_exe(&self) -> PathBuf {
  2492. self.exe_dir().join(self.platform_exe_name())
  2493. }
  2494. /// Does the app specify:
  2495. ///
  2496. /// - Dioxus with "fullstack" enabled? (access to serverfns, etc)
  2497. /// - An explicit "fullstack" feature that enables said feature?
  2498. ///
  2499. /// Note that we don't detect if dependencies enable it transitively since we want to be explicit about it.
  2500. ///
  2501. /// The intention here is to detect if "fullstack" is enabled in the target's features list:
  2502. /// ```toml
  2503. /// [dependencies]
  2504. /// dioxus = { version = "0.4", features = ["fullstack"] }
  2505. /// ```
  2506. ///
  2507. /// or as an explicit feature in default:
  2508. /// ```toml
  2509. /// [features]
  2510. /// default = ["dioxus/fullstack"]
  2511. /// ```
  2512. ///
  2513. /// or as a default feature that enables the dioxus feature:
  2514. /// ```toml
  2515. /// [features]
  2516. /// default = ["fullstack"]
  2517. /// fullstack = ["dioxus/fullstack"]
  2518. /// ```
  2519. ///
  2520. /// or as an explicit feature (that enables the dioxus feature):
  2521. /// ```
  2522. /// dx serve app --features "fullstack"
  2523. /// ```
  2524. pub(crate) fn fullstack_feature_enabled(&self) -> bool {
  2525. let dioxus_dep = self
  2526. .package()
  2527. .dependencies
  2528. .iter()
  2529. .find(|dep| dep.name == "dioxus");
  2530. // If we don't have a dioxus dependency, we can't be fullstack. This shouldn't impact non-dioxus projects
  2531. let Some(dioxus_dep) = dioxus_dep else {
  2532. return false;
  2533. };
  2534. // Check if the dioxus dependency has the "fullstack" feature enabled
  2535. if dioxus_dep.features.iter().any(|f| f == "fullstack") {
  2536. return true;
  2537. }
  2538. // Check if any of the features in our feature list enables a feature that enables "fullstack"
  2539. let transitive = self
  2540. .package()
  2541. .features
  2542. .iter()
  2543. .filter(|(_name, list)| list.iter().any(|f| f == "dioxus/fullstack"));
  2544. for (name, _list) in transitive {
  2545. if self.features.contains(name) {
  2546. return true;
  2547. }
  2548. }
  2549. false
  2550. }
  2551. /// todo(jon): use handlebars templates instead of these prebaked templates
  2552. async fn write_metadata(&self) -> Result<()> {
  2553. // write the Info.plist file
  2554. match self.platform {
  2555. Platform::MacOS => {
  2556. let dest = self.root_dir().join("Contents").join("Info.plist");
  2557. let plist = self.info_plist_contents(self.platform)?;
  2558. std::fs::write(dest, plist)?;
  2559. }
  2560. Platform::Ios => {
  2561. let dest = self.root_dir().join("Info.plist");
  2562. let plist = self.info_plist_contents(self.platform)?;
  2563. std::fs::write(dest, plist)?;
  2564. }
  2565. // AndroidManifest.xml
  2566. // er.... maybe even all the kotlin/java/gradle stuff?
  2567. Platform::Android => {}
  2568. // Probably some custom format or a plist file (haha)
  2569. // When we do the proper bundle, we'll need to do something with wix templates, I think?
  2570. Platform::Windows => {}
  2571. // eventually we'll create the .appimage file, I guess?
  2572. Platform::Linux => {}
  2573. // These are served as folders, not appimages, so we don't need to do anything special (I think?)
  2574. // Eventually maybe write some secrets/.env files for the server?
  2575. // We could also distribute them as a deb/rpm for linux and msi for windows
  2576. Platform::Web => {}
  2577. Platform::Server => {}
  2578. Platform::Liveview => {}
  2579. }
  2580. Ok(())
  2581. }
  2582. /// Run the optimizers, obfuscators, minimizers, signers, etc
  2583. async fn optimize(&self, ctx: &BuildContext) -> Result<()> {
  2584. match self.platform {
  2585. Platform::Web => {
  2586. // Compress the asset dir
  2587. // If pre-compressing is enabled, we can pre_compress the wasm-bindgen output
  2588. let pre_compress = self.should_pre_compress_web_assets(self.release);
  2589. if pre_compress {
  2590. ctx.status_compressing_assets();
  2591. let asset_dir = self.asset_dir();
  2592. tokio::task::spawn_blocking(move || {
  2593. crate::fastfs::pre_compress_folder(&asset_dir, pre_compress)
  2594. })
  2595. .await
  2596. .unwrap()?;
  2597. }
  2598. }
  2599. Platform::MacOS => {}
  2600. Platform::Windows => {}
  2601. Platform::Linux => {}
  2602. Platform::Ios => {}
  2603. Platform::Android => {}
  2604. Platform::Server => {}
  2605. Platform::Liveview => {}
  2606. }
  2607. Ok(())
  2608. }
  2609. /// Check if assets should be pre_compressed. This will only be true in release mode if the user
  2610. /// has enabled pre_compress in the web config.
  2611. fn should_pre_compress_web_assets(&self, release: bool) -> bool {
  2612. self.config.web.pre_compress && release
  2613. }
  2614. /// Bundle the web app
  2615. /// - Run wasm-bindgen
  2616. /// - Bundle split
  2617. /// - Run wasm-opt
  2618. /// - Register the .wasm and .js files with the asset system
  2619. async fn bundle_web(
  2620. &self,
  2621. ctx: &BuildContext,
  2622. exe: &Path,
  2623. assets: &mut AssetManifest,
  2624. ) -> Result<()> {
  2625. use crate::{wasm_bindgen::WasmBindgen, wasm_opt};
  2626. use std::fmt::Write;
  2627. // Locate the output of the build files and the bindgen output
  2628. // We'll fill these in a second if they don't already exist
  2629. let bindgen_outdir = self.wasm_bindgen_out_dir();
  2630. let post_bindgen_wasm = self.wasm_bindgen_wasm_output_file();
  2631. let should_bundle_split: bool = self.wasm_split;
  2632. let bindgen_version = self
  2633. .wasm_bindgen_version()
  2634. .expect("this should have been checked by tool verification");
  2635. // Prepare any work dirs
  2636. std::fs::create_dir_all(&bindgen_outdir)?;
  2637. // Lift the internal functions to exports
  2638. if ctx.mode == BuildMode::Fat {
  2639. let unprocessed = std::fs::read(exe)?;
  2640. let all_exported_bytes = crate::build::prepare_wasm_base_module(&unprocessed)?;
  2641. std::fs::write(exe, all_exported_bytes)?;
  2642. }
  2643. // Prepare our configuration
  2644. //
  2645. // we turn off debug symbols in dev mode but leave them on in release mode (weird!) since
  2646. // wasm-opt and wasm-split need them to do better optimizations.
  2647. //
  2648. // We leave demangling to false since it's faster and these tools seem to prefer the raw symbols.
  2649. // todo(jon): investigate if the chrome extension needs them demangled or demangles them automatically.
  2650. let will_wasm_opt = (self.release || self.wasm_split)
  2651. && (self.workspace.wasm_opt.is_some() || cfg!(feature = "optimizations"));
  2652. let keep_debug = self.config.web.wasm_opt.debug
  2653. || self.debug_symbols
  2654. || self.wasm_split
  2655. || !self.release
  2656. || will_wasm_opt
  2657. || ctx.mode == BuildMode::Fat;
  2658. let keep_names = will_wasm_opt || ctx.mode == BuildMode::Fat;
  2659. let demangle = false;
  2660. let wasm_opt_options = WasmOptConfig {
  2661. memory_packing: self.wasm_split,
  2662. debug: self.debug_symbols,
  2663. ..self.config.web.wasm_opt.clone()
  2664. };
  2665. // Run wasm-bindgen. Some of the options are not "optimal" but will be fixed up by wasm-opt
  2666. //
  2667. // There's performance implications here. Running with --debug is slower than without
  2668. // We're keeping around lld sections and names but wasm-opt will fix them
  2669. // todo(jon): investigate a good balance of wiping debug symbols during dev (or doing a double build?)
  2670. ctx.status_wasm_bindgen_start();
  2671. tracing::debug!(dx_src = ?TraceSrc::Bundle, "Running wasm-bindgen");
  2672. let start = std::time::Instant::now();
  2673. WasmBindgen::new(&bindgen_version)
  2674. .input_path(exe)
  2675. .target("web")
  2676. .debug(keep_debug)
  2677. .demangle(demangle)
  2678. .keep_debug(keep_debug)
  2679. .keep_lld_sections(true)
  2680. .out_name(self.executable_name())
  2681. .out_dir(&bindgen_outdir)
  2682. .remove_name_section(!keep_names)
  2683. .remove_producers_section(!keep_names)
  2684. .run()
  2685. .await
  2686. .context("Failed to generate wasm-bindgen bindings")?;
  2687. tracing::debug!(dx_src = ?TraceSrc::Bundle, "wasm-bindgen complete in {:?}", start.elapsed());
  2688. // Run bundle splitting if the user has requested it
  2689. // It's pretty expensive but because of rayon should be running separate threads, hopefully
  2690. // not blocking this thread. Dunno if that's true
  2691. if should_bundle_split {
  2692. ctx.status_splitting_bundle();
  2693. if !will_wasm_opt {
  2694. return Err(anyhow::anyhow!(
  2695. "Bundle splitting requires wasm-opt to be installed or the CLI to be built with `--features optimizations`. Please install wasm-opt and try again."
  2696. )
  2697. .into());
  2698. }
  2699. // Load the contents of these binaries since we need both of them
  2700. // We're going to use the default makeLoad glue from wasm-split
  2701. let original = std::fs::read(exe)?;
  2702. let bindgened = std::fs::read(&post_bindgen_wasm)?;
  2703. let mut glue = wasm_split_cli::MAKE_LOAD_JS.to_string();
  2704. // Run the emitter
  2705. let splitter = wasm_split_cli::Splitter::new(&original, &bindgened);
  2706. let modules = splitter
  2707. .context("Failed to parse wasm for splitter")?
  2708. .emit()
  2709. .context("Failed to emit wasm split modules")?;
  2710. // Write the chunks that contain shared imports
  2711. // These will be in the format of chunk_0_modulename.wasm - this is hardcoded in wasm-split
  2712. tracing::debug!("Writing split chunks to disk");
  2713. for (idx, chunk) in modules.chunks.iter().enumerate() {
  2714. let path = bindgen_outdir.join(format!("chunk_{}_{}.wasm", idx, chunk.module_name));
  2715. wasm_opt::write_wasm(&chunk.bytes, &path, &wasm_opt_options).await?;
  2716. writeln!(
  2717. glue, "export const __wasm_split_load_chunk_{idx} = makeLoad(\"/assets/{url}\", [], fusedImports);",
  2718. url = assets
  2719. .register_asset(&path, AssetOptions::Unknown)?.bundled_path(),
  2720. )?;
  2721. }
  2722. // Write the modules that contain the entrypoints
  2723. tracing::debug!("Writing split modules to disk");
  2724. for (idx, module) in modules.modules.iter().enumerate() {
  2725. let comp_name = module
  2726. .component_name
  2727. .as_ref()
  2728. .context("generated bindgen module has no name?")?;
  2729. let path = bindgen_outdir.join(format!("module_{}_{}.wasm", idx, comp_name));
  2730. wasm_opt::write_wasm(&module.bytes, &path, &wasm_opt_options).await?;
  2731. let hash_id = module
  2732. .hash_id
  2733. .as_ref()
  2734. .context("generated wasm-split bindgen module has no hash id?")?;
  2735. writeln!(
  2736. glue,
  2737. "export const __wasm_split_load_{module}_{hash_id}_{comp_name} = makeLoad(\"/assets/{url}\", [{deps}], fusedImports);",
  2738. module = module.module_name,
  2739. // Again, register this wasm with the asset system
  2740. url = assets
  2741. .register_asset(&path, AssetOptions::Unknown)?.bundled_path(),
  2742. // This time, make sure to write the dependencies of this chunk
  2743. // The names here are again, hardcoded in wasm-split - fix this eventually.
  2744. deps = module
  2745. .relies_on_chunks
  2746. .iter()
  2747. .map(|idx| format!("__wasm_split_load_chunk_{idx}"))
  2748. .collect::<Vec<_>>()
  2749. .join(", ")
  2750. )?;
  2751. }
  2752. // Write the js binding
  2753. // It's not registered as an asset since it will get included in the main.js file
  2754. let js_output_path = bindgen_outdir.join("__wasm_split.js");
  2755. std::fs::write(&js_output_path, &glue)?;
  2756. // Make sure to write some entropy to the main.js file so it gets a new hash
  2757. // If we don't do this, the main.js file will be cached and never pick up the chunk names
  2758. let uuid = Uuid::new_v5(&Uuid::NAMESPACE_URL, glue.as_bytes());
  2759. std::fs::OpenOptions::new()
  2760. .append(true)
  2761. .open(self.wasm_bindgen_js_output_file())
  2762. .context("Failed to open main.js file")?
  2763. .write_all(format!("/*{uuid}*/").as_bytes())?;
  2764. // Write the main wasm_bindgen file and register it with the asset system
  2765. // This will overwrite the file in place
  2766. // We will wasm-opt it in just a second...
  2767. std::fs::write(&post_bindgen_wasm, modules.main.bytes)?;
  2768. }
  2769. if matches!(ctx.mode, BuildMode::Fat) {
  2770. // add `export { __wbg_get_imports };` to the end of the wasmbindgen js file
  2771. let mut js = std::fs::read(self.wasm_bindgen_js_output_file())?;
  2772. writeln!(js, "\nexport {{ __wbg_get_imports }};")?;
  2773. std::fs::write(self.wasm_bindgen_js_output_file(), js)?;
  2774. }
  2775. // Make sure to optimize the main wasm file if requested or if bundle splitting
  2776. if should_bundle_split || self.release {
  2777. ctx.status_optimizing_wasm();
  2778. wasm_opt::optimize(&post_bindgen_wasm, &post_bindgen_wasm, &wasm_opt_options).await?;
  2779. }
  2780. // In release mode, we make the wasm and bindgen files into assets so they get bundled with max
  2781. // optimizations.
  2782. let wasm_path = if self.release {
  2783. // Register the main.js with the asset system so it bundles in the snippets and optimizes
  2784. let name = assets.register_asset(
  2785. &self.wasm_bindgen_js_output_file(),
  2786. AssetOptions::Js(JsAssetOptions::new().with_minify(true).with_preload(true)),
  2787. )?;
  2788. format!("assets/{}", name.bundled_path())
  2789. } else {
  2790. let asset = self.wasm_bindgen_wasm_output_file();
  2791. format!("wasm/{}", asset.file_name().unwrap().to_str().unwrap())
  2792. };
  2793. let js_path = if self.release {
  2794. // Make sure to register the main wasm file with the asset system
  2795. let name = assets.register_asset(&post_bindgen_wasm, AssetOptions::Unknown)?;
  2796. format!("assets/{}", name.bundled_path())
  2797. } else {
  2798. let asset = self.wasm_bindgen_js_output_file();
  2799. format!("wasm/{}", asset.file_name().unwrap().to_str().unwrap())
  2800. };
  2801. // Write the index.html file with the pre-configured contents we got from pre-rendering
  2802. std::fs::write(
  2803. self.root_dir().join("index.html"),
  2804. self.prepare_html(assets, &wasm_path, &js_path)?,
  2805. )?;
  2806. Ok(())
  2807. }
  2808. fn info_plist_contents(&self, platform: Platform) -> Result<String> {
  2809. #[derive(Serialize)]
  2810. pub struct InfoPlistData {
  2811. pub display_name: String,
  2812. pub bundle_name: String,
  2813. pub bundle_identifier: String,
  2814. pub executable_name: String,
  2815. }
  2816. // Attempt to use the user's manually specified
  2817. let _app = &self.config.application;
  2818. match platform {
  2819. Platform::MacOS => {
  2820. if let Some(macos_info_plist) = _app.macos_info_plist.as_deref() {
  2821. return Ok(std::fs::read_to_string(macos_info_plist)?);
  2822. }
  2823. }
  2824. Platform::Ios => {
  2825. if let Some(macos_info_plist) = _app.ios_info_plist.as_deref() {
  2826. return Ok(std::fs::read_to_string(macos_info_plist)?);
  2827. }
  2828. }
  2829. _ => {}
  2830. }
  2831. match platform {
  2832. Platform::MacOS => handlebars::Handlebars::new()
  2833. .render_template(
  2834. include_str!("../../assets/macos/mac.plist.hbs"),
  2835. &InfoPlistData {
  2836. display_name: self.bundled_app_name(),
  2837. bundle_name: self.bundled_app_name(),
  2838. executable_name: self.platform_exe_name(),
  2839. bundle_identifier: self.bundle_identifier(),
  2840. },
  2841. )
  2842. .map_err(|e| e.into()),
  2843. Platform::Ios => handlebars::Handlebars::new()
  2844. .render_template(
  2845. include_str!("../../assets/ios/ios.plist.hbs"),
  2846. &InfoPlistData {
  2847. display_name: self.bundled_app_name(),
  2848. bundle_name: self.bundled_app_name(),
  2849. executable_name: self.platform_exe_name(),
  2850. bundle_identifier: self.bundle_identifier(),
  2851. },
  2852. )
  2853. .map_err(|e| e.into()),
  2854. _ => Err(anyhow::anyhow!("Unsupported platform for Info.plist").into()),
  2855. }
  2856. }
  2857. /// Run any final tools to produce apks or other artifacts we might need.
  2858. ///
  2859. /// This might include codesigning, zipping, creating an appimage, etc
  2860. async fn assemble(&self, ctx: &BuildContext) -> Result<()> {
  2861. if let Platform::Android = self.platform {
  2862. ctx.status_running_gradle();
  2863. // When the build mode is set to release and there is an Android signature configuration, use assembleRelease
  2864. let build_type = if self.release && self.config.bundle.android.is_some() {
  2865. "assembleRelease"
  2866. } else {
  2867. "assembleDebug"
  2868. };
  2869. let output = Command::new(self.gradle_exe()?)
  2870. .arg(build_type)
  2871. .current_dir(self.root_dir())
  2872. .output()
  2873. .await?;
  2874. if !output.status.success() {
  2875. return Err(anyhow::anyhow!("Failed to assemble apk: {output:?}").into());
  2876. }
  2877. }
  2878. Ok(())
  2879. }
  2880. /// Run bundleRelease and return the path to the `.aab` file
  2881. ///
  2882. /// <https://stackoverflow.com/questions/57072558/whats-the-difference-between-gradlewassemblerelease-gradlewinstallrelease-and>
  2883. pub(crate) async fn android_gradle_bundle(&self) -> Result<PathBuf> {
  2884. let output = Command::new(self.gradle_exe()?)
  2885. .arg("bundleRelease")
  2886. .current_dir(self.root_dir())
  2887. .output()
  2888. .await
  2889. .context("Failed to run gradle bundleRelease")?;
  2890. if !output.status.success() {
  2891. return Err(anyhow::anyhow!("Failed to bundleRelease: {output:?}").into());
  2892. }
  2893. let app_release = self
  2894. .root_dir()
  2895. .join("app")
  2896. .join("build")
  2897. .join("outputs")
  2898. .join("bundle")
  2899. .join("release");
  2900. // Rename it to Name-arch.aab
  2901. let from = app_release.join("app-release.aab");
  2902. let to = app_release.join(format!("{}-{}.aab", self.bundled_app_name(), self.triple));
  2903. std::fs::rename(from, &to).context("Failed to rename aab")?;
  2904. Ok(to)
  2905. }
  2906. fn gradle_exe(&self) -> Result<PathBuf> {
  2907. // make sure we can execute the gradlew script
  2908. #[cfg(unix)]
  2909. {
  2910. use std::os::unix::prelude::PermissionsExt;
  2911. std::fs::set_permissions(
  2912. self.root_dir().join("gradlew"),
  2913. std::fs::Permissions::from_mode(0o755),
  2914. )?;
  2915. }
  2916. let gradle_exec_name = match cfg!(windows) {
  2917. true => "gradlew.bat",
  2918. false => "gradlew",
  2919. };
  2920. Ok(self.root_dir().join(gradle_exec_name))
  2921. }
  2922. pub(crate) fn debug_apk_path(&self) -> PathBuf {
  2923. self.root_dir()
  2924. .join("app")
  2925. .join("build")
  2926. .join("outputs")
  2927. .join("apk")
  2928. .join("debug")
  2929. .join("app-debug.apk")
  2930. }
  2931. /// We only really currently care about:
  2932. ///
  2933. /// - app dir (.app, .exe, .apk, etc)
  2934. /// - assetas dir
  2935. /// - exe dir (.exe, .app, .apk, etc)
  2936. /// - extra scaffolding
  2937. ///
  2938. /// It's not guaranteed that they're different from any other folder
  2939. pub(crate) fn prepare_build_dir(&self) -> Result<()> {
  2940. use once_cell::sync::OnceCell;
  2941. use std::fs::{create_dir_all, remove_dir_all};
  2942. static INITIALIZED: OnceCell<Result<()>> = OnceCell::new();
  2943. let success = INITIALIZED.get_or_init(|| {
  2944. if self.platform != Platform::Server {
  2945. _ = remove_dir_all(self.exe_dir());
  2946. }
  2947. self.flush_session_cache();
  2948. create_dir_all(self.root_dir())?;
  2949. create_dir_all(self.exe_dir())?;
  2950. create_dir_all(self.asset_dir())?;
  2951. tracing::debug!(
  2952. r#"Initialized build dirs:
  2953. • root dir: {:?}
  2954. • exe dir: {:?}
  2955. • asset dir: {:?}"#,
  2956. self.root_dir(),
  2957. self.exe_dir(),
  2958. self.asset_dir(),
  2959. );
  2960. // we could download the templates from somewhere (github?) but after having banged my head against
  2961. // cargo-mobile2 for ages, I give up with that. We're literally just going to hardcode the templates
  2962. // by writing them here.
  2963. if let Platform::Android = self.platform {
  2964. self.build_android_app_dir()?;
  2965. }
  2966. Ok(())
  2967. });
  2968. if let Err(e) = success.as_ref() {
  2969. return Err(format!("Failed to initialize build directory: {e}").into());
  2970. }
  2971. Ok(())
  2972. }
  2973. pub(crate) fn asset_dir(&self) -> PathBuf {
  2974. match self.platform {
  2975. Platform::MacOS => self
  2976. .root_dir()
  2977. .join("Contents")
  2978. .join("Resources")
  2979. .join("assets"),
  2980. Platform::Android => self
  2981. .root_dir()
  2982. .join("app")
  2983. .join("src")
  2984. .join("main")
  2985. .join("assets"),
  2986. // everyone else is soooo normal, just app/assets :)
  2987. Platform::Web
  2988. | Platform::Ios
  2989. | Platform::Windows
  2990. | Platform::Linux
  2991. | Platform::Server
  2992. | Platform::Liveview => self.root_dir().join("assets"),
  2993. }
  2994. }
  2995. /// The directory in which we'll put the main exe
  2996. ///
  2997. /// Mac, Android, Web are a little weird
  2998. /// - mac wants to be in Contents/MacOS
  2999. /// - android wants to be in jniLibs/arm64-v8a (or others, depending on the platform / architecture)
  3000. /// - web wants to be in wasm (which... we don't really need to, we could just drop the wasm into public and it would work)
  3001. ///
  3002. /// I think all others are just in the root folder
  3003. ///
  3004. /// todo(jon): investigate if we need to put .wasm in `wasm`. It kinda leaks implementation details, which ideally we don't want to do.
  3005. fn exe_dir(&self) -> PathBuf {
  3006. match self.platform {
  3007. Platform::MacOS => self.root_dir().join("Contents").join("MacOS"),
  3008. Platform::Web => self.root_dir().join("wasm"),
  3009. // Android has a whole build structure to it
  3010. Platform::Android => self
  3011. .root_dir()
  3012. .join("app")
  3013. .join("src")
  3014. .join("main")
  3015. .join("jniLibs")
  3016. .join(AndroidTools::android_jnilib(&self.triple)),
  3017. // these are all the same, I think?
  3018. Platform::Windows
  3019. | Platform::Linux
  3020. | Platform::Ios
  3021. | Platform::Server
  3022. | Platform::Liveview => self.root_dir(),
  3023. }
  3024. }
  3025. /// Get the path to the wasm bindgen temporary output folder
  3026. fn wasm_bindgen_out_dir(&self) -> PathBuf {
  3027. self.root_dir().join("wasm")
  3028. }
  3029. /// Get the path to the wasm bindgen javascript output file
  3030. pub(crate) fn wasm_bindgen_js_output_file(&self) -> PathBuf {
  3031. self.wasm_bindgen_out_dir()
  3032. .join(self.executable_name())
  3033. .with_extension("js")
  3034. }
  3035. /// Get the path to the wasm bindgen wasm output file
  3036. pub(crate) fn wasm_bindgen_wasm_output_file(&self) -> PathBuf {
  3037. self.wasm_bindgen_out_dir()
  3038. .join(format!("{}_bg", self.executable_name()))
  3039. .with_extension("wasm")
  3040. }
  3041. /// Get the path to the asset optimizer version file
  3042. pub(crate) fn asset_optimizer_version_file(&self) -> PathBuf {
  3043. self.platform_dir().join(".cli-version")
  3044. }
  3045. fn flush_session_cache(&self) {
  3046. let cache_dir = self.session_cache_dir();
  3047. _ = std::fs::remove_dir_all(&cache_dir);
  3048. _ = std::fs::create_dir_all(&cache_dir);
  3049. }
  3050. /// Check for tooling that might be required for this build.
  3051. ///
  3052. /// This should generally be only called on the first build since it takes time to verify the tooling
  3053. /// is in place, and we don't want to slow down subsequent builds.
  3054. pub(crate) async fn verify_tooling(&self, ctx: &BuildContext) -> Result<()> {
  3055. ctx.status_installing_tooling();
  3056. self
  3057. .initialize_profiles()
  3058. .context("Failed to initialize profiles - dioxus can't build without them. You might need to initialize them yourself.")?;
  3059. match self.platform {
  3060. Platform::Web => self.verify_web_tooling().await?,
  3061. Platform::Ios => self.verify_ios_tooling().await?,
  3062. Platform::Android => self.verify_android_tooling().await?,
  3063. Platform::Linux => self.verify_linux_tooling().await?,
  3064. Platform::MacOS | Platform::Windows | Platform::Server | Platform::Liveview => {}
  3065. }
  3066. Ok(())
  3067. }
  3068. async fn verify_web_tooling(&self) -> Result<()> {
  3069. // Install target using rustup.
  3070. #[cfg(not(feature = "no-downloads"))]
  3071. if !self.workspace.has_wasm32_unknown_unknown() {
  3072. tracing::info!(
  3073. "Web platform requires wasm32-unknown-unknown to be installed. Installing..."
  3074. );
  3075. let _ = tokio::process::Command::new("rustup")
  3076. .args(["target", "add", "wasm32-unknown-unknown"])
  3077. .output()
  3078. .await?;
  3079. }
  3080. // Ensure target is installed.
  3081. if !self.workspace.has_wasm32_unknown_unknown() {
  3082. return Err(Error::Other(anyhow::anyhow!(
  3083. "Missing target wasm32-unknown-unknown."
  3084. )));
  3085. }
  3086. // Wasm bindgen
  3087. let krate_bindgen_version = self.wasm_bindgen_version().ok_or(anyhow::anyhow!(
  3088. "failed to detect wasm-bindgen version, unable to proceed"
  3089. ))?;
  3090. WasmBindgen::verify_install(&krate_bindgen_version).await?;
  3091. Ok(())
  3092. }
  3093. /// Currently does nothing, but eventually we need to check that the mobile tooling is installed.
  3094. ///
  3095. /// For ios, this would be just aarch64-apple-ios + aarch64-apple-ios-sim, as well as xcrun and xcode-select
  3096. ///
  3097. /// We don't auto-install these yet since we're not doing an architecture check. We assume most users
  3098. /// are running on an Apple Silicon Mac, but it would be confusing if we installed these when we actually
  3099. /// should be installing the x86 versions.
  3100. async fn verify_ios_tooling(&self) -> Result<()> {
  3101. // open the simulator
  3102. // _ = tokio::process::Command::new("open")
  3103. // .arg("/Applications/Xcode.app/Contents/Developer/Applications/Simulator.app")
  3104. // .output()
  3105. // .await;
  3106. // Now xcrun to open the device
  3107. // todo: we should try and query the device list and/or parse it rather than hardcode this simulator
  3108. // _ = tokio::process::Command::new("xcrun")
  3109. // .args(["simctl", "boot", "83AE3067-987F-4F85-AE3D-7079EF48C967"])
  3110. // .output()
  3111. // .await;
  3112. // if !rustup
  3113. // .installed_toolchains
  3114. // .contains(&"aarch64-apple-ios".to_string())
  3115. // {
  3116. // tracing::error!("You need to install aarch64-apple-ios to build for ios. Run `rustup target add aarch64-apple-ios` to install it.");
  3117. // }
  3118. // if !rustup
  3119. // .installed_toolchains
  3120. // .contains(&"aarch64-apple-ios-sim".to_string())
  3121. // {
  3122. // tracing::error!("You need to install aarch64-apple-ios to build for ios. Run `rustup target add aarch64-apple-ios` to install it.");
  3123. // }
  3124. Ok(())
  3125. }
  3126. /// Check if the android tooling is installed
  3127. ///
  3128. /// looks for the android sdk + ndk
  3129. ///
  3130. /// will do its best to fill in the missing bits by exploring the sdk structure
  3131. /// IE will attempt to use the Java installed from android studio if possible.
  3132. async fn verify_android_tooling(&self) -> Result<()> {
  3133. let linker = self.workspace.android_tools()?.android_cc(&self.triple);
  3134. tracing::debug!("Verifying android linker: {linker:?}");
  3135. if linker.exists() {
  3136. return Ok(());
  3137. }
  3138. Err(anyhow::anyhow!(
  3139. "Android linker not found. Please set the `ANDROID_NDK_HOME` environment variable to the root of your NDK installation."
  3140. ).into())
  3141. }
  3142. /// Ensure the right dependencies are installed for linux apps.
  3143. /// This varies by distro, so we just do nothing for now.
  3144. ///
  3145. /// Eventually, we want to check for the prereqs for wry/tao as outlined by tauri:
  3146. /// <https://tauri.app/start/prerequisites/>
  3147. async fn verify_linux_tooling(&self) -> Result<()> {
  3148. Ok(())
  3149. }
  3150. /// update the mtime of the "main" file to bust the fingerprint, forcing rustc to recompile it.
  3151. ///
  3152. /// This prevents rustc from using the cached version of the binary, which can cause issues
  3153. /// with our hotpatching setup since it uses linker interception.
  3154. ///
  3155. /// This is sadly a hack. I think there might be other ways of busting the fingerprint (rustc wrapper?)
  3156. /// but that would require relying on cargo internals.
  3157. ///
  3158. /// This might stop working if/when cargo stabilizes contents-based fingerprinting.
  3159. fn bust_fingerprint(&self, ctx: &BuildContext) -> Result<()> {
  3160. // if matches!(ctx.mode, BuildMode::Fat | BuildMode::Base) {
  3161. if !matches!(ctx.mode, BuildMode::Thin { .. }) {
  3162. std::fs::File::open(&self.crate_target.src_path)?.set_modified(SystemTime::now())?;
  3163. }
  3164. Ok(())
  3165. }
  3166. async fn create_patch_cache(&self, exe: &Path) -> Result<HotpatchModuleCache> {
  3167. let exe = match self.platform {
  3168. Platform::Web => self.wasm_bindgen_wasm_output_file(),
  3169. _ => exe.to_path_buf(),
  3170. };
  3171. Ok(HotpatchModuleCache::new(&exe, &self.triple)?)
  3172. }
  3173. /// Users create an index.html for their SPA if they want it
  3174. ///
  3175. /// We always write our wasm as main.js and main_bg.wasm
  3176. ///
  3177. /// In prod we run the optimizer which bundles everything together properly
  3178. ///
  3179. /// So their index.html needs to include main.js in the scripts otherwise nothing happens?
  3180. ///
  3181. /// Seems like every platform has a weird file that declares a bunch of stuff
  3182. /// - web: index.html
  3183. /// - ios: info.plist
  3184. /// - macos: info.plist
  3185. /// - linux: appimage root thing?
  3186. /// - android: androidmanifest.xml
  3187. ///
  3188. /// You also might different variants of these files (staging / prod) and different flavors (eu/us)
  3189. ///
  3190. /// web's index.html is weird since it's not just a bundle format but also a *content* format
  3191. pub(crate) fn prepare_html(
  3192. &self,
  3193. assets: &AssetManifest,
  3194. wasm_path: &str,
  3195. js_path: &str,
  3196. ) -> Result<String> {
  3197. let mut html = {
  3198. const DEV_DEFAULT_HTML: &str = include_str!("../../assets/web/dev.index.html");
  3199. const PROD_DEFAULT_HTML: &str = include_str!("../../assets/web/prod.index.html");
  3200. let crate_root: &Path = &self.crate_dir();
  3201. let custom_html_file = crate_root.join("index.html");
  3202. let default_html = match self.release {
  3203. true => PROD_DEFAULT_HTML,
  3204. false => DEV_DEFAULT_HTML,
  3205. };
  3206. std::fs::read_to_string(custom_html_file).unwrap_or_else(|_| String::from(default_html))
  3207. };
  3208. // Inject any resources from the config into the html
  3209. self.inject_resources(assets, &mut html)?;
  3210. // Inject loading scripts if they are not already present
  3211. self.inject_loading_scripts(&mut html);
  3212. // Replace any special placeholders in the HTML with resolved values
  3213. self.replace_template_placeholders(&mut html, wasm_path, js_path);
  3214. let title = self.config.web.app.title.clone();
  3215. Self::replace_or_insert_before("{app_title}", "</title", &title, &mut html);
  3216. Ok(html)
  3217. }
  3218. fn is_dev_build(&self) -> bool {
  3219. !self.release
  3220. }
  3221. // Inject any resources from the config into the html
  3222. fn inject_resources(&self, assets: &AssetManifest, html: &mut String) -> Result<()> {
  3223. use std::fmt::Write;
  3224. // Collect all resources into a list of styles and scripts
  3225. let resources = &self.config.web.resource;
  3226. let mut style_list = resources.style.clone().unwrap_or_default();
  3227. let mut script_list = resources.script.clone().unwrap_or_default();
  3228. if self.is_dev_build() {
  3229. style_list.extend(resources.dev.style.iter().cloned());
  3230. script_list.extend(resources.dev.script.iter().cloned());
  3231. }
  3232. let mut head_resources = String::new();
  3233. // Add all styles to the head
  3234. for style in &style_list {
  3235. writeln!(
  3236. &mut head_resources,
  3237. "<link rel=\"stylesheet\" href=\"{}\">",
  3238. &style.to_str().unwrap(),
  3239. )?;
  3240. }
  3241. // Add all scripts to the head
  3242. for script in &script_list {
  3243. writeln!(
  3244. &mut head_resources,
  3245. "<script src=\"{}\"></script>",
  3246. &script.to_str().unwrap(),
  3247. )?;
  3248. }
  3249. // Add the base path to the head if this is a debug build
  3250. if self.is_dev_build() {
  3251. if let Some(base_path) = &self.base_path() {
  3252. head_resources.push_str(&format_base_path_meta_element(base_path));
  3253. }
  3254. }
  3255. // Inject any resources from manganis into the head
  3256. for asset in assets.assets.values() {
  3257. let asset_path = asset.bundled_path();
  3258. match asset.options() {
  3259. AssetOptions::Css(css_options) => {
  3260. if css_options.preloaded() {
  3261. head_resources.push_str(&format!(
  3262. "<link rel=\"preload\" as=\"style\" href=\"/{{base_path}}/assets/{asset_path}\" crossorigin>"
  3263. ))
  3264. }
  3265. }
  3266. AssetOptions::Image(image_options) => {
  3267. if image_options.preloaded() {
  3268. head_resources.push_str(&format!(
  3269. "<link rel=\"preload\" as=\"image\" href=\"/{{base_path}}/assets/{asset_path}\" crossorigin>"
  3270. ))
  3271. }
  3272. }
  3273. AssetOptions::Js(js_options) => {
  3274. if js_options.preloaded() {
  3275. head_resources.push_str(&format!(
  3276. "<link rel=\"preload\" as=\"script\" href=\"/{{base_path}}/assets/{asset_path}\" crossorigin>"
  3277. ))
  3278. }
  3279. }
  3280. _ => {}
  3281. }
  3282. }
  3283. // Manually inject the wasm file for preloading. WASM currently doesn't support preloading in the manganis asset system
  3284. let wasm_source_path = self.wasm_bindgen_wasm_output_file();
  3285. if let Some(wasm_path) = assets.assets.get(&wasm_source_path) {
  3286. let wasm_path = wasm_path.bundled_path();
  3287. head_resources.push_str(&format!(
  3288. "<link rel=\"preload\" as=\"fetch\" type=\"application/wasm\" href=\"/{{base_path}}/assets/{wasm_path}\" crossorigin>"
  3289. ));
  3290. Self::replace_or_insert_before("{style_include}", "</head", &head_resources, html);
  3291. }
  3292. Ok(())
  3293. }
  3294. /// Inject loading scripts if they are not already present
  3295. fn inject_loading_scripts(&self, html: &mut String) {
  3296. // If it looks like we are already loading wasm or the current build opted out of injecting loading scripts, don't inject anything
  3297. if !self.inject_loading_scripts || html.contains("__wbindgen_start") {
  3298. return;
  3299. }
  3300. // If not, insert the script
  3301. *html = html.replace(
  3302. "</body",
  3303. r#" <script>
  3304. // We can't use a module script here because we need to start the script immediately when streaming
  3305. import("/{base_path}/{js_path}").then(
  3306. ({ default: init, initSync, __wbg_get_imports }) => {
  3307. // export initSync in case a split module needs to initialize
  3308. window.__wasm_split_main_initSync = initSync;
  3309. // Actually perform the load
  3310. init({module_or_path: "/{base_path}/{wasm_path}"}).then((wasm) => {
  3311. // assign this module to be accessible globally
  3312. window.__dx_mainWasm = wasm;
  3313. window.__dx_mainInit = init;
  3314. window.__dx_mainInitSync = initSync;
  3315. window.__dx___wbg_get_imports = __wbg_get_imports;
  3316. if (wasm.__wbindgen_start == undefined) {
  3317. wasm.main();
  3318. }
  3319. });
  3320. }
  3321. );
  3322. </script>
  3323. </body"#,
  3324. );
  3325. }
  3326. /// Replace any special placeholders in the HTML with resolved values
  3327. fn replace_template_placeholders(&self, html: &mut String, wasm_path: &str, js_path: &str) {
  3328. let base_path = self.base_path_or_default();
  3329. *html = html.replace("{base_path}", base_path);
  3330. let app_name = &self.executable_name();
  3331. // If the html contains the old `{app_name}` placeholder, replace {app_name}_bg.wasm and {app_name}.js
  3332. // with the new paths
  3333. *html = html.replace("wasm/{app_name}_bg.wasm", wasm_path);
  3334. *html = html.replace("wasm/{app_name}.js", js_path);
  3335. // Otherwise replace the new placeholders
  3336. *html = html.replace("{wasm_path}", wasm_path);
  3337. *html = html.replace("{js_path}", js_path);
  3338. // Replace the app_name if we find it anywhere standalone
  3339. *html = html.replace("{app_name}", app_name);
  3340. }
  3341. /// Replace a string or insert the new contents before a marker
  3342. fn replace_or_insert_before(
  3343. replace: &str,
  3344. or_insert_before: &str,
  3345. with: &str,
  3346. content: &mut String,
  3347. ) {
  3348. if content.contains(replace) {
  3349. *content = content.replace(replace, with);
  3350. } else if let Some(pos) = content.find(or_insert_before) {
  3351. content.insert_str(pos, with);
  3352. }
  3353. }
  3354. /// Get the base path from the config or None if this is not a web or server build
  3355. pub(crate) fn base_path(&self) -> Option<&str> {
  3356. self.config
  3357. .web
  3358. .app
  3359. .base_path
  3360. .as_deref()
  3361. .filter(|_| matches!(self.platform, Platform::Web | Platform::Server))
  3362. }
  3363. /// Get the normalized base path for the application with `/` trimmed from both ends. If the base path is not set, this will return `.`.
  3364. pub(crate) fn base_path_or_default(&self) -> &str {
  3365. let trimmed_path = self.base_path().unwrap_or_default().trim_matches('/');
  3366. if trimmed_path.is_empty() {
  3367. "."
  3368. } else {
  3369. trimmed_path
  3370. }
  3371. }
  3372. /// Get the path to the package manifest directory
  3373. pub(crate) fn package_manifest_dir(&self) -> PathBuf {
  3374. self.workspace.krates[self.crate_package]
  3375. .manifest_path
  3376. .parent()
  3377. .unwrap()
  3378. .to_path_buf()
  3379. .into()
  3380. }
  3381. pub(crate) async fn start_simulators(&self) -> Result<()> {
  3382. if self.device {
  3383. return Ok(());
  3384. }
  3385. match self.platform {
  3386. // Boot an iOS simulator if one is not already running.
  3387. //
  3388. // We always choose the most recently opened simulator based on the xcrun list.
  3389. // Note that simulators can be running but the simulator app itself is not open.
  3390. // Calling `open::that` is always fine, even on running apps, since apps are singletons.
  3391. Platform::Ios => {
  3392. #[derive(Deserialize, Debug)]
  3393. struct XcrunListJson {
  3394. // "com.apple.CoreSimulator.SimRuntime.iOS-18-4": [{}, {}, {}]
  3395. devices: BTreeMap<String, Vec<XcrunDevice>>,
  3396. }
  3397. #[derive(Deserialize, Debug)]
  3398. struct XcrunDevice {
  3399. #[serde(rename = "lastBootedAt")]
  3400. last_booted_at: Option<String>,
  3401. udid: String,
  3402. name: String,
  3403. state: String,
  3404. }
  3405. let xcrun_list = Command::new("xcrun")
  3406. .arg("simctl")
  3407. .arg("list")
  3408. .arg("-j")
  3409. .output()
  3410. .await?;
  3411. let as_str = String::from_utf8_lossy(&xcrun_list.stdout);
  3412. let xcrun_list_json = serde_json::from_str::<XcrunListJson>(as_str.trim());
  3413. if let Ok(xcrun_list_json) = xcrun_list_json {
  3414. if xcrun_list_json.devices.is_empty() {
  3415. tracing::warn!(
  3416. "No iOS sdks installed found. Please install the iOS SDK in Xcode."
  3417. );
  3418. }
  3419. if let Some((_rt, devices)) = xcrun_list_json.devices.iter().next() {
  3420. if devices.iter().all(|device| device.state != "Booted") {
  3421. let last_booted =
  3422. devices
  3423. .iter()
  3424. .max_by_key(|device| match device.last_booted_at {
  3425. Some(ref last_booted) => last_booted,
  3426. None => "2000-01-01T01:01:01Z",
  3427. });
  3428. if let Some(device) = last_booted {
  3429. tracing::info!("Booting iOS simulator: \"{}\"", device.name);
  3430. Command::new("xcrun")
  3431. .arg("simctl")
  3432. .arg("boot")
  3433. .arg(&device.udid)
  3434. .output()
  3435. .await?;
  3436. }
  3437. }
  3438. }
  3439. }
  3440. let path_to_xcode = Command::new("xcode-select")
  3441. .arg("--print-path")
  3442. .output()
  3443. .await?;
  3444. let path_to_xcode: PathBuf = String::from_utf8_lossy(&path_to_xcode.stdout)
  3445. .as_ref()
  3446. .trim()
  3447. .into();
  3448. let path_to_sim = path_to_xcode.join("Applications").join("Simulator.app");
  3449. open::that(path_to_sim)?;
  3450. }
  3451. Platform::Android => {
  3452. let tools = self.workspace.android_tools()?;
  3453. tokio::spawn(async move {
  3454. let emulator = tools.emulator();
  3455. let avds = Command::new(&emulator)
  3456. .arg("-list-avds")
  3457. .output()
  3458. .await
  3459. .unwrap();
  3460. let avds = String::from_utf8_lossy(&avds.stdout);
  3461. let avd = avds.trim().lines().next().map(|s| s.trim().to_string());
  3462. if let Some(avd) = avd {
  3463. tracing::info!("Booting Android emulator: \"{avd}\"");
  3464. Command::new(&emulator)
  3465. .arg("-avd")
  3466. .arg(avd)
  3467. .args(["-netdelay", "none", "-netspeed", "full"])
  3468. .stdout(std::process::Stdio::null()) // prevent accumulating huge amounts of mem usage
  3469. .stderr(std::process::Stdio::null()) // prevent accumulating huge amounts of mem usage
  3470. .output()
  3471. .await
  3472. .unwrap();
  3473. } else {
  3474. tracing::warn!("No Android emulators found. Please create one using `emulator -avd <name>`");
  3475. }
  3476. });
  3477. }
  3478. _ => {
  3479. // nothing - maybe on the web we should open the browser?
  3480. }
  3481. };
  3482. Ok(())
  3483. }
  3484. }