request.rs 171 KB

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