request.rs 177 KB

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