Jsrt.cpp 186 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft. All rights reserved.
  3. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  4. //-------------------------------------------------------------------------------------------------------
  5. #include "JsrtPch.h"
  6. #include "JsrtInternal.h"
  7. #include "JsrtExternalObject.h"
  8. #include "JsrtExternalArrayBuffer.h"
  9. #include "jsrtHelper.h"
  10. #include "JsrtSourceHolder.h"
  11. #include "ByteCode/ByteCodeSerializer.h"
  12. #include "Common/ByteSwap.h"
  13. #include "Library/DataView.h"
  14. #include "Library/JavascriptExceptionMetadata.h"
  15. #include "Library/JavascriptSymbol.h"
  16. #include "Library/JavascriptPromise.h"
  17. #include "Base/ThreadContextTlsEntry.h"
  18. #include "Codex/Utf8Helper.h"
  19. // Parser Includes
  20. #include "cmperr.h" // For ERRnoMemory
  21. #include "screrror.h" // For CompileScriptException
  22. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  23. #include "TestHooksRt.h"
  24. #endif
  25. struct CodexHeapAllocatorInterface
  26. {
  27. public:
  28. static void* allocate(size_t size)
  29. {
  30. return HeapNewArray(char, size);
  31. }
  32. static void free(void* ptr, size_t count)
  33. {
  34. HeapDeleteArray(count, (char*) ptr);
  35. }
  36. };
  37. JsErrorCode CheckContext(JsrtContext *currentContext, bool verifyRuntimeState,
  38. bool allowInObjectBeforeCollectCallback)
  39. {
  40. if (currentContext == nullptr)
  41. {
  42. return JsErrorNoCurrentContext;
  43. }
  44. // We don't need parameter check if it's checked in previous wrapper.
  45. if (verifyRuntimeState)
  46. {
  47. Js::ScriptContext *scriptContext = currentContext->GetScriptContext();
  48. Assert(scriptContext != nullptr);
  49. Recycler *recycler = scriptContext->GetRecycler();
  50. ThreadContext *threadContext = scriptContext->GetThreadContext();
  51. if (recycler && recycler->IsHeapEnumInProgress())
  52. {
  53. return JsErrorHeapEnumInProgress;
  54. }
  55. else if (!allowInObjectBeforeCollectCallback &&
  56. recycler && recycler->IsInObjectBeforeCollectCallback())
  57. {
  58. return JsErrorInObjectBeforeCollectCallback;
  59. }
  60. else if (threadContext->IsExecutionDisabled())
  61. {
  62. return JsErrorInDisabledState;
  63. }
  64. else if (scriptContext->IsInProfileCallback())
  65. {
  66. return JsErrorInProfileCallback;
  67. }
  68. else if (threadContext->IsInThreadServiceCallback())
  69. {
  70. return JsErrorInThreadServiceCallback;
  71. }
  72. // Make sure we don't have an outstanding exception.
  73. if (scriptContext->GetThreadContext()->GetRecordedException() != nullptr)
  74. {
  75. return JsErrorInExceptionState;
  76. }
  77. }
  78. return JsNoError;
  79. }
  80. /////////////////////
  81. #if ENABLE_TTD
  82. void CALLBACK OnScriptLoad_TTDCallback(FinalizableObject* jsrtCtx, Js::FunctionBody* body, Js::Utf8SourceInfo* utf8SourceInfo, CompileScriptException* compileException, bool notify)
  83. {
  84. ((JsrtContext*)jsrtCtx)->OnScriptLoad_TTDCallback(body, utf8SourceInfo, compileException, notify);
  85. }
  86. uint32 CALLBACK OnBPRegister_TTDCallback(void* runtimeRcvr, int64 bpID, Js::ScriptContext* scriptContext, Js::Utf8SourceInfo* utf8SourceInfo, uint32 line, uint32 column, BOOL* isNewBP)
  87. {
  88. return ((JsrtRuntime*)runtimeRcvr)->BPRegister_TTD(bpID, scriptContext, utf8SourceInfo, line, column, isNewBP);
  89. }
  90. void CALLBACK OnBPDelete_TTDCallback(void* runtimeRcvr, uint32 bpID)
  91. {
  92. ((JsrtRuntime*)runtimeRcvr)->BPDelete_TTD(bpID);
  93. }
  94. void CALLBACK OnBPClearDocument_TTDCallback(void* runtimeRcvr)
  95. {
  96. ((JsrtRuntime*)runtimeRcvr)->BPClearDocument_TTD();
  97. }
  98. #endif
  99. //A create context function that we can funnel to for regular and record or debug aware creation
  100. JsErrorCode CreateContextCore(_In_ JsRuntimeHandle runtimeHandle, _In_ TTDRecorder& _actionEntryPopper, _In_ bool inRecordMode, _In_ bool activelyRecording, _In_ bool inReplayMode, _Out_ JsContextRef *newContext)
  101. {
  102. JsrtRuntime * runtime = JsrtRuntime::FromHandle(runtimeHandle);
  103. ThreadContext * threadContext = runtime->GetThreadContext();
  104. if(threadContext->GetRecycler() && threadContext->GetRecycler()->IsHeapEnumInProgress())
  105. {
  106. return JsErrorHeapEnumInProgress;
  107. }
  108. else if(threadContext->IsInThreadServiceCallback())
  109. {
  110. return JsErrorInThreadServiceCallback;
  111. }
  112. ThreadContextScope scope(threadContext);
  113. if(!scope.IsValid())
  114. {
  115. return JsErrorWrongThread;
  116. }
  117. #if ENABLE_TTD
  118. TTD::NSLogEvents::EventLogEntry* createEvent = nullptr;
  119. if(activelyRecording)
  120. {
  121. createEvent = threadContext->TTDLog->RecordJsRTCreateScriptContext(_actionEntryPopper);
  122. }
  123. #endif
  124. JsrtContext * context = JsrtContext::New(runtime);
  125. #if ENABLE_TTD
  126. if(inRecordMode | inReplayMode)
  127. {
  128. Js::ScriptContext* scriptContext = context->GetScriptContext();
  129. HostScriptContextCallbackFunctor callbackFunctor((FinalizableObject*)context, (void*)runtime, &OnScriptLoad_TTDCallback, &OnBPRegister_TTDCallback, &OnBPDelete_TTDCallback, &OnBPClearDocument_TTDCallback);
  130. #if ENABLE_TTD_DIAGNOSTICS_TRACING
  131. bool noNative = true;
  132. bool doDebug = true;
  133. #else
  134. bool noNative = TTD_FORCE_NOJIT_MODE || threadContext->TTDLog->IsDebugModeFlagSet();
  135. bool doDebug = TTD_FORCE_DEBUG_MODE || threadContext->TTDLog->IsDebugModeFlagSet();
  136. #endif
  137. threadContext->TTDLog->PushMode(TTD::TTDMode::ExcludedExecutionTTAction);
  138. if(inRecordMode)
  139. {
  140. threadContext->TTDContext->AddNewScriptContextRecord(context, scriptContext, callbackFunctor, noNative, doDebug);
  141. }
  142. else
  143. {
  144. threadContext->TTDContext->AddNewScriptContextReplay(context, scriptContext, callbackFunctor, noNative, doDebug);
  145. }
  146. threadContext->TTDLog->SetModeFlagsOnContext(scriptContext);
  147. threadContext->TTDLog->PopMode(TTD::TTDMode::ExcludedExecutionTTAction);
  148. }
  149. #endif
  150. #ifdef ENABLE_SCRIPT_DEBUGGING
  151. JsrtDebugManager* jsrtDebugManager = runtime->GetJsrtDebugManager();
  152. if(jsrtDebugManager != nullptr)
  153. {
  154. // JsDiagStartDebugging was called
  155. threadContext->GetDebugManager()->SetLocalsDisplayFlags(Js::DebugManager::LocalsDisplayFlags::LocalsDisplayFlags_NoGroupMethods);
  156. Js::ScriptContext* scriptContext = context->GetScriptContext();
  157. Js::DebugContext* debugContext = scriptContext->GetDebugContext();
  158. debugContext->SetHostDebugContext(jsrtDebugManager);
  159. if (!jsrtDebugManager->IsDebugEventCallbackSet())
  160. {
  161. // JsDiagStopDebugging was called so we need to be in SourceRunDownMode
  162. debugContext->SetDebuggerMode(Js::DebuggerMode::SourceRundown);
  163. }
  164. else
  165. {
  166. // Set Debugging mode
  167. scriptContext->InitializeDebugging();
  168. Js::ProbeContainer* probeContainer = debugContext->GetProbeContainer();
  169. probeContainer->InitializeInlineBreakEngine(jsrtDebugManager);
  170. probeContainer->InitializeDebuggerScriptOptionCallback(jsrtDebugManager);
  171. }
  172. }
  173. #endif
  174. #if ENABLE_TTD
  175. if(activelyRecording)
  176. {
  177. threadContext->TTDLog->RecordJsRTCreateScriptContextResult(createEvent, context->GetScriptContext());
  178. }
  179. #endif
  180. *newContext = (JsContextRef)context;
  181. return JsNoError;
  182. }
  183. #if ENABLE_TTD
  184. void CALLBACK CreateExternalObject_TTDCallback(Js::ScriptContext* ctx, Js::Var prototype, Js::Var* object)
  185. {
  186. TTDAssert(object != nullptr, "This should always be a valid location");
  187. Js::RecyclableObject * prototypeObject = nullptr;
  188. if (prototype != JS_INVALID_REFERENCE)
  189. {
  190. prototypeObject = Js::RecyclableObject::FromVar(prototype);
  191. }
  192. *object = JsrtExternalObject::Create(nullptr, nullptr, prototypeObject, ctx);
  193. }
  194. void CALLBACK TTDDummyPromiseContinuationCallback(JsValueRef task, void *callbackState)
  195. {
  196. TTDAssert(false, "This should never actually be invoked!!!");
  197. }
  198. void CALLBACK CreateJsRTContext_TTDCallback(void* runtimeHandle, Js::ScriptContext** result)
  199. {
  200. JsContextRef newContext = nullptr;
  201. *result = nullptr;
  202. TTDRecorder dummyActionEntryPopper;
  203. JsErrorCode err = CreateContextCore(static_cast<JsRuntimeHandle>(runtimeHandle), dummyActionEntryPopper, false /*inRecordMode*/, false /*activelyRecording*/, true /*inReplayMode*/, &newContext);
  204. TTDAssert(err == JsNoError, "Shouldn't fail on us!!!");
  205. *result = static_cast<JsrtContext*>(newContext)->GetScriptContext();
  206. (*result)->GetLibrary()->SetNativeHostPromiseContinuationFunction((Js::JavascriptLibrary::PromiseContinuationCallback)TTDDummyPromiseContinuationCallback, nullptr);
  207. //To ensure we have a valid context active (when we next try and inflate into this context) set this as active by convention
  208. JsrtContext::TrySetCurrent(static_cast<JsrtContext*>(newContext));
  209. }
  210. void CALLBACK ReleaseJsRTContext_TTDCallback(FinalizableObject* jsrtCtx)
  211. {
  212. static_cast<JsrtContext*>(jsrtCtx)->GetScriptContext()->GetThreadContext()->GetRecycler()->RootRelease(jsrtCtx);
  213. JsrtContext::OnReplayDisposeContext_TTDCallback(jsrtCtx);
  214. }
  215. void CALLBACK SetActiveJsRTContext_TTDCallback(void* runtimeHandle, Js::ScriptContext* ctx)
  216. {
  217. JsrtRuntime * runtime = JsrtRuntime::FromHandle(static_cast<JsRuntimeHandle>(runtimeHandle));
  218. ThreadContext * threadContext = runtime->GetThreadContext();
  219. threadContext->TTDContext->SetActiveScriptContext(ctx);
  220. JsrtContext* runtimeCtx = (JsrtContext*)threadContext->TTDContext->GetRuntimeContextForScriptContext(ctx);
  221. JsrtContext::TrySetCurrent(runtimeCtx);
  222. }
  223. #endif
  224. //A create runtime function that we can funnel to for regular and record or debug aware creation
  225. JsErrorCode CreateRuntimeCore(_In_ JsRuntimeAttributes attributes,
  226. _In_opt_ const char* optTTUri, size_t optTTUriCount, bool isRecord, bool isReplay, bool isDebug,
  227. _In_ UINT32 snapInterval, _In_ UINT32 snapHistoryLength,
  228. _In_opt_ TTDOpenResourceStreamCallback openResourceStream, _In_opt_ JsTTDReadBytesFromStreamCallback readBytesFromStream,
  229. _In_opt_ JsTTDWriteBytesToStreamCallback writeBytesToStream, _In_opt_ JsTTDFlushAndCloseStreamCallback flushAndCloseStream,
  230. _In_opt_ JsThreadServiceCallback threadService, _Out_ JsRuntimeHandle *runtimeHandle)
  231. {
  232. VALIDATE_ENTER_CURRENT_THREAD();
  233. PARAM_NOT_NULL(runtimeHandle);
  234. *runtimeHandle = nullptr;
  235. JsErrorCode runtimeResult = GlobalAPIWrapper_NoRecord([&]() -> JsErrorCode {
  236. const JsRuntimeAttributes JsRuntimeAttributesAll =
  237. (JsRuntimeAttributes)(
  238. JsRuntimeAttributeDisableBackgroundWork |
  239. JsRuntimeAttributeAllowScriptInterrupt |
  240. JsRuntimeAttributeEnableIdleProcessing |
  241. JsRuntimeAttributeDisableEval |
  242. JsRuntimeAttributeDisableNativeCodeGeneration |
  243. JsRuntimeAttributeEnableExperimentalFeatures |
  244. JsRuntimeAttributeDispatchSetExceptionsToDebugger |
  245. JsRuntimeAttributeDisableFatalOnOOM
  246. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  247. | JsRuntimeAttributeSerializeLibraryByteCode
  248. #endif
  249. );
  250. Assert((attributes & ~JsRuntimeAttributesAll) == 0);
  251. if ((attributes & ~JsRuntimeAttributesAll) != 0)
  252. {
  253. return JsErrorInvalidArgument;
  254. }
  255. CreateFileMapping(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, 0, nullptr);
  256. AllocationPolicyManager * policyManager = HeapNew(AllocationPolicyManager, (attributes & JsRuntimeAttributeDisableBackgroundWork) == 0);
  257. bool enableExperimentalFeatures = (attributes & JsRuntimeAttributeEnableExperimentalFeatures) != 0;
  258. ThreadContext * threadContext = HeapNew(ThreadContext, policyManager, threadService, enableExperimentalFeatures);
  259. if (((attributes & JsRuntimeAttributeDisableBackgroundWork) != 0)
  260. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  261. && !Js::Configuration::Global.flags.ConcurrentRuntime
  262. #endif
  263. )
  264. {
  265. threadContext->OptimizeForManyInstances(true);
  266. #if ENABLE_NATIVE_CODEGEN
  267. threadContext->EnableBgJit(false);
  268. #endif
  269. }
  270. if (!threadContext->IsRentalThreadingEnabledInJSRT()
  271. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  272. || Js::Configuration::Global.flags.DisableRentalThreading
  273. #endif
  274. )
  275. {
  276. threadContext->SetIsThreadBound();
  277. }
  278. if (attributes & JsRuntimeAttributeAllowScriptInterrupt)
  279. {
  280. threadContext->SetThreadContextFlag(ThreadContextFlagCanDisableExecution);
  281. }
  282. if (attributes & JsRuntimeAttributeDisableEval)
  283. {
  284. threadContext->SetThreadContextFlag(ThreadContextFlagEvalDisabled);
  285. }
  286. if (attributes & JsRuntimeAttributeDisableNativeCodeGeneration)
  287. {
  288. threadContext->SetThreadContextFlag(ThreadContextFlagNoJIT);
  289. }
  290. if (attributes & JsRuntimeAttributeDisableFatalOnOOM)
  291. {
  292. threadContext->SetThreadContextFlag(ThreadContextFlagDisableFatalOnOOM);
  293. }
  294. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  295. if (Js::Configuration::Global.flags.PrimeRecycler)
  296. {
  297. threadContext->EnsureRecycler()->Prime();
  298. }
  299. #endif
  300. bool enableIdle = (attributes & JsRuntimeAttributeEnableIdleProcessing) == JsRuntimeAttributeEnableIdleProcessing;
  301. bool dispatchExceptions = (attributes & JsRuntimeAttributeDispatchSetExceptionsToDebugger) == JsRuntimeAttributeDispatchSetExceptionsToDebugger;
  302. JsrtRuntime * runtime = HeapNew(JsrtRuntime, threadContext, enableIdle, dispatchExceptions);
  303. threadContext->SetCurrentThreadId(ThreadContext::NoThread);
  304. *runtimeHandle = runtime->ToHandle();
  305. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  306. runtime->SetSerializeByteCodeForLibrary((attributes & JsRuntimeAttributeSerializeLibraryByteCode) != 0);
  307. #endif
  308. return JsNoError;
  309. });
  310. #if ENABLE_TTD
  311. if(runtimeResult != JsNoError)
  312. {
  313. return runtimeResult;
  314. }
  315. if(isRecord | isReplay | isDebug)
  316. {
  317. ThreadContext* threadContext = JsrtRuntime::FromHandle(*runtimeHandle)->GetThreadContext();
  318. if(isRecord && isReplay)
  319. {
  320. return JsErrorInvalidArgument; //A runtime can only be in 1 mode
  321. }
  322. if(isReplay && optTTUri == nullptr)
  323. {
  324. return JsErrorInvalidArgument; //We must have a location to store data into
  325. }
  326. runtimeResult = GlobalAPIWrapper_NoRecord([&]() -> JsErrorCode {
  327. //Make sure the thread context recycler is allocated before we do anything else
  328. ThreadContextScope scope(threadContext);
  329. threadContext->EnsureRecycler();
  330. threadContext->InitTimeTravel(threadContext, *runtimeHandle, snapInterval, max<uint32>(2, snapHistoryLength));
  331. threadContext->InitHostFunctionsAndTTData(isRecord, isReplay, isDebug, optTTUriCount, optTTUri,
  332. openResourceStream, readBytesFromStream, writeBytesToStream, flushAndCloseStream,
  333. &CreateExternalObject_TTDCallback, &CreateJsRTContext_TTDCallback, &ReleaseJsRTContext_TTDCallback, &SetActiveJsRTContext_TTDCallback);
  334. return JsNoError;
  335. });
  336. }
  337. #endif
  338. return runtimeResult;
  339. }
  340. /////////////////////
  341. CHAKRA_API JsCreateRuntime(_In_ JsRuntimeAttributes attributes, _In_opt_ JsThreadServiceCallback threadService, _Out_ JsRuntimeHandle *runtimeHandle)
  342. {
  343. return CreateRuntimeCore(attributes,
  344. nullptr /*optRecordUri*/, 0 /*optRecordUriCount */, false /*isRecord*/, false /*isReplay*/, false /*isDebug*/,
  345. UINT_MAX /*optSnapInterval*/, UINT_MAX /*optLogLength*/,
  346. nullptr, nullptr, nullptr, nullptr, /*TTD IO handlers*/
  347. threadService, runtimeHandle);
  348. }
  349. template <CollectionFlags flags>
  350. JsErrorCode JsCollectGarbageCommon(JsRuntimeHandle runtimeHandle)
  351. {
  352. return GlobalAPIWrapper_NoRecord([&]() -> JsErrorCode {
  353. VALIDATE_INCOMING_RUNTIME_HANDLE(runtimeHandle);
  354. ThreadContext * threadContext = JsrtRuntime::FromHandle(runtimeHandle)->GetThreadContext();
  355. if (threadContext->GetRecycler() && threadContext->GetRecycler()->IsHeapEnumInProgress())
  356. {
  357. return JsErrorHeapEnumInProgress;
  358. }
  359. else if (threadContext->IsInThreadServiceCallback())
  360. {
  361. return JsErrorInThreadServiceCallback;
  362. }
  363. ThreadContextScope scope(threadContext);
  364. if (!scope.IsValid())
  365. {
  366. return JsErrorWrongThread;
  367. }
  368. Recycler* recycler = threadContext->EnsureRecycler();
  369. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  370. if (flags & CollectOverride_SkipStack)
  371. {
  372. Recycler::AutoEnterExternalStackSkippingGCMode autoGC(recycler);
  373. recycler->CollectNow<flags>();
  374. }
  375. else
  376. #endif
  377. {
  378. recycler->CollectNow<flags>();
  379. }
  380. return JsNoError;
  381. });
  382. }
  383. CHAKRA_API JsCollectGarbage(_In_ JsRuntimeHandle runtimeHandle)
  384. {
  385. return JsCollectGarbageCommon<CollectNowExhaustive>(runtimeHandle);
  386. }
  387. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  388. CHAKRA_API JsPrivateCollectGarbageSkipStack(_In_ JsRuntimeHandle runtimeHandle)
  389. {
  390. return JsCollectGarbageCommon<CollectNowExhaustiveSkipStack>(runtimeHandle);
  391. }
  392. #endif
  393. CHAKRA_API JsDisposeRuntime(_In_ JsRuntimeHandle runtimeHandle)
  394. {
  395. return GlobalAPIWrapper_NoRecord([&] () -> JsErrorCode {
  396. VALIDATE_INCOMING_RUNTIME_HANDLE(runtimeHandle);
  397. JsrtRuntime * runtime = JsrtRuntime::FromHandle(runtimeHandle);
  398. ThreadContext * threadContext = runtime->GetThreadContext();
  399. ThreadContextScope scope(threadContext);
  400. // We should not dispose if the runtime is being used.
  401. if (!scope.IsValid() ||
  402. scope.WasInUse() ||
  403. (threadContext->GetRecycler() && threadContext->GetRecycler()->IsHeapEnumInProgress()))
  404. {
  405. return JsErrorRuntimeInUse;
  406. }
  407. else if (threadContext->IsInThreadServiceCallback())
  408. {
  409. return JsErrorInThreadServiceCallback;
  410. }
  411. // Invoke and clear the callbacks while the contexts and runtime are still available
  412. {
  413. Recycler* recycler = threadContext->GetRecycler();
  414. if (recycler != nullptr)
  415. {
  416. recycler->ClearObjectBeforeCollectCallbacks();
  417. }
  418. }
  419. #ifdef ENABLE_SCRIPT_DEBUGGING
  420. if (runtime->GetJsrtDebugManager() != nullptr)
  421. {
  422. runtime->GetJsrtDebugManager()->ClearDebuggerObjects();
  423. }
  424. #endif
  425. Js::ScriptContext *scriptContext;
  426. for (scriptContext = threadContext->GetScriptContextList(); scriptContext; scriptContext = scriptContext->next)
  427. {
  428. #ifdef ENABLE_SCRIPT_DEBUGGING
  429. if (runtime->GetJsrtDebugManager() != nullptr)
  430. {
  431. runtime->GetJsrtDebugManager()->ClearDebugDocument(scriptContext);
  432. }
  433. #endif
  434. scriptContext->MarkForClose();
  435. }
  436. // Close any open Contexts.
  437. // We need to do this before recycler shutdown, because ScriptEngine->Close won't work then.
  438. runtime->CloseContexts();
  439. #ifdef ENABLE_SCRIPT_DEBUGGING
  440. runtime->DeleteJsrtDebugManager();
  441. #endif
  442. #if defined(CHECK_MEMORY_LEAK) || defined(LEAK_REPORT)
  443. bool doFinalGC = false;
  444. #if defined(LEAK_REPORT)
  445. if (Js::Configuration::Global.flags.IsEnabled(Js::LeakReportFlag))
  446. {
  447. doFinalGC = true;
  448. }
  449. #endif
  450. #if defined(CHECK_MEMORY_LEAK)
  451. if (Js::Configuration::Global.flags.CheckMemoryLeak)
  452. {
  453. doFinalGC = true;
  454. }
  455. #endif
  456. if (doFinalGC)
  457. {
  458. Recycler *recycler = threadContext->GetRecycler();
  459. if (recycler)
  460. {
  461. recycler->EnsureNotCollecting();
  462. recycler->CollectNow<CollectNowFinalGC>();
  463. Assert(!recycler->CollectionInProgress());
  464. }
  465. }
  466. #endif
  467. runtime->SetBeforeCollectCallback(nullptr, nullptr);
  468. threadContext->CloseForJSRT();
  469. HeapDelete(threadContext);
  470. HeapDelete(runtime);
  471. scope.Invalidate();
  472. return JsNoError;
  473. });
  474. }
  475. CHAKRA_API JsAddRef(_In_ JsRef ref, _Out_opt_ unsigned int *count)
  476. {
  477. VALIDATE_JSREF(ref);
  478. if (count != nullptr)
  479. {
  480. *count = 0;
  481. }
  482. if (Js::TaggedNumber::Is(ref))
  483. {
  484. // The count is always one because these are never collected
  485. if (count)
  486. {
  487. *count = 1;
  488. }
  489. return JsNoError;
  490. }
  491. if (JsrtContext::Is(ref))
  492. {
  493. return GlobalAPIWrapper_NoRecord([&] () -> JsErrorCode
  494. {
  495. Recycler * recycler = static_cast<JsrtContext *>(ref)->GetRuntime()->GetThreadContext()->GetRecycler();
  496. recycler->RootAddRef(ref, count);
  497. return JsNoError;
  498. });
  499. }
  500. else
  501. {
  502. ThreadContext* threadContext = ThreadContext::GetContextForCurrentThread();
  503. if (threadContext == nullptr)
  504. {
  505. return JsErrorNoCurrentContext;
  506. }
  507. Recycler * recycler = threadContext->GetRecycler();
  508. return GlobalAPIWrapper([&] (TTDRecorder& _actionEntryPopper) -> JsErrorCode
  509. {
  510. // Note, some references may live in arena-allocated memory, so we need to do this check
  511. if (!recycler->IsValidObject(ref))
  512. {
  513. return JsNoError;
  514. }
  515. #if ENABLE_TTD
  516. unsigned int lCount = 0;
  517. recycler->RootAddRef(ref, &lCount);
  518. if (count != nullptr)
  519. {
  520. *count = lCount;
  521. }
  522. if((lCount == 1) && (threadContext->IsRuntimeInTTDMode()) && (!threadContext->TTDLog->IsPropertyRecordRef(ref)))
  523. {
  524. Js::RecyclableObject* obj = Js::RecyclableObject::FromVar(ref);
  525. if(obj->GetScriptContext()->IsTTDRecordModeEnabled())
  526. {
  527. if(obj->GetScriptContext()->ShouldPerformRecordAction())
  528. {
  529. threadContext->TTDLog->RecordJsRTAddRootRef(_actionEntryPopper, (Js::Var)ref);
  530. }
  531. threadContext->TTDContext->AddRootRef_Record(TTD_CONVERT_OBJ_TO_LOG_PTR_ID(obj), obj);
  532. }
  533. }
  534. #else
  535. recycler->RootAddRef(ref, count);
  536. #endif
  537. return JsNoError;
  538. });
  539. }
  540. }
  541. CHAKRA_API JsRelease(_In_ JsRef ref, _Out_opt_ unsigned int *count)
  542. {
  543. VALIDATE_JSREF(ref);
  544. if (count != nullptr)
  545. {
  546. *count = 0;
  547. }
  548. if (Js::TaggedNumber::Is(ref))
  549. {
  550. // The count is always one because these are never collected
  551. if (count)
  552. {
  553. *count = 1;
  554. }
  555. return JsNoError;
  556. }
  557. if (JsrtContext::Is(ref))
  558. {
  559. return GlobalAPIWrapper_NoRecord([&] () -> JsErrorCode
  560. {
  561. Recycler * recycler = static_cast<JsrtContext *>(ref)->GetRuntime()->GetThreadContext()->GetRecycler();
  562. recycler->RootRelease(ref, count);
  563. return JsNoError;
  564. });
  565. }
  566. else
  567. {
  568. ThreadContext* threadContext = ThreadContext::GetContextForCurrentThread();
  569. if (threadContext == nullptr)
  570. {
  571. return JsErrorNoCurrentContext;
  572. }
  573. Recycler * recycler = threadContext->GetRecycler();
  574. return GlobalAPIWrapper([&](TTDRecorder& _actionEntryPopper) -> JsErrorCode
  575. {
  576. // Note, some references may live in arena-allocated memory, so we need to do this check
  577. if (!recycler->IsValidObject(ref))
  578. {
  579. return JsNoError;
  580. }
  581. recycler->RootRelease(ref, count);
  582. return JsNoError;
  583. });
  584. }
  585. }
  586. CHAKRA_API JsSetObjectBeforeCollectCallback(_In_ JsRef ref, _In_opt_ void *callbackState, _In_ JsObjectBeforeCollectCallback objectBeforeCollectCallback)
  587. {
  588. VALIDATE_JSREF(ref);
  589. if (Js::TaggedNumber::Is(ref))
  590. {
  591. return JsErrorInvalidArgument;
  592. }
  593. if (JsrtContext::Is(ref))
  594. {
  595. return GlobalAPIWrapper_NoRecord([&]() -> JsErrorCode
  596. {
  597. ThreadContext* threadContext = static_cast<JsrtContext *>(ref)->GetRuntime()->GetThreadContext();
  598. Recycler * recycler = threadContext->GetRecycler();
  599. recycler->SetObjectBeforeCollectCallback(ref, reinterpret_cast<Recycler::ObjectBeforeCollectCallback>(objectBeforeCollectCallback), callbackState,
  600. reinterpret_cast<Recycler::ObjectBeforeCollectCallbackWrapper>(JsrtCallbackState::ObjectBeforeCallectCallbackWrapper), threadContext);
  601. return JsNoError;
  602. });
  603. }
  604. else
  605. {
  606. ThreadContext* threadContext = ThreadContext::GetContextForCurrentThread();
  607. if (threadContext == nullptr)
  608. {
  609. return JsErrorNoCurrentContext;
  610. }
  611. Recycler * recycler = threadContext->GetRecycler();
  612. return GlobalAPIWrapper_NoRecord([&]() -> JsErrorCode
  613. {
  614. if (!recycler->IsValidObject(ref))
  615. {
  616. return JsErrorInvalidArgument;
  617. }
  618. recycler->SetObjectBeforeCollectCallback(ref, reinterpret_cast<Recycler::ObjectBeforeCollectCallback>(objectBeforeCollectCallback), callbackState,
  619. reinterpret_cast<Recycler::ObjectBeforeCollectCallbackWrapper>(JsrtCallbackState::ObjectBeforeCallectCallbackWrapper), threadContext);
  620. return JsNoError;
  621. });
  622. }
  623. }
  624. CHAKRA_API JsCreateContext(_In_ JsRuntimeHandle runtimeHandle, _Out_ JsContextRef *newContext)
  625. {
  626. return GlobalAPIWrapper([&](TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  627. PARAM_NOT_NULL(newContext);
  628. VALIDATE_INCOMING_RUNTIME_HANDLE(runtimeHandle);
  629. bool inRecord = false;
  630. bool activelyRecording = false;
  631. bool inReplay = false;
  632. #if ENABLE_TTD
  633. JsrtRuntime * runtime = JsrtRuntime::FromHandle(runtimeHandle);
  634. ThreadContext * threadContext = runtime->GetThreadContext();
  635. if(threadContext->IsRuntimeInTTDMode() && threadContext->TTDContext->GetActiveScriptContext() != nullptr)
  636. {
  637. Js::ScriptContext* currentCtx = threadContext->TTDContext->GetActiveScriptContext();
  638. inRecord = currentCtx->IsTTDRecordModeEnabled();
  639. activelyRecording = currentCtx->ShouldPerformRecordAction();
  640. inReplay = currentCtx->IsTTDReplayModeEnabled();
  641. }
  642. #endif
  643. return CreateContextCore(runtimeHandle, _actionEntryPopper, inRecord, activelyRecording, inReplay, newContext);
  644. });
  645. }
  646. CHAKRA_API JsGetCurrentContext(_Out_ JsContextRef *currentContext)
  647. {
  648. PARAM_NOT_NULL(currentContext);
  649. BEGIN_JSRT_NO_EXCEPTION
  650. {
  651. *currentContext = (JsContextRef)JsrtContext::GetCurrent();
  652. }
  653. END_JSRT_NO_EXCEPTION
  654. }
  655. CHAKRA_API JsSetCurrentContext(_In_ JsContextRef newContext)
  656. {
  657. VALIDATE_ENTER_CURRENT_THREAD();
  658. return GlobalAPIWrapper([&] (TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  659. JsrtContext *currentContext = JsrtContext::GetCurrent();
  660. Recycler* recycler = currentContext != nullptr ? currentContext->GetScriptContext()->GetRecycler() : nullptr;
  661. #if ENABLE_TTD
  662. Js::ScriptContext* newScriptContext = newContext != nullptr ? static_cast<JsrtContext*>(newContext)->GetScriptContext() : nullptr;
  663. Js::ScriptContext* oldScriptContext = currentContext != nullptr ? static_cast<JsrtContext*>(currentContext)->GetScriptContext() : nullptr;
  664. if(newScriptContext == nullptr)
  665. {
  666. if(oldScriptContext == nullptr)
  667. {
  668. ; //if newScriptContext and oldScriptContext are null then we don't worry about doing anything
  669. }
  670. else
  671. {
  672. if(oldScriptContext->IsTTDRecordModeEnabled())
  673. {
  674. //already know newScriptContext != oldScriptContext so don't check again
  675. if(oldScriptContext->ShouldPerformRecordAction())
  676. {
  677. oldScriptContext->GetThreadContext()->TTDLog->RecordJsRTSetCurrentContext(_actionEntryPopper, nullptr);
  678. }
  679. oldScriptContext->GetThreadContext()->TTDContext->SetActiveScriptContext(nullptr);
  680. }
  681. }
  682. }
  683. else
  684. {
  685. if(newScriptContext->IsTTDRecordModeEnabled())
  686. {
  687. if(newScriptContext != oldScriptContext && newScriptContext->ShouldPerformRecordAction())
  688. {
  689. newScriptContext->GetThreadContext()->TTDLog->RecordJsRTSetCurrentContext(_actionEntryPopper, newScriptContext->GetGlobalObject());
  690. }
  691. newScriptContext->GetThreadContext()->TTDContext->SetActiveScriptContext(newScriptContext);
  692. }
  693. }
  694. #endif
  695. if (currentContext && recycler->IsHeapEnumInProgress())
  696. {
  697. return JsErrorHeapEnumInProgress;
  698. }
  699. else if (currentContext && currentContext->GetRuntime()->GetThreadContext()->IsInThreadServiceCallback())
  700. {
  701. return JsErrorInThreadServiceCallback;
  702. }
  703. if (!JsrtContext::TrySetCurrent((JsrtContext *)newContext))
  704. {
  705. return JsErrorWrongThread;
  706. }
  707. return JsNoError;
  708. });
  709. }
  710. CHAKRA_API JsGetContextOfObject(_In_ JsValueRef object, _Out_ JsContextRef *context)
  711. {
  712. VALIDATE_JSREF(object);
  713. PARAM_NOT_NULL(context);
  714. BEGIN_JSRT_NO_EXCEPTION
  715. {
  716. if (!Js::RecyclableObject::Is(object))
  717. {
  718. RETURN_NO_EXCEPTION(JsErrorArgumentNotObject);
  719. }
  720. Js::RecyclableObject* obj = Js::RecyclableObject::FromVar(object);
  721. *context = (JsContextRef)obj->GetScriptContext()->GetLibrary()->GetJsrtContext();
  722. }
  723. END_JSRT_NO_EXCEPTION
  724. }
  725. CHAKRA_API JsGetContextData(_In_ JsContextRef context, _Out_ void **data)
  726. {
  727. VALIDATE_JSREF(context);
  728. PARAM_NOT_NULL(data);
  729. BEGIN_JSRT_NO_EXCEPTION
  730. {
  731. if (!JsrtContext::Is(context))
  732. {
  733. RETURN_NO_EXCEPTION(JsErrorInvalidArgument);
  734. }
  735. *data = static_cast<JsrtContext *>(context)->GetExternalData();
  736. }
  737. END_JSRT_NO_EXCEPTION
  738. }
  739. CHAKRA_API JsSetContextData(_In_ JsContextRef context, _In_ void *data)
  740. {
  741. VALIDATE_JSREF(context);
  742. BEGIN_JSRT_NO_EXCEPTION
  743. {
  744. if (!JsrtContext::Is(context))
  745. {
  746. RETURN_NO_EXCEPTION(JsErrorInvalidArgument);
  747. }
  748. static_cast<JsrtContext *>(context)->SetExternalData(data);
  749. }
  750. END_JSRT_NO_EXCEPTION
  751. }
  752. void HandleScriptCompileError(Js::ScriptContext * scriptContext, CompileScriptException * se, const WCHAR * sourceUrl)
  753. {
  754. HRESULT hr = se->ei.scode;
  755. if (hr == E_OUTOFMEMORY || hr == VBSERR_OutOfMemory || hr == VBSERR_OutOfStack || hr == ERRnoMemory)
  756. {
  757. Js::Throw::OutOfMemory();
  758. }
  759. Js::JavascriptError* error = Js::JavascriptError::CreateFromCompileScriptException(scriptContext, se, sourceUrl);
  760. Js::JavascriptExceptionObject * exceptionObject = RecyclerNew(scriptContext->GetRecycler(),
  761. Js::JavascriptExceptionObject, error, scriptContext, nullptr);
  762. scriptContext->GetThreadContext()->SetRecordedException(exceptionObject);
  763. }
  764. CHAKRA_API JsGetUndefinedValue(_Out_ JsValueRef *undefinedValue)
  765. {
  766. return ContextAPINoScriptWrapper_NoRecord([&] (Js::ScriptContext *scriptContext) -> JsErrorCode {
  767. PARAM_NOT_NULL(undefinedValue);
  768. *undefinedValue = scriptContext->GetLibrary()->GetUndefined();
  769. return JsNoError;
  770. },
  771. /*allowInObjectBeforeCollectCallback*/true);
  772. }
  773. CHAKRA_API JsGetNullValue(_Out_ JsValueRef *nullValue)
  774. {
  775. return ContextAPINoScriptWrapper_NoRecord([&] (Js::ScriptContext *scriptContext) -> JsErrorCode {
  776. PARAM_NOT_NULL(nullValue);
  777. *nullValue = scriptContext->GetLibrary()->GetNull();
  778. return JsNoError;
  779. },
  780. /*allowInObjectBeforeCollectCallback*/true);
  781. }
  782. CHAKRA_API JsGetTrueValue(_Out_ JsValueRef *trueValue)
  783. {
  784. return ContextAPINoScriptWrapper_NoRecord([&] (Js::ScriptContext *scriptContext) -> JsErrorCode {
  785. PARAM_NOT_NULL(trueValue);
  786. *trueValue = scriptContext->GetLibrary()->GetTrue();
  787. return JsNoError;
  788. },
  789. /*allowInObjectBeforeCollectCallback*/true);
  790. }
  791. CHAKRA_API JsGetFalseValue(_Out_ JsValueRef *falseValue)
  792. {
  793. return ContextAPINoScriptWrapper_NoRecord([&] (Js::ScriptContext *scriptContext) -> JsErrorCode {
  794. PARAM_NOT_NULL(falseValue);
  795. *falseValue = scriptContext->GetLibrary()->GetFalse();
  796. return JsNoError;
  797. },
  798. /*allowInObjectBeforeCollectCallback*/true);
  799. }
  800. CHAKRA_API JsBoolToBoolean(_In_ bool value, _Out_ JsValueRef *booleanValue)
  801. {
  802. return ContextAPINoScriptWrapper([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  803. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTCreateBoolean, value);
  804. PARAM_NOT_NULL(booleanValue);
  805. *booleanValue = value ? scriptContext->GetLibrary()->GetTrue() : scriptContext->GetLibrary()->GetFalse();
  806. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, booleanValue);
  807. return JsNoError;
  808. },
  809. /*allowInObjectBeforeCollectCallback*/true);
  810. }
  811. CHAKRA_API JsBooleanToBool(_In_ JsValueRef value, _Out_ bool *boolValue)
  812. {
  813. VALIDATE_JSREF(value);
  814. PARAM_NOT_NULL(boolValue);
  815. BEGIN_JSRT_NO_EXCEPTION
  816. {
  817. if (!Js::JavascriptBoolean::Is(value))
  818. {
  819. RETURN_NO_EXCEPTION(JsErrorInvalidArgument);
  820. }
  821. *boolValue = Js::JavascriptBoolean::FromVar(value)->GetValue() ? true : false;
  822. }
  823. END_JSRT_NO_EXCEPTION
  824. }
  825. CHAKRA_API JsConvertValueToBoolean(_In_ JsValueRef value, _Out_ JsValueRef *result)
  826. {
  827. return ContextAPIWrapper<JSRT_MAYBE_TRUE>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  828. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTVarToBooleanConversion, (Js::Var)value);
  829. VALIDATE_INCOMING_REFERENCE(value, scriptContext);
  830. PARAM_NOT_NULL(result);
  831. if (Js::JavascriptConversion::ToBool((Js::Var)value, scriptContext))
  832. {
  833. *result = scriptContext->GetLibrary()->GetTrue();
  834. }
  835. else
  836. {
  837. *result = scriptContext->GetLibrary()->GetFalse();
  838. }
  839. //It is either true or false which we always track so no need to store result identity
  840. return JsNoError;
  841. });
  842. }
  843. CHAKRA_API JsGetValueType(_In_ JsValueRef value, _Out_ JsValueType *type)
  844. {
  845. VALIDATE_JSREF(value);
  846. PARAM_NOT_NULL(type);
  847. BEGIN_JSRT_NO_EXCEPTION
  848. {
  849. Js::TypeId typeId = Js::JavascriptOperators::GetTypeId(value);
  850. switch (typeId)
  851. {
  852. case Js::TypeIds_Undefined:
  853. *type = JsUndefined;
  854. break;
  855. case Js::TypeIds_Null:
  856. *type = JsNull;
  857. break;
  858. case Js::TypeIds_Boolean:
  859. *type = JsBoolean;
  860. break;
  861. case Js::TypeIds_Integer:
  862. case Js::TypeIds_Number:
  863. case Js::TypeIds_Int64Number:
  864. case Js::TypeIds_UInt64Number:
  865. *type = JsNumber;
  866. break;
  867. case Js::TypeIds_String:
  868. *type = JsString;
  869. break;
  870. case Js::TypeIds_Function:
  871. *type = JsFunction;
  872. break;
  873. case Js::TypeIds_Error:
  874. *type = JsError;
  875. break;
  876. case Js::TypeIds_Array:
  877. case Js::TypeIds_NativeIntArray:
  878. #if ENABLE_COPYONACCESS_ARRAY
  879. case Js::TypeIds_CopyOnAccessNativeIntArray:
  880. #endif
  881. case Js::TypeIds_NativeFloatArray:
  882. case Js::TypeIds_ES5Array:
  883. *type = JsArray;
  884. break;
  885. case Js::TypeIds_Symbol:
  886. *type = JsSymbol;
  887. break;
  888. case Js::TypeIds_ArrayBuffer:
  889. *type = JsArrayBuffer;
  890. break;
  891. case Js::TypeIds_DataView:
  892. *type = JsDataView;
  893. break;
  894. default:
  895. if (Js::TypedArrayBase::Is(typeId))
  896. {
  897. *type = JsTypedArray;
  898. }
  899. else
  900. {
  901. *type = JsObject;
  902. }
  903. break;
  904. }
  905. }
  906. END_JSRT_NO_EXCEPTION
  907. }
  908. CHAKRA_API JsDoubleToNumber(_In_ double dbl, _Out_ JsValueRef *asValue)
  909. {
  910. PARAM_NOT_NULL(asValue);
  911. //If number is not heap allocated then we don't need to record/track the creation for time-travel
  912. if (Js::JavascriptNumber::TryToVarFastWithCheck(dbl, asValue))
  913. {
  914. return JsNoError;
  915. }
  916. return ContextAPINoScriptWrapper([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  917. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTCreateNumber, dbl);
  918. *asValue = Js::JavascriptNumber::ToVarNoCheck(dbl, scriptContext);
  919. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, asValue);
  920. return JsNoError;
  921. });
  922. }
  923. CHAKRA_API JsIntToNumber(_In_ int intValue, _Out_ JsValueRef *asValue)
  924. {
  925. PARAM_NOT_NULL(asValue);
  926. //If number is not heap allocated then we don't need to record/track the creation for time-travel
  927. if (Js::JavascriptNumber::TryToVarFast(intValue, asValue))
  928. {
  929. return JsNoError;
  930. }
  931. return ContextAPINoScriptWrapper([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  932. #if !INT32VAR
  933. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTCreateInteger, intValue);
  934. #endif
  935. *asValue = Js::JavascriptNumber::ToVar(intValue, scriptContext);
  936. #if !INT32VAR
  937. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, asValue);
  938. #endif
  939. return JsNoError;
  940. });
  941. }
  942. CHAKRA_API JsNumberToDouble(_In_ JsValueRef value, _Out_ double *asDouble)
  943. {
  944. VALIDATE_JSREF(value);
  945. PARAM_NOT_NULL(asDouble);
  946. BEGIN_JSRT_NO_EXCEPTION
  947. {
  948. if (Js::TaggedInt::Is(value))
  949. {
  950. *asDouble = Js::TaggedInt::ToDouble(value);
  951. }
  952. else if (Js::JavascriptNumber::Is_NoTaggedIntCheck(value))
  953. {
  954. *asDouble = Js::JavascriptNumber::GetValue(value);
  955. }
  956. else
  957. {
  958. *asDouble = 0;
  959. RETURN_NO_EXCEPTION(JsErrorInvalidArgument);
  960. }
  961. }
  962. END_JSRT_NO_EXCEPTION
  963. }
  964. CHAKRA_API JsNumberToInt(_In_ JsValueRef value, _Out_ int *asInt)
  965. {
  966. VALIDATE_JSREF(value);
  967. PARAM_NOT_NULL(asInt);
  968. BEGIN_JSRT_NO_EXCEPTION
  969. {
  970. if (Js::TaggedInt::Is(value))
  971. {
  972. *asInt = Js::TaggedInt::ToInt32(value);
  973. }
  974. else if (Js::JavascriptNumber::Is_NoTaggedIntCheck(value))
  975. {
  976. *asInt = Js::JavascriptConversion::ToInt32(Js::JavascriptNumber::GetValue(value));
  977. }
  978. else
  979. {
  980. *asInt = 0;
  981. RETURN_NO_EXCEPTION(JsErrorInvalidArgument);
  982. }
  983. }
  984. END_JSRT_NO_EXCEPTION
  985. }
  986. CHAKRA_API JsConvertValueToNumber(_In_ JsValueRef value, _Out_ JsValueRef *result)
  987. {
  988. return ContextAPIWrapper<JSRT_MAYBE_TRUE>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  989. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTVarToNumberConversion, (Js::Var)value);
  990. VALIDATE_INCOMING_REFERENCE(value, scriptContext);
  991. PARAM_NOT_NULL(result);
  992. *result = (JsValueRef)Js::JavascriptOperators::ToNumber((Js::Var)value, scriptContext);
  993. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, result);
  994. return JsNoError;
  995. });
  996. }
  997. CHAKRA_API JsGetStringLength(_In_ JsValueRef value, _Out_ int *length)
  998. {
  999. VALIDATE_JSREF(value);
  1000. PARAM_NOT_NULL(length);
  1001. BEGIN_JSRT_NO_EXCEPTION
  1002. {
  1003. if (!Js::JavascriptString::Is(value))
  1004. {
  1005. RETURN_NO_EXCEPTION(JsErrorInvalidArgument);
  1006. }
  1007. *length = Js::JavascriptString::FromVar(value)->GetLengthAsSignedInt();
  1008. }
  1009. END_JSRT_NO_EXCEPTION
  1010. }
  1011. CHAKRA_API JsPointerToString(_In_reads_(stringLength) const WCHAR *stringValue, _In_ size_t stringLength, _Out_ JsValueRef *string)
  1012. {
  1013. return ContextAPINoScriptWrapper([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1014. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTCreateString, stringValue, stringLength);
  1015. PARAM_NOT_NULL(stringValue);
  1016. PARAM_NOT_NULL(string);
  1017. if (!Js::IsValidCharCount(stringLength))
  1018. {
  1019. Js::JavascriptError::ThrowOutOfMemoryError(scriptContext);
  1020. }
  1021. *string = Js::JavascriptString::NewCopyBuffer(stringValue, static_cast<charcount_t>(stringLength), scriptContext);
  1022. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, string);
  1023. return JsNoError;
  1024. });
  1025. }
  1026. // TODO: The annotation of stringPtr is wrong. Need to fix definition in chakrart.h
  1027. // The warning is '*stringPtr' could be '0' : this does not adhere to the specification for the function 'JsStringToPointer'.
  1028. #pragma warning(suppress:6387)
  1029. CHAKRA_API JsStringToPointer(_In_ JsValueRef stringValue, _Outptr_result_buffer_(*stringLength) const WCHAR **stringPtr, _Out_ size_t *stringLength)
  1030. {
  1031. VALIDATE_JSREF(stringValue);
  1032. PARAM_NOT_NULL(stringPtr);
  1033. *stringPtr = nullptr;
  1034. PARAM_NOT_NULL(stringLength);
  1035. *stringLength = 0;
  1036. if (!Js::JavascriptString::Is(stringValue))
  1037. {
  1038. return JsErrorInvalidArgument;
  1039. }
  1040. return GlobalAPIWrapper_NoRecord([&]() -> JsErrorCode {
  1041. Js::JavascriptString *jsString = Js::JavascriptString::FromVar(stringValue);
  1042. *stringPtr = jsString->GetSz();
  1043. *stringLength = jsString->GetLength();
  1044. return JsNoError;
  1045. });
  1046. }
  1047. CHAKRA_API JsConvertValueToString(_In_ JsValueRef value, _Out_ JsValueRef *result)
  1048. {
  1049. PARAM_NOT_NULL(result);
  1050. *result = nullptr;
  1051. if (value != nullptr && Js::JavascriptString::Is(value))
  1052. {
  1053. return ContextAPINoScriptWrapper([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1054. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTVarToStringConversion, (Js::Var)value);
  1055. VALIDATE_INCOMING_REFERENCE(value, scriptContext);
  1056. *result = value;
  1057. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, result);
  1058. return JsNoError;
  1059. });
  1060. }
  1061. return ContextAPIWrapper<JSRT_MAYBE_TRUE>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1062. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTVarToStringConversion, (Js::Var)value);
  1063. VALIDATE_INCOMING_REFERENCE(value, scriptContext);
  1064. *result = (JsValueRef) Js::JavascriptConversion::ToString((Js::Var)value, scriptContext);
  1065. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, result);
  1066. return JsNoError;
  1067. });
  1068. }
  1069. CHAKRA_API JsGetGlobalObject(_Out_ JsValueRef *globalObject)
  1070. {
  1071. return ContextAPINoScriptWrapper_NoRecord([&](Js::ScriptContext *scriptContext) -> JsErrorCode {
  1072. PARAM_NOT_NULL(globalObject);
  1073. *globalObject = (JsValueRef)scriptContext->GetGlobalObject();
  1074. return JsNoError;
  1075. },
  1076. /*allowInObjectBeforeCollectCallback*/true);
  1077. }
  1078. CHAKRA_API JsCreateObject(_Out_ JsValueRef *object)
  1079. {
  1080. return ContextAPINoScriptWrapper([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1081. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTAllocateBasicObject);
  1082. PARAM_NOT_NULL(object);
  1083. *object = scriptContext->GetLibrary()->CreateObject();
  1084. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, object);
  1085. return JsNoError;
  1086. });
  1087. }
  1088. CHAKRA_API JsCreateExternalObjectWithPrototype(_In_opt_ void *data,
  1089. _In_opt_ JsFinalizeCallback finalizeCallback,
  1090. _In_opt_ JsValueRef prototype,
  1091. _Out_ JsValueRef *object)
  1092. {
  1093. return ContextAPINoScriptWrapper([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1094. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTAllocateExternalObject, prototype);
  1095. PARAM_NOT_NULL(object);
  1096. Js::RecyclableObject * prototypeObject = nullptr;
  1097. if (prototype != JS_INVALID_REFERENCE)
  1098. {
  1099. VALIDATE_INCOMING_OBJECT(prototype, scriptContext);
  1100. prototypeObject = Js::RecyclableObject::FromVar(prototype);
  1101. }
  1102. *object = JsrtExternalObject::Create(data, finalizeCallback, prototypeObject, scriptContext);
  1103. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, object);
  1104. return JsNoError;
  1105. });
  1106. }
  1107. CHAKRA_API JsCreateExternalObject(_In_opt_ void *data, _In_opt_ JsFinalizeCallback finalizeCallback, _Out_ JsValueRef *object)
  1108. {
  1109. return JsCreateExternalObjectWithPrototype(data, finalizeCallback, JS_INVALID_REFERENCE, object);
  1110. }
  1111. CHAKRA_API JsConvertValueToObject(_In_ JsValueRef value, _Out_ JsValueRef *result)
  1112. {
  1113. return ContextAPIWrapper<JSRT_MAYBE_TRUE>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1114. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTVarToObjectConversion, (Js::Var)value);
  1115. VALIDATE_INCOMING_REFERENCE(value, scriptContext);
  1116. PARAM_NOT_NULL(result);
  1117. *result = (JsValueRef)Js::JavascriptOperators::ToObject((Js::Var)value, scriptContext);
  1118. Assert(*result == nullptr || !Js::CrossSite::NeedMarshalVar(*result, scriptContext));
  1119. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, result);
  1120. return JsNoError;
  1121. });
  1122. }
  1123. CHAKRA_API JsGetPrototype(_In_ JsValueRef object, _Out_ JsValueRef *prototypeObject)
  1124. {
  1125. return ContextAPIWrapper<JSRT_MAYBE_TRUE>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1126. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTGetPrototype, object);
  1127. VALIDATE_INCOMING_OBJECT(object, scriptContext);
  1128. PARAM_NOT_NULL(prototypeObject);
  1129. *prototypeObject = (JsValueRef)Js::JavascriptOperators::OP_GetPrototype(object, scriptContext);
  1130. Assert(*prototypeObject == nullptr || !Js::CrossSite::NeedMarshalVar(*prototypeObject, scriptContext));
  1131. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, prototypeObject);
  1132. return JsNoError;
  1133. });
  1134. }
  1135. CHAKRA_API JsSetPrototype(_In_ JsValueRef object, _In_ JsValueRef prototypeObject)
  1136. {
  1137. return ContextAPIWrapper<JSRT_MAYBE_TRUE>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1138. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTSetPrototype, object, prototypeObject);
  1139. VALIDATE_INCOMING_OBJECT(object, scriptContext);
  1140. VALIDATE_INCOMING_OBJECT_OR_NULL(prototypeObject, scriptContext);
  1141. // We're not allowed to set this.
  1142. if (object == scriptContext->GetLibrary()->GetObjectPrototype())
  1143. {
  1144. return JsErrorInvalidArgument;
  1145. }
  1146. Js::JavascriptObject::ChangePrototype(Js::RecyclableObject::FromVar(object), Js::RecyclableObject::FromVar(prototypeObject), true, scriptContext);
  1147. return JsNoError;
  1148. });
  1149. }
  1150. CHAKRA_API JsInstanceOf(_In_ JsValueRef object, _In_ JsValueRef constructor, _Out_ bool *result) {
  1151. return ContextAPIWrapper<JSRT_MAYBE_TRUE>([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1152. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTInstanceOf, object, constructor);
  1153. VALIDATE_INCOMING_REFERENCE(object, scriptContext);
  1154. VALIDATE_INCOMING_REFERENCE(constructor, scriptContext);
  1155. PARAM_NOT_NULL(result);
  1156. *result = Js::RecyclableObject::FromVar(constructor)->HasInstance(object, scriptContext) ? true : false;
  1157. return JsNoError;
  1158. });
  1159. }
  1160. CHAKRA_API JsGetExtensionAllowed(_In_ JsValueRef object, _Out_ bool *value)
  1161. {
  1162. return ContextAPIWrapper<JSRT_MAYBE_TRUE>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1163. PERFORM_JSRT_TTD_RECORD_ACTION_NOT_IMPLEMENTED(scriptContext);
  1164. VALIDATE_INCOMING_OBJECT(object, scriptContext);
  1165. PARAM_NOT_NULL(value);
  1166. *value = false;
  1167. *value = Js::RecyclableObject::FromVar(object)->IsExtensible() != 0;
  1168. return JsNoError;
  1169. });
  1170. }
  1171. CHAKRA_API JsPreventExtension(_In_ JsValueRef object)
  1172. {
  1173. return ContextAPIWrapper<JSRT_MAYBE_TRUE>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1174. PERFORM_JSRT_TTD_RECORD_ACTION_NOT_IMPLEMENTED(scriptContext);
  1175. VALIDATE_INCOMING_OBJECT(object, scriptContext);
  1176. Js::RecyclableObject::FromVar(object)->PreventExtensions();
  1177. return JsNoError;
  1178. });
  1179. }
  1180. CHAKRA_API JsHasOwnPropertyCommon(Js::ScriptContext * scriptContext, _In_ JsValueRef object,
  1181. _In_ const Js::PropertyRecord * propertyRecord, _Out_ bool *hasOwnProperty)
  1182. {
  1183. *hasOwnProperty = Js::JavascriptOperators::OP_HasOwnProperty(object,
  1184. propertyRecord->GetPropertyId(), scriptContext) != 0;
  1185. return JsNoError;
  1186. }
  1187. CHAKRA_API JsHasOwnProperty(_In_ JsValueRef object, _In_ JsPropertyIdRef propertyId,
  1188. _Out_ bool *hasOwnProperty)
  1189. {
  1190. return ContextAPIWrapper<true>([&] (Js::ScriptContext *scriptContext,
  1191. TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1192. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTHasOwnProperty, (const Js::PropertyRecord *)propertyId, object);
  1193. VALIDATE_INCOMING_OBJECT(object, scriptContext);
  1194. VALIDATE_INCOMING_PROPERTYID(propertyId);
  1195. PARAM_NOT_NULL(hasOwnProperty);
  1196. *hasOwnProperty = false;
  1197. return JsHasOwnPropertyCommon(scriptContext, object,
  1198. (const Js::PropertyRecord *)propertyId, hasOwnProperty);
  1199. });
  1200. }
  1201. #ifdef _CHAKRACOREBUILD
  1202. static JsErrorCode InternalGetPropertyRecord(Js::ScriptContext * scriptContext,
  1203. Js::RecyclableObject * key, _Out_ const Js::PropertyRecord ** propertyRecord)
  1204. {
  1205. Assert(propertyRecord != nullptr);
  1206. *propertyRecord = nullptr;
  1207. switch(key->GetTypeId())
  1208. {
  1209. case Js::TypeIds_String:
  1210. scriptContext->GetOrAddPropertyRecord(Js::JavascriptString::FromVar(key),
  1211. (Js::PropertyRecord const **)propertyRecord);
  1212. break;
  1213. case Js::TypeIds_Symbol:
  1214. *propertyRecord = Js::JavascriptSymbol::FromVar(key)->GetValue();
  1215. break;
  1216. default:
  1217. return JsErrorInvalidArgument;
  1218. };
  1219. return JsNoError;
  1220. }
  1221. CHAKRA_API JsObjectHasOwnProperty(_In_ JsValueRef object, _In_ JsValueRef propertyId, _Out_ bool *hasOwnProperty)
  1222. {
  1223. return ContextAPIWrapper<true>([&] (Js::ScriptContext *scriptContext,
  1224. TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1225. PERFORM_JSRT_TTD_RECORD_ACTION_NOT_IMPLEMENTED(scriptContext);
  1226. VALIDATE_INCOMING_OBJECT(object, scriptContext);
  1227. VALIDATE_INCOMING_RECYCLABLE(propertyId, scriptContext);
  1228. PARAM_NOT_NULL(hasOwnProperty);
  1229. *hasOwnProperty = false;
  1230. const Js::PropertyRecord *propertyRecord = nullptr;
  1231. JsErrorCode errorValue = InternalGetPropertyRecord(scriptContext,
  1232. Js::RecyclableObject::FromVar(propertyId), &propertyRecord);
  1233. if (errorValue != JsNoError)
  1234. {
  1235. return errorValue;
  1236. }
  1237. return JsHasOwnPropertyCommon(scriptContext, object, propertyRecord, hasOwnProperty);
  1238. });
  1239. }
  1240. #endif
  1241. static JsErrorCode JsGetPropertyCommon(Js::ScriptContext * scriptContext,
  1242. _In_ Js::RecyclableObject * object,
  1243. _In_ const Js::PropertyRecord * propertyRecord, _Out_ JsValueRef *value)
  1244. {
  1245. AssertMsg(scriptContext->GetThreadContext()->IsScriptActive(), "Caller is expected to be under ContextAPIWrapper!");
  1246. *value = Js::JavascriptOperators::GetPropertyNoCache(object, propertyRecord->GetPropertyId(), scriptContext);
  1247. Assert(*value == nullptr || !Js::CrossSite::NeedMarshalVar(*value, scriptContext));
  1248. return JsNoError;
  1249. }
  1250. CHAKRA_API JsGetProperty(_In_ JsValueRef object, _In_ JsPropertyIdRef propertyId, _Out_ JsValueRef *value)
  1251. {
  1252. return ContextAPIWrapper<JSRT_MAYBE_TRUE>([&] (Js::ScriptContext *scriptContext,
  1253. TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1254. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTGetProperty, (const Js::PropertyRecord *)propertyId, object);
  1255. VALIDATE_INCOMING_OBJECT(object, scriptContext);
  1256. VALIDATE_INCOMING_PROPERTYID(propertyId);
  1257. PARAM_NOT_NULL(value);
  1258. *value = nullptr;
  1259. Js::RecyclableObject * instance = Js::RecyclableObject::FromVar(object);
  1260. JsErrorCode err = JsGetPropertyCommon(scriptContext, instance, (const Js::PropertyRecord *)propertyId,
  1261. value);
  1262. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, value);
  1263. return err;
  1264. });
  1265. }
  1266. #ifdef _CHAKRACOREBUILD
  1267. CHAKRA_API JsObjectGetProperty(_In_ JsValueRef object, _In_ JsValueRef propertyId, _Out_ JsValueRef *value)
  1268. {
  1269. return ContextAPIWrapper<JSRT_MAYBE_TRUE>([&] (Js::ScriptContext *scriptContext,
  1270. TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1271. PERFORM_JSRT_TTD_RECORD_ACTION_NOT_IMPLEMENTED(scriptContext);
  1272. VALIDATE_INCOMING_OBJECT(object, scriptContext);
  1273. VALIDATE_INCOMING_RECYCLABLE(propertyId, scriptContext);
  1274. PARAM_NOT_NULL(value);
  1275. *value = nullptr;
  1276. const Js::PropertyRecord *propertyRecord = nullptr;
  1277. JsErrorCode errorValue = InternalGetPropertyRecord(scriptContext,
  1278. Js::RecyclableObject::FromVar(propertyId), &propertyRecord);
  1279. if (errorValue != JsNoError)
  1280. {
  1281. return errorValue;
  1282. }
  1283. Assert(propertyRecord != nullptr);
  1284. Js::RecyclableObject * instance = Js::RecyclableObject::FromVar(object);
  1285. return JsGetPropertyCommon(scriptContext, instance, propertyRecord, value);
  1286. });
  1287. }
  1288. #endif
  1289. static JsErrorCode JsGetOwnPropertyDescriptorCommon(Js::ScriptContext * scriptContext,
  1290. _In_ JsValueRef object, _In_ const Js::PropertyRecord * propertyRecord, _Out_ JsValueRef *propertyDescriptor)
  1291. {
  1292. AssertMsg(scriptContext->GetThreadContext()->IsScriptActive(), "Caller is expected to be under ContextAPIWrapper!");
  1293. Js::PropertyDescriptor propertyDescriptorValue;
  1294. if (Js::JavascriptOperators::GetOwnPropertyDescriptor(Js::RecyclableObject::FromVar(object),
  1295. propertyRecord->GetPropertyId(), scriptContext, &propertyDescriptorValue))
  1296. {
  1297. *propertyDescriptor = Js::JavascriptOperators::FromPropertyDescriptor(propertyDescriptorValue, scriptContext);
  1298. }
  1299. else
  1300. {
  1301. *propertyDescriptor = scriptContext->GetLibrary()->GetUndefined();
  1302. }
  1303. Assert(*propertyDescriptor == nullptr || !Js::CrossSite::NeedMarshalVar(*propertyDescriptor, scriptContext));
  1304. return JsNoError;
  1305. }
  1306. CHAKRA_API JsGetOwnPropertyDescriptor(_In_ JsValueRef object, _In_ JsPropertyIdRef propertyId, _Out_ JsValueRef *propertyDescriptor)
  1307. {
  1308. return ContextAPIWrapper<JSRT_MAYBE_TRUE>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1309. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTGetOwnPropertyInfo, (const Js::PropertyRecord *)propertyId, object);
  1310. VALIDATE_INCOMING_OBJECT(object, scriptContext);
  1311. VALIDATE_INCOMING_PROPERTYID(propertyId);
  1312. PARAM_NOT_NULL(propertyDescriptor);
  1313. *propertyDescriptor = nullptr;
  1314. JsErrorCode err = JsGetOwnPropertyDescriptorCommon(scriptContext, object, (const Js::PropertyRecord *)propertyId,
  1315. propertyDescriptor);
  1316. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, propertyDescriptor);
  1317. return err;
  1318. });
  1319. }
  1320. #ifdef _CHAKRACOREBUILD
  1321. CHAKRA_API JsObjectGetOwnPropertyDescriptor(_In_ JsValueRef object, _In_ JsValueRef propertyId, _Out_ JsValueRef *propertyDescriptor)
  1322. {
  1323. return ContextAPIWrapper<JSRT_MAYBE_TRUE>([&] (Js::ScriptContext *scriptContext,
  1324. TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1325. PERFORM_JSRT_TTD_RECORD_ACTION_NOT_IMPLEMENTED(scriptContext);
  1326. VALIDATE_INCOMING_OBJECT(object, scriptContext);
  1327. VALIDATE_INCOMING_RECYCLABLE(propertyId, scriptContext);
  1328. PARAM_NOT_NULL(propertyDescriptor);
  1329. *propertyDescriptor = nullptr;
  1330. const Js::PropertyRecord *propertyRecord = nullptr;
  1331. JsErrorCode errorValue = InternalGetPropertyRecord(scriptContext,
  1332. Js::RecyclableObject::FromVar(propertyId), &propertyRecord);
  1333. if (errorValue != JsNoError)
  1334. {
  1335. return errorValue;
  1336. }
  1337. Assert(propertyRecord != nullptr);
  1338. return JsGetOwnPropertyDescriptorCommon(scriptContext, object, propertyRecord, propertyDescriptor);
  1339. });
  1340. }
  1341. #endif
  1342. static JsErrorCode JsSetPropertyCommon(Js::ScriptContext * scriptContext, _In_ JsValueRef object,
  1343. _In_ const Js::PropertyRecord * propertyRecord, _In_ JsValueRef value, _In_ bool useStrictRules)
  1344. {
  1345. AssertMsg(scriptContext->GetThreadContext()->IsScriptActive(), "Caller is expected to be under ContextAPIWrapper!");
  1346. Js::JavascriptOperators::OP_SetProperty(object, propertyRecord->GetPropertyId(),
  1347. value, scriptContext, nullptr, useStrictRules ? Js::PropertyOperation_StrictMode : Js::PropertyOperation_None);
  1348. return JsNoError;
  1349. }
  1350. CHAKRA_API JsSetProperty(_In_ JsValueRef object, _In_ JsPropertyIdRef propertyId, _In_ JsValueRef value, _In_ bool useStrictRules)
  1351. {
  1352. return ContextAPIWrapper<JSRT_MAYBE_TRUE>([&] (Js::ScriptContext *scriptContext,
  1353. TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1354. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTSetProperty, object, (const Js::PropertyRecord *)propertyId, value, useStrictRules);
  1355. VALIDATE_INCOMING_OBJECT(object, scriptContext);
  1356. VALIDATE_INCOMING_PROPERTYID(propertyId);
  1357. VALIDATE_INCOMING_REFERENCE(value, scriptContext);
  1358. return JsSetPropertyCommon(scriptContext, object, (const Js::PropertyRecord *)propertyId,
  1359. value, useStrictRules);
  1360. });
  1361. }
  1362. #ifdef _CHAKRACOREBUILD
  1363. CHAKRA_API JsObjectSetProperty(_In_ JsValueRef object, _In_ JsValueRef propertyId, _In_ JsValueRef value, _In_ bool useStrictRules)
  1364. {
  1365. return ContextAPIWrapper<JSRT_MAYBE_TRUE>([&] (Js::ScriptContext *scriptContext,
  1366. TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1367. PERFORM_JSRT_TTD_RECORD_ACTION_NOT_IMPLEMENTED(scriptContext);
  1368. VALIDATE_INCOMING_OBJECT(object, scriptContext);
  1369. VALIDATE_INCOMING_RECYCLABLE(propertyId, scriptContext);
  1370. VALIDATE_INCOMING_REFERENCE(value, scriptContext);
  1371. const Js::PropertyRecord *propertyRecord = nullptr;
  1372. JsErrorCode errorValue = InternalGetPropertyRecord(scriptContext,
  1373. Js::RecyclableObject::FromVar(propertyId), &propertyRecord);
  1374. if (errorValue != JsNoError)
  1375. {
  1376. return errorValue;
  1377. }
  1378. Assert(propertyRecord != nullptr);
  1379. return JsSetPropertyCommon(scriptContext, object, propertyRecord, value, useStrictRules);
  1380. });
  1381. }
  1382. #endif
  1383. CHAKRA_API JsHasProperty(_In_ JsValueRef object, _In_ JsPropertyIdRef propertyId, _Out_ bool *hasProperty)
  1384. {
  1385. VALIDATE_JSREF(object);
  1386. if (!Js::JavascriptOperators::IsObject(object)) return JsErrorArgumentNotObject;
  1387. auto internalHasProperty = [&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1388. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTHasProperty, (Js::PropertyRecord *)propertyId, object);
  1389. VALIDATE_INCOMING_OBJECT(object, scriptContext);
  1390. VALIDATE_INCOMING_PROPERTYID(propertyId);
  1391. PARAM_NOT_NULL(hasProperty);
  1392. *hasProperty = false;
  1393. Js::RecyclableObject * instance = Js::RecyclableObject::FromVar(object);
  1394. *hasProperty = Js::JavascriptOperators::HasProperty(instance, ((Js::PropertyRecord *)propertyId)->GetPropertyId()) != 0;
  1395. return JsNoError;
  1396. };
  1397. Js::RecyclableObject* robject = Js::RecyclableObject::FromVar(object);
  1398. Js::TypeId typeId = Js::JavascriptOperators::GetTypeId(robject);
  1399. while (typeId != Js::TypeIds_Null && typeId != Js::TypeIds_Proxy)
  1400. {
  1401. robject = robject->GetPrototype();
  1402. typeId = Js::JavascriptOperators::GetTypeId(robject);
  1403. }
  1404. if (typeId == Js::TypeIds_Proxy)
  1405. {
  1406. return ContextAPIWrapper<JSRT_MAYBE_TRUE>(internalHasProperty);
  1407. }
  1408. else
  1409. {
  1410. return ContextAPINoScriptWrapper(internalHasProperty);
  1411. }
  1412. }
  1413. #ifdef _CHAKRACOREBUILD
  1414. CHAKRA_API JsObjectHasProperty(_In_ JsValueRef object, _In_ JsValueRef propertyId, _Out_ bool *hasProperty)
  1415. {
  1416. VALIDATE_JSREF(object);
  1417. if (!Js::JavascriptOperators::IsObject(object)) return JsErrorArgumentNotObject;
  1418. auto internalHasProperty = [&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1419. PERFORM_JSRT_TTD_RECORD_ACTION_NOT_IMPLEMENTED(scriptContext);
  1420. VALIDATE_INCOMING_OBJECT(object, scriptContext);
  1421. VALIDATE_INCOMING_RECYCLABLE(propertyId, scriptContext);
  1422. PARAM_NOT_NULL(hasProperty);
  1423. *hasProperty = false;
  1424. const Js::PropertyRecord *propertyRecord = nullptr;
  1425. JsErrorCode errorValue = InternalGetPropertyRecord(scriptContext,
  1426. Js::RecyclableObject::FromVar(propertyId), &propertyRecord);
  1427. if (errorValue != JsNoError)
  1428. {
  1429. return errorValue;
  1430. }
  1431. Js::RecyclableObject * instance = Js::RecyclableObject::FromVar(object);
  1432. *hasProperty = Js::JavascriptOperators::HasProperty(instance, propertyRecord->GetPropertyId()) != 0;
  1433. return JsNoError;
  1434. };
  1435. Js::RecyclableObject* robject = Js::RecyclableObject::FromVar(object);
  1436. Js::TypeId typeId = Js::JavascriptOperators::GetTypeId(robject);
  1437. while (typeId != Js::TypeIds_Null && typeId != Js::TypeIds_Proxy)
  1438. {
  1439. robject = robject->GetPrototype();
  1440. typeId = Js::JavascriptOperators::GetTypeId(robject);
  1441. }
  1442. if (typeId == Js::TypeIds_Proxy)
  1443. {
  1444. return ContextAPIWrapper<JSRT_MAYBE_TRUE>(internalHasProperty);
  1445. }
  1446. else
  1447. {
  1448. return ContextAPINoScriptWrapper(internalHasProperty);
  1449. }
  1450. }
  1451. #endif
  1452. static JsErrorCode JsDeletePropertyCommon(Js::ScriptContext * scriptContext, _In_ JsValueRef object,
  1453. _In_ const Js::PropertyRecord * propertyRecord, _In_ bool useStrictRules, _Out_ JsValueRef *result)
  1454. {
  1455. AssertMsg(scriptContext->GetThreadContext()->IsScriptActive(), "Caller is expected to be under ContextAPIWrapper!");
  1456. *result = Js::JavascriptOperators::OP_DeleteProperty((Js::Var)object,
  1457. propertyRecord->GetPropertyId(),
  1458. scriptContext, useStrictRules ? Js::PropertyOperation_StrictMode : Js::PropertyOperation_None);
  1459. Assert(*result == nullptr || !Js::CrossSite::NeedMarshalVar(*result, scriptContext));
  1460. return JsNoError;
  1461. }
  1462. CHAKRA_API JsDeleteProperty(_In_ JsValueRef object, _In_ JsPropertyIdRef propertyId,
  1463. _In_ bool useStrictRules, _Out_ JsValueRef *result)
  1464. {
  1465. return ContextAPIWrapper<JSRT_MAYBE_TRUE>([&] (Js::ScriptContext *scriptContext,
  1466. TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1467. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTDeleteProperty, object, (const Js::PropertyRecord *)propertyId, useStrictRules);
  1468. VALIDATE_INCOMING_OBJECT(object, scriptContext);
  1469. VALIDATE_INCOMING_PROPERTYID(propertyId);
  1470. PARAM_NOT_NULL(result);
  1471. *result = nullptr;
  1472. JsErrorCode err = JsDeletePropertyCommon(scriptContext, object, (const Js::PropertyRecord *)propertyId,
  1473. useStrictRules, result);
  1474. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, result);
  1475. return err;
  1476. });
  1477. }
  1478. #ifdef _CHAKRACOREBUILD
  1479. CHAKRA_API JsObjectDeleteProperty(_In_ JsValueRef object, _In_ JsValueRef propertyId,
  1480. _In_ bool useStrictRules, _Out_ JsValueRef *result)
  1481. {
  1482. return ContextAPIWrapper<JSRT_MAYBE_TRUE>([&] (Js::ScriptContext *scriptContext,
  1483. TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1484. PERFORM_JSRT_TTD_RECORD_ACTION_NOT_IMPLEMENTED(scriptContext);
  1485. VALIDATE_INCOMING_OBJECT(object, scriptContext);
  1486. VALIDATE_INCOMING_RECYCLABLE(propertyId, scriptContext);
  1487. PARAM_NOT_NULL(result);
  1488. *result = nullptr;
  1489. const Js::PropertyRecord *propertyRecord = nullptr;
  1490. JsErrorCode errorValue = InternalGetPropertyRecord(scriptContext,
  1491. Js::RecyclableObject::FromVar(propertyId), &propertyRecord);
  1492. if (errorValue != JsNoError)
  1493. {
  1494. return errorValue;
  1495. }
  1496. Assert(propertyRecord != nullptr);
  1497. return JsDeletePropertyCommon(scriptContext, object, propertyRecord,
  1498. useStrictRules, result);
  1499. });
  1500. }
  1501. #endif
  1502. static JsErrorCode JsDefinePropertyCommon(Js::ScriptContext * scriptContext, _In_ JsValueRef object,
  1503. _In_ const Js::PropertyRecord *propertyRecord, _In_ JsValueRef propertyDescriptor,
  1504. _Out_ bool *result)
  1505. {
  1506. AssertMsg(scriptContext->GetThreadContext()->IsScriptActive(), "Caller is expected to be under ContextAPIWrapper!");
  1507. Js::PropertyDescriptor propertyDescriptorValue;
  1508. if (!Js::JavascriptOperators::ToPropertyDescriptor(propertyDescriptor, &propertyDescriptorValue, scriptContext))
  1509. {
  1510. return JsErrorInvalidArgument;
  1511. }
  1512. *result = Js::JavascriptOperators::DefineOwnPropertyDescriptor(
  1513. Js::RecyclableObject::FromVar(object), propertyRecord->GetPropertyId(),
  1514. propertyDescriptorValue, true, scriptContext) != 0;
  1515. return JsNoError;
  1516. }
  1517. CHAKRA_API JsDefineProperty(_In_ JsValueRef object, _In_ JsPropertyIdRef propertyId,
  1518. _In_ JsValueRef propertyDescriptor, _Out_ bool *result)
  1519. {
  1520. return ContextAPIWrapper<JSRT_MAYBE_TRUE>([&] (Js::ScriptContext *scriptContext,
  1521. TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1522. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTDefineProperty, object, (const Js::PropertyRecord *)propertyId, propertyDescriptor);
  1523. VALIDATE_INCOMING_OBJECT(object, scriptContext);
  1524. VALIDATE_INCOMING_PROPERTYID(propertyId);
  1525. VALIDATE_INCOMING_OBJECT(propertyDescriptor, scriptContext);
  1526. PARAM_NOT_NULL(result);
  1527. *result = false;
  1528. return JsDefinePropertyCommon(scriptContext, object, (const Js::PropertyRecord *)propertyId,
  1529. propertyDescriptor, result);
  1530. });
  1531. }
  1532. #ifdef _CHAKRACOREBUILD
  1533. CHAKRA_API JsObjectDefineProperty(_In_ JsValueRef object, _In_ JsValueRef propertyId,
  1534. _In_ JsValueRef propertyDescriptor, _Out_ bool *result)
  1535. {
  1536. return ContextAPIWrapper<JSRT_MAYBE_TRUE>([&] (Js::ScriptContext *scriptContext,
  1537. TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1538. PERFORM_JSRT_TTD_RECORD_ACTION_NOT_IMPLEMENTED(scriptContext);
  1539. VALIDATE_INCOMING_OBJECT(object, scriptContext);
  1540. VALIDATE_INCOMING_RECYCLABLE(propertyId, scriptContext);
  1541. VALIDATE_INCOMING_OBJECT(propertyDescriptor, scriptContext);
  1542. PARAM_NOT_NULL(result);
  1543. *result = false;
  1544. const Js::PropertyRecord *propertyRecord = nullptr;
  1545. JsErrorCode errorValue = InternalGetPropertyRecord(scriptContext,
  1546. Js::RecyclableObject::FromVar(propertyId), &propertyRecord);
  1547. if (errorValue != JsNoError)
  1548. {
  1549. return errorValue;
  1550. }
  1551. return JsDefinePropertyCommon(scriptContext, object, propertyRecord, propertyDescriptor, result);
  1552. });
  1553. }
  1554. #endif
  1555. CHAKRA_API JsGetOwnPropertyNames(_In_ JsValueRef object, _Out_ JsValueRef *propertyNames)
  1556. {
  1557. return ContextAPIWrapper<JSRT_MAYBE_TRUE>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1558. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTGetOwnPropertyNamesInfo, object);
  1559. VALIDATE_INCOMING_OBJECT(object, scriptContext);
  1560. PARAM_NOT_NULL(propertyNames);
  1561. *propertyNames = nullptr;
  1562. *propertyNames = Js::JavascriptOperators::GetOwnPropertyNames(object, scriptContext);
  1563. Assert(*propertyNames == nullptr || !Js::CrossSite::NeedMarshalVar(*propertyNames, scriptContext));
  1564. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, propertyNames);
  1565. return JsNoError;
  1566. });
  1567. }
  1568. CHAKRA_API JsGetOwnPropertySymbols(_In_ JsValueRef object, _Out_ JsValueRef *propertySymbols)
  1569. {
  1570. return ContextAPIWrapper<JSRT_MAYBE_TRUE>([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1571. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTGetOwnPropertySymbolsInfo, object);
  1572. VALIDATE_INCOMING_OBJECT(object, scriptContext);
  1573. PARAM_NOT_NULL(propertySymbols);
  1574. *propertySymbols = Js::JavascriptOperators::GetOwnPropertySymbols(object, scriptContext);
  1575. Assert(*propertySymbols == nullptr || !Js::CrossSite::NeedMarshalVar(*propertySymbols, scriptContext));
  1576. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, propertySymbols);
  1577. return JsNoError;
  1578. });
  1579. }
  1580. CHAKRA_API JsCreateArray(_In_ unsigned int length, _Out_ JsValueRef *result)
  1581. {
  1582. return ContextAPINoScriptWrapper([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1583. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTAllocateBasicArray, length);
  1584. PARAM_NOT_NULL(result);
  1585. *result = nullptr;
  1586. *result = scriptContext->GetLibrary()->CreateArray(length);
  1587. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, result);
  1588. return JsNoError;
  1589. });
  1590. }
  1591. CHAKRA_API JsCreateArrayBuffer(_In_ unsigned int byteLength, _Out_ JsValueRef *result)
  1592. {
  1593. return ContextAPIWrapper<JSRT_MAYBE_TRUE>([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1594. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTAllocateArrayBuffer, byteLength);
  1595. PARAM_NOT_NULL(result);
  1596. Js::JavascriptLibrary* library = scriptContext->GetLibrary();
  1597. *result = library->CreateArrayBuffer(byteLength);
  1598. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, result);
  1599. JS_ETW(EventWriteJSCRIPT_RECYCLER_ALLOCATE_OBJECT(*result));
  1600. return JsNoError;
  1601. });
  1602. }
  1603. #ifdef _CHAKRACOREBUILD
  1604. CHAKRA_API JsCreateSharedArrayBufferWithSharedContent(_In_ JsSharedArrayBufferContentHandle sharedContents, _Out_ JsValueRef *result)
  1605. {
  1606. return ContextAPIWrapper<JSRT_MAYBE_TRUE>([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1607. PARAM_NOT_NULL(result);
  1608. Js::JavascriptLibrary* library = scriptContext->GetLibrary();
  1609. *result = library->CreateSharedArrayBuffer((Js::SharedContents*)sharedContents);
  1610. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, result);
  1611. JS_ETW(EventWriteJSCRIPT_RECYCLER_ALLOCATE_OBJECT(*result));
  1612. return JsNoError;
  1613. });
  1614. }
  1615. CHAKRA_API JsGetSharedArrayBufferContent(_In_ JsValueRef sharedArrayBuffer, _Out_ JsSharedArrayBufferContentHandle *sharedContents)
  1616. {
  1617. return ContextAPIWrapper<JSRT_MAYBE_TRUE>([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1618. PARAM_NOT_NULL(sharedContents);
  1619. if (!Js::SharedArrayBuffer::Is(sharedArrayBuffer))
  1620. {
  1621. return JsErrorInvalidArgument;
  1622. }
  1623. Js::SharedContents**& content = (Js::SharedContents**&)sharedContents;
  1624. *content = Js::SharedArrayBuffer::FromVar(sharedArrayBuffer)->GetSharedContents();
  1625. if (*content == nullptr)
  1626. {
  1627. return JsErrorFatal;
  1628. }
  1629. (*content)->AddRef();
  1630. return JsNoError;
  1631. });
  1632. }
  1633. CHAKRA_API JsReleaseSharedArrayBufferContentHandle(_In_ JsSharedArrayBufferContentHandle sharedContents)
  1634. {
  1635. return ContextAPIWrapper<JSRT_MAYBE_TRUE>([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1636. ((Js::SharedContents*)sharedContents)->Release();
  1637. return JsNoError;
  1638. });
  1639. }
  1640. #endif // _CHAKRACOREBUILD
  1641. CHAKRA_API JsCreateExternalArrayBuffer(_Pre_maybenull_ _Pre_writable_byte_size_(byteLength) void *data, _In_ unsigned int byteLength,
  1642. _In_opt_ JsFinalizeCallback finalizeCallback, _In_opt_ void *callbackState, _Out_ JsValueRef *result)
  1643. {
  1644. return ContextAPINoScriptWrapper([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1645. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTAllocateExternalArrayBuffer, reinterpret_cast<BYTE*>(data), byteLength);
  1646. PARAM_NOT_NULL(result);
  1647. if (data == nullptr && byteLength > 0)
  1648. {
  1649. return JsErrorInvalidArgument;
  1650. }
  1651. Js::JavascriptLibrary* library = scriptContext->GetLibrary();
  1652. *result = Js::JsrtExternalArrayBuffer::New(
  1653. reinterpret_cast<BYTE*>(data),
  1654. byteLength,
  1655. finalizeCallback,
  1656. callbackState,
  1657. library->GetArrayBufferType());
  1658. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, result);
  1659. JS_ETW(EventWriteJSCRIPT_RECYCLER_ALLOCATE_OBJECT(*result));
  1660. return JsNoError;
  1661. });
  1662. }
  1663. CHAKRA_API JsCreateTypedArray(_In_ JsTypedArrayType arrayType, _In_ JsValueRef baseArray, _In_ unsigned int byteOffset,
  1664. _In_ unsigned int elementLength, _Out_ JsValueRef *result)
  1665. {
  1666. return ContextAPIWrapper<JSRT_MAYBE_TRUE>([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1667. PERFORM_JSRT_TTD_RECORD_ACTION_NOT_IMPLEMENTED(scriptContext);
  1668. if (baseArray != JS_INVALID_REFERENCE)
  1669. {
  1670. VALIDATE_INCOMING_REFERENCE(baseArray, scriptContext);
  1671. }
  1672. PARAM_NOT_NULL(result);
  1673. Js::JavascriptLibrary* library = scriptContext->GetLibrary();
  1674. const bool fromArrayBuffer = (baseArray != JS_INVALID_REFERENCE && Js::ArrayBuffer::Is(baseArray));
  1675. if (byteOffset != 0 && !fromArrayBuffer)
  1676. {
  1677. return JsErrorInvalidArgument;
  1678. }
  1679. if (elementLength != 0 && !(baseArray == JS_INVALID_REFERENCE || fromArrayBuffer))
  1680. {
  1681. return JsErrorInvalidArgument;
  1682. }
  1683. Js::JavascriptFunction* constructorFunc = nullptr;
  1684. Js::Var values[4] =
  1685. {
  1686. library->GetUndefined(),
  1687. baseArray != nullptr ? baseArray : Js::JavascriptNumber::ToVar(elementLength, scriptContext)
  1688. };
  1689. if (fromArrayBuffer)
  1690. {
  1691. values[2] = Js::JavascriptNumber::ToVar(byteOffset, scriptContext);
  1692. values[3] = Js::JavascriptNumber::ToVar(elementLength, scriptContext);
  1693. }
  1694. Js::CallInfo info(Js::CallFlags_New, fromArrayBuffer ? 4 : 2);
  1695. Js::Arguments args(info, values);
  1696. switch (arrayType)
  1697. {
  1698. case JsArrayTypeInt8:
  1699. constructorFunc = library->GetInt8ArrayConstructor();
  1700. break;
  1701. case JsArrayTypeUint8:
  1702. constructorFunc = library->GetUint8ArrayConstructor();
  1703. break;
  1704. case JsArrayTypeUint8Clamped:
  1705. constructorFunc = library->GetUint8ClampedArrayConstructor();
  1706. break;
  1707. case JsArrayTypeInt16:
  1708. constructorFunc = library->GetInt16ArrayConstructor();
  1709. break;
  1710. case JsArrayTypeUint16:
  1711. constructorFunc = library->GetUint16ArrayConstructor();
  1712. break;
  1713. case JsArrayTypeInt32:
  1714. constructorFunc = library->GetInt32ArrayConstructor();
  1715. break;
  1716. case JsArrayTypeUint32:
  1717. constructorFunc = library->GetUint32ArrayConstructor();
  1718. break;
  1719. case JsArrayTypeFloat32:
  1720. constructorFunc = library->GetFloat32ArrayConstructor();
  1721. break;
  1722. case JsArrayTypeFloat64:
  1723. constructorFunc = library->GetFloat64ArrayConstructor();
  1724. break;
  1725. default:
  1726. return JsErrorInvalidArgument;
  1727. }
  1728. *result = Js::JavascriptFunction::CallAsConstructor(constructorFunc, /* overridingNewTarget = */nullptr, args, scriptContext);
  1729. JS_ETW(EventWriteJSCRIPT_RECYCLER_ALLOCATE_OBJECT(*result));
  1730. return JsNoError;
  1731. });
  1732. }
  1733. CHAKRA_API JsCreateDataView(_In_ JsValueRef arrayBuffer, _In_ unsigned int byteOffset, _In_ unsigned int byteLength, _Out_ JsValueRef *result)
  1734. {
  1735. return ContextAPIWrapper<JSRT_MAYBE_TRUE>([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1736. PERFORM_JSRT_TTD_RECORD_ACTION_NOT_IMPLEMENTED(scriptContext);
  1737. VALIDATE_INCOMING_REFERENCE(arrayBuffer, scriptContext);
  1738. PARAM_NOT_NULL(result);
  1739. if (!Js::ArrayBuffer::Is(arrayBuffer))
  1740. {
  1741. return JsErrorInvalidArgument;
  1742. }
  1743. Js::JavascriptLibrary* library = scriptContext->GetLibrary();
  1744. *result = library->CreateDataView(Js::ArrayBuffer::FromVar(arrayBuffer), byteOffset, byteLength);
  1745. JS_ETW(EventWriteJSCRIPT_RECYCLER_ALLOCATE_OBJECT(*result));
  1746. return JsNoError;
  1747. });
  1748. }
  1749. C_ASSERT(JsArrayTypeUint8 - Js::TypeIds_Uint8Array == JsArrayTypeInt8 - Js::TypeIds_Int8Array);
  1750. C_ASSERT(JsArrayTypeUint8Clamped - Js::TypeIds_Uint8ClampedArray == JsArrayTypeInt8 - Js::TypeIds_Int8Array);
  1751. C_ASSERT(JsArrayTypeInt16 - Js::TypeIds_Int16Array == JsArrayTypeInt8 - Js::TypeIds_Int8Array);
  1752. C_ASSERT(JsArrayTypeUint16 - Js::TypeIds_Uint16Array == JsArrayTypeInt8 - Js::TypeIds_Int8Array);
  1753. C_ASSERT(JsArrayTypeInt32 - Js::TypeIds_Int32Array == JsArrayTypeInt8 - Js::TypeIds_Int8Array);
  1754. C_ASSERT(JsArrayTypeUint32 - Js::TypeIds_Uint32Array == JsArrayTypeInt8 - Js::TypeIds_Int8Array);
  1755. C_ASSERT(JsArrayTypeFloat32 - Js::TypeIds_Float32Array == JsArrayTypeInt8 - Js::TypeIds_Int8Array);
  1756. C_ASSERT(JsArrayTypeFloat64 - Js::TypeIds_Float64Array == JsArrayTypeInt8 - Js::TypeIds_Int8Array);
  1757. inline JsTypedArrayType GetTypedArrayType(Js::TypeId typeId)
  1758. {
  1759. Assert(Js::TypedArrayBase::Is(typeId));
  1760. return static_cast<JsTypedArrayType>(typeId + (JsArrayTypeInt8 - Js::TypeIds_Int8Array));
  1761. }
  1762. CHAKRA_API JsGetTypedArrayInfo(_In_ JsValueRef typedArray, _Out_opt_ JsTypedArrayType *arrayType, _Out_opt_ JsValueRef *arrayBuffer,
  1763. _Out_opt_ unsigned int *byteOffset, _Out_opt_ unsigned int *byteLength)
  1764. {
  1765. VALIDATE_JSREF(typedArray);
  1766. BEGIN_JSRT_NO_EXCEPTION
  1767. {
  1768. const Js::TypeId typeId = Js::JavascriptOperators::GetTypeId(typedArray);
  1769. if (!Js::TypedArrayBase::Is(typeId))
  1770. {
  1771. RETURN_NO_EXCEPTION(JsErrorInvalidArgument);
  1772. }
  1773. if (arrayType != nullptr) {
  1774. *arrayType = GetTypedArrayType(typeId);
  1775. }
  1776. Js::TypedArrayBase* typedArrayBase = Js::TypedArrayBase::FromVar(typedArray);
  1777. if (arrayBuffer != nullptr) {
  1778. *arrayBuffer = typedArrayBase->GetArrayBuffer();
  1779. }
  1780. if (byteOffset != nullptr) {
  1781. *byteOffset = typedArrayBase->GetByteOffset();
  1782. }
  1783. if (byteLength != nullptr) {
  1784. *byteLength = typedArrayBase->GetByteLength();
  1785. }
  1786. }
  1787. #if ENABLE_TTD
  1788. Js::ScriptContext* scriptContext = Js::RecyclableObject::FromVar(typedArray)->GetScriptContext();
  1789. if(PERFORM_JSRT_TTD_RECORD_ACTION_CHECK(scriptContext) && arrayBuffer != nullptr)
  1790. {
  1791. scriptContext->GetThreadContext()->TTDLog->RecordJsRTGetTypedArrayInfo(typedArray, *arrayBuffer);
  1792. }
  1793. #endif
  1794. END_JSRT_NO_EXCEPTION
  1795. }
  1796. CHAKRA_API JsGetArrayBufferStorage(_In_ JsValueRef instance, _Outptr_result_bytebuffer_(*bufferLength) BYTE **buffer,
  1797. _Out_ unsigned int *bufferLength)
  1798. {
  1799. VALIDATE_JSREF(instance);
  1800. PARAM_NOT_NULL(buffer);
  1801. PARAM_NOT_NULL(bufferLength);
  1802. BEGIN_JSRT_NO_EXCEPTION
  1803. {
  1804. if (!Js::ArrayBuffer::Is(instance))
  1805. {
  1806. RETURN_NO_EXCEPTION(JsErrorInvalidArgument);
  1807. }
  1808. Js::ArrayBuffer* arrayBuffer = Js::ArrayBuffer::FromVar(instance);
  1809. *buffer = arrayBuffer->GetBuffer();
  1810. *bufferLength = arrayBuffer->GetByteLength();
  1811. }
  1812. END_JSRT_NO_EXCEPTION
  1813. }
  1814. CHAKRA_API JsGetTypedArrayStorage(_In_ JsValueRef instance, _Outptr_result_bytebuffer_(*bufferLength) BYTE **buffer,
  1815. _Out_ unsigned int *bufferLength, _Out_opt_ JsTypedArrayType *typedArrayType, _Out_opt_ int *elementSize)
  1816. {
  1817. VALIDATE_JSREF(instance);
  1818. PARAM_NOT_NULL(buffer);
  1819. PARAM_NOT_NULL(bufferLength);
  1820. BEGIN_JSRT_NO_EXCEPTION
  1821. {
  1822. const Js::TypeId typeId = Js::JavascriptOperators::GetTypeId(instance);
  1823. if (!Js::TypedArrayBase::Is(typeId))
  1824. {
  1825. RETURN_NO_EXCEPTION(JsErrorInvalidArgument);
  1826. }
  1827. Js::TypedArrayBase* typedArrayBase = Js::TypedArrayBase::FromVar(instance);
  1828. *buffer = typedArrayBase->GetByteBuffer();
  1829. *bufferLength = typedArrayBase->GetByteLength();
  1830. if (typedArrayType)
  1831. {
  1832. *typedArrayType = GetTypedArrayType(typeId);
  1833. }
  1834. if (elementSize)
  1835. {
  1836. switch (typeId)
  1837. {
  1838. case Js::TypeIds_Int8Array:
  1839. *elementSize = sizeof(int8);
  1840. break;
  1841. case Js::TypeIds_Uint8Array:
  1842. *elementSize = sizeof(uint8);
  1843. break;
  1844. case Js::TypeIds_Uint8ClampedArray:
  1845. *elementSize = sizeof(uint8);
  1846. break;
  1847. case Js::TypeIds_Int16Array:
  1848. *elementSize = sizeof(int16);
  1849. break;
  1850. case Js::TypeIds_Uint16Array:
  1851. *elementSize = sizeof(uint16);
  1852. break;
  1853. case Js::TypeIds_Int32Array:
  1854. *elementSize = sizeof(int32);
  1855. break;
  1856. case Js::TypeIds_Uint32Array:
  1857. *elementSize = sizeof(uint32);
  1858. break;
  1859. case Js::TypeIds_Float32Array:
  1860. *elementSize = sizeof(float);
  1861. break;
  1862. case Js::TypeIds_Float64Array:
  1863. *elementSize = sizeof(double);
  1864. break;
  1865. default:
  1866. AssertMsg(FALSE, "invalid typed array type");
  1867. *elementSize = 1;
  1868. RETURN_NO_EXCEPTION(JsErrorFatal);
  1869. }
  1870. }
  1871. }
  1872. END_JSRT_NO_EXCEPTION
  1873. }
  1874. CHAKRA_API JsGetDataViewStorage(_In_ JsValueRef instance, _Outptr_result_bytebuffer_(*bufferLength) BYTE **buffer, _Out_ unsigned int *bufferLength)
  1875. {
  1876. VALIDATE_JSREF(instance);
  1877. PARAM_NOT_NULL(buffer);
  1878. PARAM_NOT_NULL(bufferLength);
  1879. BEGIN_JSRT_NO_EXCEPTION
  1880. {
  1881. if (!Js::DataView::Is(instance))
  1882. {
  1883. RETURN_NO_EXCEPTION(JsErrorInvalidArgument);
  1884. }
  1885. Js::DataView* dataView = Js::DataView::FromVar(instance);
  1886. *buffer = dataView->GetArrayBuffer()->GetBuffer() + dataView->GetByteOffset();
  1887. *bufferLength = dataView->GetLength();
  1888. }
  1889. END_JSRT_NO_EXCEPTION
  1890. }
  1891. CHAKRA_API JsCreateSymbol(_In_ JsValueRef description, _Out_ JsValueRef *result)
  1892. {
  1893. return ContextAPIWrapper<JSRT_MAYBE_TRUE>([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1894. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTCreateSymbol, description);
  1895. PARAM_NOT_NULL(result);
  1896. *result = nullptr;
  1897. Js::JavascriptString* descriptionString;
  1898. if (description != JS_INVALID_REFERENCE)
  1899. {
  1900. VALIDATE_INCOMING_REFERENCE(description, scriptContext);
  1901. descriptionString = Js::JavascriptConversion::ToString(description, scriptContext);
  1902. }
  1903. else
  1904. {
  1905. descriptionString = scriptContext->GetLibrary()->GetEmptyString();
  1906. }
  1907. *result = scriptContext->GetLibrary()->CreateSymbol(descriptionString);
  1908. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, result);
  1909. return JsNoError;
  1910. });
  1911. }
  1912. CHAKRA_API JsHasIndexedProperty(_In_ JsValueRef object, _In_ JsValueRef index, _Out_ bool *result)
  1913. {
  1914. return ContextAPIWrapper<JSRT_MAYBE_TRUE>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1915. PERFORM_JSRT_TTD_RECORD_ACTION_NOT_IMPLEMENTED(scriptContext);
  1916. VALIDATE_INCOMING_OBJECT(object, scriptContext);
  1917. VALIDATE_INCOMING_REFERENCE(index, scriptContext);
  1918. PARAM_NOT_NULL(result);
  1919. *result = false;
  1920. *result = Js::JavascriptOperators::OP_HasItem((Js::Var)object, (Js::Var)index, scriptContext) != 0;
  1921. return JsNoError;
  1922. });
  1923. }
  1924. CHAKRA_API JsGetIndexedProperty(_In_ JsValueRef object, _In_ JsValueRef index, _Out_ JsValueRef *result)
  1925. {
  1926. return ContextAPIWrapper<JSRT_MAYBE_TRUE>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1927. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTGetIndex, index, object);
  1928. VALIDATE_INCOMING_OBJECT(object, scriptContext);
  1929. VALIDATE_INCOMING_REFERENCE(index, scriptContext);
  1930. PARAM_NOT_NULL(result);
  1931. *result = nullptr;
  1932. *result = (JsValueRef)Js::JavascriptOperators::OP_GetElementI((Js::Var)object, (Js::Var)index, scriptContext);
  1933. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, result);
  1934. return JsNoError;
  1935. });
  1936. }
  1937. CHAKRA_API JsSetIndexedProperty(_In_ JsValueRef object, _In_ JsValueRef index, _In_ JsValueRef value)
  1938. {
  1939. return ContextAPIWrapper<JSRT_MAYBE_TRUE>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1940. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTSetIndex, object, index, value);
  1941. VALIDATE_INCOMING_OBJECT(object, scriptContext);
  1942. VALIDATE_INCOMING_REFERENCE(index, scriptContext);
  1943. VALIDATE_INCOMING_REFERENCE(value, scriptContext);
  1944. Js::JavascriptOperators::OP_SetElementI((Js::Var)object, (Js::Var)index, (Js::Var)value, scriptContext);
  1945. return JsNoError;
  1946. });
  1947. }
  1948. CHAKRA_API JsDeleteIndexedProperty(_In_ JsValueRef object, _In_ JsValueRef index)
  1949. {
  1950. return ContextAPIWrapper<JSRT_MAYBE_TRUE>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1951. PERFORM_JSRT_TTD_RECORD_ACTION_NOT_IMPLEMENTED(scriptContext);
  1952. VALIDATE_INCOMING_OBJECT(object, scriptContext);
  1953. VALIDATE_INCOMING_REFERENCE(index, scriptContext);
  1954. Js::JavascriptOperators::OP_DeleteElementI((Js::Var)object, (Js::Var)index, scriptContext);
  1955. return JsNoError;
  1956. });
  1957. }
  1958. template <class T, bool clamped = false> struct TypedArrayTypeTraits { static const JsTypedArrayType cTypedArrayType; };
  1959. template<> struct TypedArrayTypeTraits<int8> { static const JsTypedArrayType cTypedArrayType = JsTypedArrayType::JsArrayTypeInt8; };
  1960. template<> struct TypedArrayTypeTraits<uint8, false> { static const JsTypedArrayType cTypedArrayType = JsTypedArrayType::JsArrayTypeUint8; };
  1961. template<> struct TypedArrayTypeTraits<uint8, true> { static const JsTypedArrayType cTypedArrayType = JsTypedArrayType::JsArrayTypeUint8Clamped; };
  1962. template<> struct TypedArrayTypeTraits<int16> { static const JsTypedArrayType cTypedArrayType = JsTypedArrayType::JsArrayTypeInt16; };
  1963. template<> struct TypedArrayTypeTraits<uint16> { static const JsTypedArrayType cTypedArrayType = JsTypedArrayType::JsArrayTypeUint16; };
  1964. template<> struct TypedArrayTypeTraits<int32> { static const JsTypedArrayType cTypedArrayType = JsTypedArrayType::JsArrayTypeInt32; };
  1965. template<> struct TypedArrayTypeTraits<uint32> { static const JsTypedArrayType cTypedArrayType = JsTypedArrayType::JsArrayTypeUint32; };
  1966. template<> struct TypedArrayTypeTraits<float> { static const JsTypedArrayType cTypedArrayType = JsTypedArrayType::JsArrayTypeFloat32; };
  1967. template<> struct TypedArrayTypeTraits<double> { static const JsTypedArrayType cTypedArrayType = JsTypedArrayType::JsArrayTypeFloat64; };
  1968. template <class T, bool clamped = false>
  1969. Js::ArrayObject* CreateTypedArray(Js::ScriptContext *scriptContext, void* data, unsigned int length)
  1970. {
  1971. Js::JavascriptLibrary* library = scriptContext->GetLibrary();
  1972. Js::ArrayBufferBase* arrayBuffer = RecyclerNew(
  1973. scriptContext->GetRecycler(),
  1974. Js::ExternalArrayBuffer,
  1975. reinterpret_cast<BYTE*>(data),
  1976. length * sizeof(T),
  1977. library->GetArrayBufferType());
  1978. return static_cast<Js::ArrayObject*>(Js::TypedArray<T, clamped>::Create(arrayBuffer, 0, length, library));
  1979. }
  1980. template <class T, bool clamped = false>
  1981. void GetObjectArrayData(Js::ArrayObject* objectArray, void** data, JsTypedArrayType* arrayType, uint* length)
  1982. {
  1983. Js::TypedArray<T, clamped>* typedArray = Js::TypedArray<T, clamped>::FromVar(objectArray);
  1984. *data = typedArray->GetArrayBuffer()->GetBuffer();
  1985. *arrayType = TypedArrayTypeTraits<T, clamped>::cTypedArrayType;
  1986. *length = typedArray->GetLength();
  1987. }
  1988. CHAKRA_API JsSetIndexedPropertiesToExternalData(
  1989. _In_ JsValueRef object,
  1990. _In_ void* data,
  1991. _In_ JsTypedArrayType arrayType,
  1992. _In_ unsigned int elementLength)
  1993. {
  1994. return ContextAPIWrapper<JSRT_MAYBE_TRUE>([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  1995. PERFORM_JSRT_TTD_RECORD_ACTION_NOT_IMPLEMENTED(scriptContext);
  1996. VALIDATE_INCOMING_OBJECT(object, scriptContext);
  1997. // Don't support doing this on array or array-like object
  1998. Js::TypeId typeId = Js::JavascriptOperators::GetTypeId(object);
  1999. if (!Js::DynamicType::Is(typeId)
  2000. || Js::DynamicObject::IsAnyArrayTypeId(typeId)
  2001. || (typeId >= Js::TypeIds_TypedArrayMin && typeId <= Js::TypeIds_TypedArrayMax)
  2002. || typeId == Js::TypeIds_ArrayBuffer
  2003. || typeId == Js::TypeIds_DataView
  2004. || Js::RecyclableObject::FromVar(object)->IsExternal()
  2005. )
  2006. {
  2007. return JsErrorInvalidArgument;
  2008. }
  2009. if (data == nullptr && elementLength > 0)
  2010. {
  2011. return JsErrorInvalidArgument;
  2012. }
  2013. Js::ArrayObject* newTypedArray = nullptr;
  2014. switch (arrayType)
  2015. {
  2016. case JsArrayTypeInt8:
  2017. newTypedArray = CreateTypedArray<int8>(scriptContext, data, elementLength);
  2018. break;
  2019. case JsArrayTypeUint8:
  2020. newTypedArray = CreateTypedArray<uint8>(scriptContext, data, elementLength);
  2021. break;
  2022. case JsArrayTypeUint8Clamped:
  2023. newTypedArray = CreateTypedArray<uint8, true>(scriptContext, data, elementLength);
  2024. break;
  2025. case JsArrayTypeInt16:
  2026. newTypedArray = CreateTypedArray<int16>(scriptContext, data, elementLength);
  2027. break;
  2028. case JsArrayTypeUint16:
  2029. newTypedArray = CreateTypedArray<uint16>(scriptContext, data, elementLength);
  2030. break;
  2031. case JsArrayTypeInt32:
  2032. newTypedArray = CreateTypedArray<int32>(scriptContext, data, elementLength);
  2033. break;
  2034. case JsArrayTypeUint32:
  2035. newTypedArray = CreateTypedArray<uint32>(scriptContext, data, elementLength);
  2036. break;
  2037. case JsArrayTypeFloat32:
  2038. newTypedArray = CreateTypedArray<float>(scriptContext, data, elementLength);
  2039. break;
  2040. case JsArrayTypeFloat64:
  2041. newTypedArray = CreateTypedArray<double>(scriptContext, data, elementLength);
  2042. break;
  2043. default:
  2044. return JsErrorInvalidArgument;
  2045. }
  2046. Js::DynamicObject* dynamicObject = Js::DynamicObject::FromVar(object);
  2047. dynamicObject->SetObjectArray(newTypedArray);
  2048. return JsNoError;
  2049. });
  2050. }
  2051. CHAKRA_API JsHasIndexedPropertiesExternalData(_In_ JsValueRef object, _Out_ bool *value)
  2052. {
  2053. VALIDATE_JSREF(object);
  2054. PARAM_NOT_NULL(value);
  2055. BEGIN_JSRT_NO_EXCEPTION
  2056. {
  2057. *value = false;
  2058. if (Js::DynamicType::Is(Js::JavascriptOperators::GetTypeId(object)))
  2059. {
  2060. Js::DynamicObject* dynamicObject = Js::DynamicObject::UnsafeFromVar(object);
  2061. Js::ArrayObject* objectArray = dynamicObject->GetObjectArray();
  2062. *value = (objectArray && !Js::DynamicObject::IsAnyArray(objectArray));
  2063. }
  2064. }
  2065. END_JSRT_NO_EXCEPTION
  2066. }
  2067. CHAKRA_API JsGetIndexedPropertiesExternalData(
  2068. _In_ JsValueRef object,
  2069. _Out_ void** buffer,
  2070. _Out_ JsTypedArrayType* arrayType,
  2071. _Out_ unsigned int* elementLength)
  2072. {
  2073. VALIDATE_JSREF(object);
  2074. PARAM_NOT_NULL(buffer);
  2075. PARAM_NOT_NULL(arrayType);
  2076. PARAM_NOT_NULL(elementLength);
  2077. BEGIN_JSRT_NO_EXCEPTION
  2078. {
  2079. if (!Js::DynamicType::Is(Js::JavascriptOperators::GetTypeId(object)))
  2080. {
  2081. RETURN_NO_EXCEPTION(JsErrorInvalidArgument);
  2082. }
  2083. *buffer = nullptr;
  2084. *arrayType = JsTypedArrayType();
  2085. *elementLength = 0;
  2086. Js::DynamicObject* dynamicObject = Js::DynamicObject::UnsafeFromVar(object);
  2087. Js::ArrayObject* objectArray = dynamicObject->GetObjectArray();
  2088. if (!objectArray)
  2089. {
  2090. RETURN_NO_EXCEPTION(JsErrorInvalidArgument);
  2091. }
  2092. switch (Js::JavascriptOperators::GetTypeId(objectArray))
  2093. {
  2094. case Js::TypeIds_Int8Array:
  2095. GetObjectArrayData<int8>(objectArray, buffer, arrayType, elementLength);
  2096. break;
  2097. case Js::TypeIds_Uint8Array:
  2098. GetObjectArrayData<uint8>(objectArray, buffer, arrayType, elementLength);
  2099. break;
  2100. case Js::TypeIds_Uint8ClampedArray:
  2101. GetObjectArrayData<uint8, true>(objectArray, buffer, arrayType, elementLength);
  2102. break;
  2103. case Js::TypeIds_Int16Array:
  2104. GetObjectArrayData<int16>(objectArray, buffer, arrayType, elementLength);
  2105. break;
  2106. case Js::TypeIds_Uint16Array:
  2107. GetObjectArrayData<uint16>(objectArray, buffer, arrayType, elementLength);
  2108. break;
  2109. case Js::TypeIds_Int32Array:
  2110. GetObjectArrayData<int32>(objectArray, buffer, arrayType, elementLength);
  2111. break;
  2112. case Js::TypeIds_Uint32Array:
  2113. GetObjectArrayData<uint32>(objectArray, buffer, arrayType, elementLength);
  2114. break;
  2115. case Js::TypeIds_Float32Array:
  2116. GetObjectArrayData<float>(objectArray, buffer, arrayType, elementLength);
  2117. break;
  2118. case Js::TypeIds_Float64Array:
  2119. GetObjectArrayData<double>(objectArray, buffer, arrayType, elementLength);
  2120. break;
  2121. default:
  2122. RETURN_NO_EXCEPTION(JsErrorInvalidArgument);
  2123. }
  2124. }
  2125. END_JSRT_NO_EXCEPTION
  2126. }
  2127. CHAKRA_API JsLessThan(_In_ JsValueRef object1, _In_ JsValueRef object2, _Out_ bool *result)
  2128. {
  2129. return ContextAPIWrapper<JSRT_MAYBE_TRUE>([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  2130. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTLessThan, object1, object2, false);
  2131. VALIDATE_INCOMING_REFERENCE(object1, scriptContext);
  2132. VALIDATE_INCOMING_REFERENCE(object2, scriptContext);
  2133. PARAM_NOT_NULL(result);
  2134. *result = Js::JavascriptOperators::Less((Js::Var)object1, (Js::Var)object2, scriptContext) != 0;
  2135. return JsNoError;
  2136. });
  2137. }
  2138. CHAKRA_API JsLessThanOrEqual(_In_ JsValueRef object1, _In_ JsValueRef object2, _Out_ bool *result)
  2139. {
  2140. return ContextAPIWrapper<JSRT_MAYBE_TRUE>([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  2141. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTLessThan, object1, object2, true);
  2142. VALIDATE_INCOMING_REFERENCE(object1, scriptContext);
  2143. VALIDATE_INCOMING_REFERENCE(object2, scriptContext);
  2144. PARAM_NOT_NULL(result);
  2145. *result = Js::JavascriptOperators::LessEqual((Js::Var)object1, (Js::Var)object2, scriptContext) != 0;
  2146. return JsNoError;
  2147. });
  2148. }
  2149. CHAKRA_API JsEquals(_In_ JsValueRef object1, _In_ JsValueRef object2, _Out_ bool *result)
  2150. {
  2151. return ContextAPIWrapper<JSRT_MAYBE_TRUE>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  2152. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTEquals, object1, object2, false);
  2153. VALIDATE_INCOMING_REFERENCE(object1, scriptContext);
  2154. VALIDATE_INCOMING_REFERENCE(object2, scriptContext);
  2155. PARAM_NOT_NULL(result);
  2156. *result = Js::JavascriptOperators::Equal((Js::Var)object1, (Js::Var)object2, scriptContext) != 0;
  2157. return JsNoError;
  2158. });
  2159. }
  2160. CHAKRA_API JsStrictEquals(_In_ JsValueRef object1, _In_ JsValueRef object2, _Out_ bool *result)
  2161. {
  2162. return ContextAPIWrapper<JSRT_MAYBE_TRUE>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  2163. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTEquals, object1, object2, true);
  2164. VALIDATE_INCOMING_REFERENCE(object1, scriptContext);
  2165. VALIDATE_INCOMING_REFERENCE(object2, scriptContext);
  2166. PARAM_NOT_NULL(result);
  2167. *result = Js::JavascriptOperators::StrictEqual((Js::Var)object1, (Js::Var)object2, scriptContext) != 0;
  2168. return JsNoError;
  2169. });
  2170. }
  2171. CHAKRA_API JsHasExternalData(_In_ JsValueRef object, _Out_ bool *value)
  2172. {
  2173. VALIDATE_JSREF(object);
  2174. PARAM_NOT_NULL(value);
  2175. BEGIN_JSRT_NO_EXCEPTION
  2176. {
  2177. *value = JsrtExternalObject::Is(object);
  2178. }
  2179. END_JSRT_NO_EXCEPTION
  2180. }
  2181. CHAKRA_API JsGetExternalData(_In_ JsValueRef object, _Out_ void **data)
  2182. {
  2183. VALIDATE_JSREF(object);
  2184. PARAM_NOT_NULL(data);
  2185. BEGIN_JSRT_NO_EXCEPTION
  2186. {
  2187. if (JsrtExternalObject::Is(object))
  2188. {
  2189. *data = JsrtExternalObject::FromVar(object)->GetSlotData();
  2190. }
  2191. else
  2192. {
  2193. *data = nullptr;
  2194. RETURN_NO_EXCEPTION(JsErrorInvalidArgument);
  2195. }
  2196. }
  2197. END_JSRT_NO_EXCEPTION
  2198. }
  2199. CHAKRA_API JsSetExternalData(_In_ JsValueRef object, _In_opt_ void *data)
  2200. {
  2201. VALIDATE_JSREF(object);
  2202. BEGIN_JSRT_NO_EXCEPTION
  2203. {
  2204. if (JsrtExternalObject::Is(object))
  2205. {
  2206. JsrtExternalObject::FromVar(object)->SetSlotData(data);
  2207. }
  2208. else
  2209. {
  2210. RETURN_NO_EXCEPTION(JsErrorInvalidArgument);
  2211. }
  2212. }
  2213. END_JSRT_NO_EXCEPTION
  2214. }
  2215. CHAKRA_API JsCallFunction(_In_ JsValueRef function, _In_reads_(cargs) JsValueRef *args, _In_ ushort cargs, _Out_opt_ JsValueRef *result)
  2216. {
  2217. if(result != nullptr)
  2218. {
  2219. *result = nullptr;
  2220. }
  2221. return ContextAPIWrapper<JSRT_MAYBE_TRUE>([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  2222. #if ENABLE_TTD
  2223. TTD::TTDJsRTFunctionCallActionPopperRecorder callInfoPopper;
  2224. if(PERFORM_JSRT_TTD_RECORD_ACTION_CHECK(scriptContext))
  2225. {
  2226. TTD::NSLogEvents::EventLogEntry* callEvent = scriptContext->GetThreadContext()->TTDLog->RecordJsRTCallFunction(_actionEntryPopper, scriptContext->GetThreadContext()->TTDRootNestingCount, function, cargs, args);
  2227. callInfoPopper.InitializeForRecording(scriptContext, scriptContext->GetThreadContext()->TTDLog->GetCurrentWallTime(), callEvent);
  2228. if(scriptContext->GetThreadContext()->TTDRootNestingCount == 0)
  2229. {
  2230. TTD::EventLog* elog = scriptContext->GetThreadContext()->TTDLog;
  2231. elog->ResetCallStackForTopLevelCall(elog->GetLastEventTime());
  2232. TTD::ExecutionInfoManager* emanager = scriptContext->GetThreadContext()->TTDExecutionInfo;
  2233. if(emanager != nullptr)
  2234. {
  2235. emanager->ResetCallStackForTopLevelCall(elog->GetLastEventTime());
  2236. }
  2237. }
  2238. }
  2239. #endif
  2240. VALIDATE_INCOMING_FUNCTION(function, scriptContext);
  2241. if(cargs == 0 || args == nullptr)
  2242. {
  2243. return JsErrorInvalidArgument;
  2244. }
  2245. for(int index = 0; index < cargs; index++)
  2246. {
  2247. VALIDATE_INCOMING_REFERENCE(args[index], scriptContext);
  2248. }
  2249. Js::JavascriptFunction *jsFunction = Js::JavascriptFunction::FromVar(function);
  2250. Js::CallInfo callInfo(cargs);
  2251. Js::Arguments jsArgs(callInfo, reinterpret_cast<Js::Var *>(args));
  2252. Js::Var varResult = jsFunction->CallRootFunction(jsArgs, scriptContext, true);
  2253. if(result != nullptr)
  2254. {
  2255. *result = varResult;
  2256. Assert(*result == nullptr || !Js::CrossSite::NeedMarshalVar(*result, scriptContext));
  2257. }
  2258. #if ENABLE_TTD
  2259. if(PERFORM_JSRT_TTD_RECORD_ACTION_CHECK(scriptContext))
  2260. {
  2261. _actionEntryPopper.SetResult(result);
  2262. }
  2263. #endif
  2264. return JsNoError;
  2265. });
  2266. }
  2267. CHAKRA_API JsConstructObject(_In_ JsValueRef function, _In_reads_(cargs) JsValueRef *args, _In_ ushort cargs, _Out_ JsValueRef *result)
  2268. {
  2269. return ContextAPIWrapper<JSRT_MAYBE_TRUE>([&] (Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  2270. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTConstructCall, function, cargs, args);
  2271. VALIDATE_INCOMING_FUNCTION(function, scriptContext);
  2272. PARAM_NOT_NULL(result);
  2273. *result = nullptr;
  2274. if (cargs == 0 || args == nullptr)
  2275. {
  2276. return JsErrorInvalidArgument;
  2277. }
  2278. for (int index = 0; index < cargs; index++)
  2279. {
  2280. VALIDATE_INCOMING_REFERENCE(args[index], scriptContext);
  2281. }
  2282. Js::JavascriptFunction *jsFunction = Js::JavascriptFunction::FromVar(function);
  2283. Js::CallInfo callInfo(Js::CallFlags::CallFlags_New, cargs);
  2284. Js::Arguments jsArgs(callInfo, reinterpret_cast<Js::Var *>(args));
  2285. //
  2286. //TODO: we will want to look at this at some point -- either treat as "top-level" call or maybe constructors are fast so we can just jump back to previous "real" code
  2287. //TTDAssert(!Js::ScriptFunction::Is(jsFunction) || execContext->GetThreadContext()->TTDRootNestingCount != 0, "This will cause user code to execute and we need to add support for that as a top-level call source!!!!");
  2288. //
  2289. *result = Js::JavascriptFunction::CallAsConstructor(jsFunction, /* overridingNewTarget = */nullptr, jsArgs, scriptContext);
  2290. Assert(*result == nullptr || !Js::CrossSite::NeedMarshalVar(*result, scriptContext));
  2291. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, result);
  2292. return JsNoError;
  2293. });
  2294. }
  2295. #ifndef _CHAKRACOREBUILD
  2296. typedef struct JsNativeFunctionInfo
  2297. {
  2298. JsValueRef thisArg;
  2299. JsValueRef newTargetArg;
  2300. bool isConstructCall;
  2301. }JsNativeFunctionInfo;
  2302. typedef _Ret_maybenull_ JsValueRef(CHAKRA_CALLBACK * JsEnhancedNativeFunction)(_In_ JsValueRef callee, _In_ JsValueRef *arguments, _In_ unsigned short argumentCount, _In_ JsNativeFunctionInfo *info, _In_opt_ void *callbackState);
  2303. #endif
  2304. typedef struct JsNativeFunctionWrapperHolder
  2305. {
  2306. FieldNoBarrier(void *) callbackState;
  2307. FieldNoBarrier(JsNativeFunction) nativeFunction;
  2308. }JsNativeFunctionWrapperHolder;
  2309. JsValueRef CALLBACK JsNativeFunctionWrapper(JsValueRef callee, JsValueRef *arguments, unsigned short argumentCount, JsNativeFunctionInfo *info, void *wrapperData)
  2310. {
  2311. JsNativeFunctionWrapperHolder *wrapperHolder = static_cast<JsNativeFunctionWrapperHolder*>(wrapperData);
  2312. JsValueRef result = wrapperHolder->nativeFunction(callee, info->isConstructCall, arguments, argumentCount, wrapperHolder->callbackState);
  2313. return result;
  2314. }
  2315. template <bool wrapNativeFunction, class T>
  2316. JsErrorCode JsCreateEnhancedFunctionHelper(_In_ T nativeFunction, _In_opt_ JsValueRef metadata, _In_opt_ void *callbackState, _Out_ JsValueRef *function)
  2317. {
  2318. return ContextAPIWrapper<JSRT_MAYBE_TRUE>([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  2319. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTAllocateFunction, metadata);
  2320. PARAM_NOT_NULL(nativeFunction);
  2321. PARAM_NOT_NULL(function);
  2322. *function = nullptr;
  2323. Js::StdCallJavascriptMethod method;
  2324. if (wrapNativeFunction)
  2325. {
  2326. JsNativeFunctionWrapperHolder *wrapperHolder = RecyclerNewStruct(scriptContext->GetRecycler(), JsNativeFunctionWrapperHolder);
  2327. wrapperHolder->callbackState = callbackState;
  2328. wrapperHolder->nativeFunction = (JsNativeFunction)nativeFunction;
  2329. callbackState = wrapperHolder;
  2330. method = (Js::StdCallJavascriptMethod)JsNativeFunctionWrapper;
  2331. }
  2332. else
  2333. {
  2334. method = (Js::StdCallJavascriptMethod)nativeFunction;
  2335. }
  2336. if (metadata != JS_INVALID_REFERENCE)
  2337. {
  2338. VALIDATE_INCOMING_REFERENCE(metadata, scriptContext);
  2339. metadata = Js::JavascriptConversion::ToString(metadata, scriptContext);
  2340. }
  2341. else
  2342. {
  2343. metadata = scriptContext->GetLibrary()->GetEmptyString();
  2344. }
  2345. Js::JavascriptExternalFunction *externalFunction = scriptContext->GetLibrary()->CreateStdCallExternalFunction(method, metadata, callbackState);
  2346. *function = (JsValueRef)externalFunction;
  2347. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, function);
  2348. return JsNoError;
  2349. });
  2350. }
  2351. CHAKRA_API JsCreateEnhancedFunction(_In_ JsEnhancedNativeFunction nativeFunction, _In_opt_ JsValueRef metadata, _In_opt_ void *callbackState, _Out_ JsValueRef *function)
  2352. {
  2353. return JsCreateEnhancedFunctionHelper<false>(nativeFunction, metadata, callbackState, function);
  2354. }
  2355. CHAKRA_API JsCreateFunction(_In_ JsNativeFunction nativeFunction, _In_opt_ void *callbackState, _Out_ JsValueRef *function)
  2356. {
  2357. return JsCreateEnhancedFunctionHelper<true>(nativeFunction, JS_INVALID_REFERENCE, callbackState, function);
  2358. }
  2359. CHAKRA_API JsCreateNamedFunction(_In_ JsValueRef name, _In_ JsNativeFunction nativeFunction, _In_opt_ void *callbackState, _Out_ JsValueRef *function)
  2360. {
  2361. return JsCreateEnhancedFunctionHelper<true>(nativeFunction, name, callbackState, function);
  2362. }
  2363. void SetErrorMessage(Js::ScriptContext *scriptContext, Js::JavascriptError *newError, JsValueRef message)
  2364. {
  2365. // ECMA262 #sec-error-message
  2366. if (!Js::JavascriptOperators::IsUndefined(message))
  2367. {
  2368. Js::JavascriptString *messageStr = nullptr;
  2369. if (Js::JavascriptString::Is(message))
  2370. {
  2371. messageStr = Js::JavascriptString::FromVar(message);
  2372. }
  2373. else
  2374. {
  2375. messageStr = Js::JavascriptConversion::ToString(message, scriptContext);
  2376. }
  2377. Js::PropertyDescriptor desc;
  2378. desc.SetValue(messageStr);
  2379. desc.SetWritable(true);
  2380. desc.SetEnumerable(false);
  2381. desc.SetConfigurable(true);
  2382. Js::JavascriptOperators::SetPropertyDescriptor(newError, Js::PropertyIds::message, desc);
  2383. }
  2384. }
  2385. CHAKRA_API JsCreateError(_In_ JsValueRef message, _Out_ JsValueRef *error)
  2386. {
  2387. return ContextAPIWrapper<JSRT_MAYBE_TRUE>([&] (Js::ScriptContext * scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  2388. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTCreateError, message);
  2389. VALIDATE_INCOMING_REFERENCE(message, scriptContext);
  2390. PARAM_NOT_NULL(error);
  2391. *error = nullptr;
  2392. Js::JavascriptError *newError = scriptContext->GetLibrary()->CreateError();
  2393. SetErrorMessage(scriptContext, newError, message);
  2394. *error = newError;
  2395. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, error);
  2396. return JsNoError;
  2397. });
  2398. }
  2399. CHAKRA_API JsCreateRangeError(_In_ JsValueRef message, _Out_ JsValueRef *error)
  2400. {
  2401. return ContextAPIWrapper<JSRT_MAYBE_TRUE>([&] (Js::ScriptContext * scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  2402. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTCreateRangeError, message);
  2403. VALIDATE_INCOMING_REFERENCE(message, scriptContext);
  2404. PARAM_NOT_NULL(error);
  2405. *error = nullptr;
  2406. Js::JavascriptError *newError = scriptContext->GetLibrary()->CreateRangeError();
  2407. SetErrorMessage(scriptContext, newError, message);
  2408. *error = newError;
  2409. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, error);
  2410. return JsNoError;
  2411. });
  2412. }
  2413. CHAKRA_API JsCreateReferenceError(_In_ JsValueRef message, _Out_ JsValueRef *error)
  2414. {
  2415. return ContextAPIWrapper<JSRT_MAYBE_TRUE>([&] (Js::ScriptContext * scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  2416. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTCreateReferenceError, message);
  2417. VALIDATE_INCOMING_REFERENCE(message, scriptContext);
  2418. PARAM_NOT_NULL(error);
  2419. *error = nullptr;
  2420. Js::JavascriptError *newError = scriptContext->GetLibrary()->CreateReferenceError();
  2421. SetErrorMessage(scriptContext, newError, message);
  2422. *error = newError;
  2423. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, error);
  2424. return JsNoError;
  2425. });
  2426. }
  2427. CHAKRA_API JsCreateSyntaxError(_In_ JsValueRef message, _Out_ JsValueRef *error)
  2428. {
  2429. return ContextAPIWrapper<JSRT_MAYBE_TRUE>([&] (Js::ScriptContext * scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  2430. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTCreateSyntaxError, message);
  2431. VALIDATE_INCOMING_REFERENCE(message, scriptContext);
  2432. PARAM_NOT_NULL(error);
  2433. *error = nullptr;
  2434. Js::JavascriptError *newError = scriptContext->GetLibrary()->CreateSyntaxError();
  2435. SetErrorMessage(scriptContext, newError, message);
  2436. *error = newError;
  2437. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, error);
  2438. return JsNoError;
  2439. });
  2440. }
  2441. CHAKRA_API JsCreateTypeError(_In_ JsValueRef message, _Out_ JsValueRef *error)
  2442. {
  2443. return ContextAPIWrapper<JSRT_MAYBE_TRUE>([&] (Js::ScriptContext * scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  2444. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTCreateTypeError, message);
  2445. VALIDATE_INCOMING_REFERENCE(message, scriptContext);
  2446. PARAM_NOT_NULL(error);
  2447. *error = nullptr;
  2448. Js::JavascriptError *newError = scriptContext->GetLibrary()->CreateTypeError();
  2449. SetErrorMessage(scriptContext, newError, message);
  2450. *error = newError;
  2451. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, error);
  2452. return JsNoError;
  2453. });
  2454. }
  2455. CHAKRA_API JsCreateURIError(_In_ JsValueRef message, _Out_ JsValueRef *error)
  2456. {
  2457. return ContextAPIWrapper<JSRT_MAYBE_TRUE>([&] (Js::ScriptContext * scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  2458. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTCreateURIError, message);
  2459. VALIDATE_INCOMING_REFERENCE(message, scriptContext);
  2460. PARAM_NOT_NULL(error);
  2461. *error = nullptr;
  2462. Js::JavascriptError *newError = scriptContext->GetLibrary()->CreateURIError();
  2463. SetErrorMessage(scriptContext, newError, message);
  2464. *error = newError;
  2465. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, error);
  2466. return JsNoError;
  2467. });
  2468. }
  2469. CHAKRA_API JsHasException(_Out_ bool *hasException)
  2470. {
  2471. PARAM_NOT_NULL(hasException);
  2472. *hasException = false;
  2473. JsrtContext *currentContext = JsrtContext::GetCurrent();
  2474. if (currentContext == nullptr)
  2475. {
  2476. return JsErrorNoCurrentContext;
  2477. }
  2478. Js::ScriptContext *scriptContext = currentContext->GetScriptContext();
  2479. Assert(scriptContext != nullptr);
  2480. Recycler *recycler = scriptContext->GetRecycler();
  2481. ThreadContext *threadContext = scriptContext->GetThreadContext();
  2482. #ifndef JSRT_VERIFY_RUNTIME_STATE
  2483. if (recycler && recycler->IsInObjectBeforeCollectCallback())
  2484. {
  2485. return JsErrorInObjectBeforeCollectCallback;
  2486. }
  2487. #endif
  2488. if (recycler && recycler->IsHeapEnumInProgress())
  2489. {
  2490. return JsErrorHeapEnumInProgress;
  2491. }
  2492. else if (threadContext->IsInThreadServiceCallback())
  2493. {
  2494. return JsErrorInThreadServiceCallback;
  2495. }
  2496. if (threadContext->IsExecutionDisabled())
  2497. {
  2498. return JsErrorInDisabledState;
  2499. }
  2500. *hasException = scriptContext->HasRecordedException();
  2501. return JsNoError;
  2502. }
  2503. CHAKRA_API JsGetAndClearException(_Out_ JsValueRef *exception)
  2504. {
  2505. PARAM_NOT_NULL(exception);
  2506. *exception = nullptr;
  2507. JsrtContext *currentContext = JsrtContext::GetCurrent();
  2508. if (currentContext == nullptr)
  2509. {
  2510. return JsErrorNoCurrentContext;
  2511. }
  2512. Js::ScriptContext *scriptContext = currentContext->GetScriptContext();
  2513. Assert(scriptContext != nullptr);
  2514. if (scriptContext->GetRecycler() && scriptContext->GetRecycler()->IsHeapEnumInProgress())
  2515. {
  2516. return JsErrorHeapEnumInProgress;
  2517. }
  2518. else if (scriptContext->GetThreadContext()->IsInThreadServiceCallback())
  2519. {
  2520. return JsErrorInThreadServiceCallback;
  2521. }
  2522. if (scriptContext->GetThreadContext()->IsExecutionDisabled())
  2523. {
  2524. return JsErrorInDisabledState;
  2525. }
  2526. HRESULT hr = S_OK;
  2527. Js::JavascriptExceptionObject *recordedException = nullptr;
  2528. BEGIN_TRANSLATE_OOM_TO_HRESULT
  2529. if (scriptContext->HasRecordedException())
  2530. {
  2531. recordedException = scriptContext->GetAndClearRecordedException();
  2532. }
  2533. END_TRANSLATE_OOM_TO_HRESULT(hr)
  2534. if (hr == E_OUTOFMEMORY)
  2535. {
  2536. recordedException = scriptContext->GetThreadContext()->GetRecordedException();
  2537. }
  2538. if (recordedException == nullptr)
  2539. {
  2540. return JsErrorInvalidArgument;
  2541. }
  2542. *exception = recordedException->GetThrownObject(nullptr);
  2543. #if ENABLE_TTD
  2544. if(hr != E_OUTOFMEMORY)
  2545. {
  2546. TTD::TTDJsRTActionResultAutoRecorder _actionEntryPopper;
  2547. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTGetAndClearException);
  2548. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, exception);
  2549. }
  2550. #endif
  2551. if (*exception == nullptr)
  2552. {
  2553. return JsErrorInvalidArgument;
  2554. }
  2555. return JsNoError;
  2556. }
  2557. CHAKRA_API JsSetException(_In_ JsValueRef exception)
  2558. {
  2559. return ContextAPINoScriptWrapper([&](Js::ScriptContext* scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  2560. JsrtContext * context = JsrtContext::GetCurrent();
  2561. JsrtRuntime * runtime = context->GetRuntime();
  2562. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTSetException, exception, runtime->DispatchExceptions());
  2563. VALIDATE_INCOMING_REFERENCE(exception, scriptContext);
  2564. Js::JavascriptExceptionObject *exceptionObject;
  2565. exceptionObject = RecyclerNew(scriptContext->GetRecycler(), Js::JavascriptExceptionObject, exception, scriptContext, nullptr);
  2566. scriptContext->RecordException(exceptionObject, runtime->DispatchExceptions());
  2567. return JsNoError;
  2568. });
  2569. }
  2570. CHAKRA_API JsGetRuntimeMemoryUsage(_In_ JsRuntimeHandle runtimeHandle, _Out_ size_t * memoryUsage)
  2571. {
  2572. VALIDATE_INCOMING_RUNTIME_HANDLE(runtimeHandle);
  2573. PARAM_NOT_NULL(memoryUsage);
  2574. *memoryUsage = 0;
  2575. ThreadContext * threadContext = JsrtRuntime::FromHandle(runtimeHandle)->GetThreadContext();
  2576. AllocationPolicyManager * allocPolicyManager = threadContext->GetAllocationPolicyManager();
  2577. *memoryUsage = allocPolicyManager->GetUsage();
  2578. return JsNoError;
  2579. }
  2580. CHAKRA_API JsSetRuntimeMemoryLimit(_In_ JsRuntimeHandle runtimeHandle, _In_ size_t memoryLimit)
  2581. {
  2582. VALIDATE_INCOMING_RUNTIME_HANDLE(runtimeHandle);
  2583. ThreadContext * threadContext = JsrtRuntime::FromHandle(runtimeHandle)->GetThreadContext();
  2584. AllocationPolicyManager * allocPolicyManager = threadContext->GetAllocationPolicyManager();
  2585. allocPolicyManager->SetLimit(memoryLimit);
  2586. return JsNoError;
  2587. }
  2588. CHAKRA_API JsGetRuntimeMemoryLimit(_In_ JsRuntimeHandle runtimeHandle, _Out_ size_t * memoryLimit)
  2589. {
  2590. VALIDATE_INCOMING_RUNTIME_HANDLE(runtimeHandle);
  2591. PARAM_NOT_NULL(memoryLimit);
  2592. *memoryLimit = 0;
  2593. ThreadContext * threadContext = JsrtRuntime::FromHandle(runtimeHandle)->GetThreadContext();
  2594. AllocationPolicyManager * allocPolicyManager = threadContext->GetAllocationPolicyManager();
  2595. *memoryLimit = allocPolicyManager->GetLimit();
  2596. return JsNoError;
  2597. }
  2598. C_ASSERT(JsMemoryAllocate == (_JsMemoryEventType) AllocationPolicyManager::MemoryAllocateEvent::MemoryAllocate);
  2599. C_ASSERT(JsMemoryFree == (_JsMemoryEventType) AllocationPolicyManager::MemoryAllocateEvent::MemoryFree);
  2600. C_ASSERT(JsMemoryFailure == (_JsMemoryEventType) AllocationPolicyManager::MemoryAllocateEvent::MemoryFailure);
  2601. C_ASSERT(JsMemoryFailure == (_JsMemoryEventType) AllocationPolicyManager::MemoryAllocateEvent::MemoryMax);
  2602. CHAKRA_API JsSetRuntimeMemoryAllocationCallback(_In_ JsRuntimeHandle runtime, _In_opt_ void *callbackState, _In_ JsMemoryAllocationCallback allocationCallback)
  2603. {
  2604. VALIDATE_INCOMING_RUNTIME_HANDLE(runtime);
  2605. ThreadContext* threadContext = JsrtRuntime::FromHandle(runtime)->GetThreadContext();
  2606. AllocationPolicyManager * allocPolicyManager = threadContext->GetAllocationPolicyManager();
  2607. allocPolicyManager->SetMemoryAllocationCallback(callbackState, (AllocationPolicyManager::PageAllocatorMemoryAllocationCallback)allocationCallback);
  2608. return JsNoError;
  2609. }
  2610. CHAKRA_API JsSetRuntimeBeforeCollectCallback(_In_ JsRuntimeHandle runtime, _In_opt_ void *callbackState, _In_ JsBeforeCollectCallback beforeCollectCallback)
  2611. {
  2612. return GlobalAPIWrapper_NoRecord([&]() -> JsErrorCode {
  2613. VALIDATE_INCOMING_RUNTIME_HANDLE(runtime);
  2614. JsrtRuntime::FromHandle(runtime)->SetBeforeCollectCallback(beforeCollectCallback, callbackState);
  2615. return JsNoError;
  2616. });
  2617. }
  2618. CHAKRA_API JsDisableRuntimeExecution(_In_ JsRuntimeHandle runtimeHandle)
  2619. {
  2620. VALIDATE_INCOMING_RUNTIME_HANDLE(runtimeHandle);
  2621. ThreadContext * threadContext = JsrtRuntime::FromHandle(runtimeHandle)->GetThreadContext();
  2622. if (!threadContext->TestThreadContextFlag(ThreadContextFlagCanDisableExecution))
  2623. {
  2624. return JsErrorCannotDisableExecution;
  2625. }
  2626. if (threadContext->GetRecycler() && threadContext->GetRecycler()->IsHeapEnumInProgress())
  2627. {
  2628. return JsErrorHeapEnumInProgress;
  2629. }
  2630. else if (threadContext->IsInThreadServiceCallback())
  2631. {
  2632. return JsErrorInThreadServiceCallback;
  2633. }
  2634. threadContext->DisableExecution();
  2635. return JsNoError;
  2636. }
  2637. CHAKRA_API JsEnableRuntimeExecution(_In_ JsRuntimeHandle runtimeHandle)
  2638. {
  2639. return GlobalAPIWrapper_NoRecord([&] () -> JsErrorCode {
  2640. VALIDATE_INCOMING_RUNTIME_HANDLE(runtimeHandle);
  2641. ThreadContext * threadContext = JsrtRuntime::FromHandle(runtimeHandle)->GetThreadContext();
  2642. if (!threadContext->TestThreadContextFlag(ThreadContextFlagCanDisableExecution))
  2643. {
  2644. return JsNoError;
  2645. }
  2646. if (threadContext->GetRecycler() && threadContext->GetRecycler()->IsHeapEnumInProgress())
  2647. {
  2648. return JsErrorHeapEnumInProgress;
  2649. }
  2650. else if (threadContext->IsInThreadServiceCallback())
  2651. {
  2652. return JsErrorInThreadServiceCallback;
  2653. }
  2654. ThreadContextScope scope(threadContext);
  2655. if (!scope.IsValid())
  2656. {
  2657. return JsErrorWrongThread;
  2658. }
  2659. threadContext->EnableExecution();
  2660. return JsNoError;
  2661. });
  2662. }
  2663. CHAKRA_API JsIsRuntimeExecutionDisabled(_In_ JsRuntimeHandle runtimeHandle, _Out_ bool *isDisabled)
  2664. {
  2665. VALIDATE_INCOMING_RUNTIME_HANDLE(runtimeHandle);
  2666. PARAM_NOT_NULL(isDisabled);
  2667. *isDisabled = false;
  2668. ThreadContext* threadContext = JsrtRuntime::FromHandle(runtimeHandle)->GetThreadContext();
  2669. *isDisabled = threadContext->IsExecutionDisabled();
  2670. return JsNoError;
  2671. }
  2672. inline JsErrorCode JsGetPropertyIdFromNameInternal(_In_z_ const WCHAR *name, size_t cPropertyNameLength, _Out_ JsPropertyIdRef *propertyId)
  2673. {
  2674. return ContextAPINoScriptWrapper_NoRecord([&](Js::ScriptContext * scriptContext) -> JsErrorCode {
  2675. PARAM_NOT_NULL(name);
  2676. PARAM_NOT_NULL(propertyId);
  2677. *propertyId = nullptr;
  2678. if (cPropertyNameLength <= INT_MAX)
  2679. {
  2680. scriptContext->GetOrAddPropertyRecord(name, static_cast<int>(cPropertyNameLength), (Js::PropertyRecord const **)propertyId);
  2681. return JsNoError;
  2682. }
  2683. else
  2684. {
  2685. return JsErrorOutOfMemory;
  2686. }
  2687. });
  2688. }
  2689. CHAKRA_API JsGetPropertyIdFromName(_In_z_ const WCHAR *name, _Out_ JsPropertyIdRef *propertyId)
  2690. {
  2691. return JsGetPropertyIdFromNameInternal(name, wcslen(name), propertyId);
  2692. }
  2693. CHAKRA_API JsGetPropertyIdFromSymbol(_In_ JsValueRef symbol, _Out_ JsPropertyIdRef *propertyId)
  2694. {
  2695. return ContextAPINoScriptWrapper([&](Js::ScriptContext * scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  2696. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTGetPropertyIdFromSymbol, symbol);
  2697. VALIDATE_INCOMING_REFERENCE(symbol, scriptContext);
  2698. PARAM_NOT_NULL(propertyId);
  2699. *propertyId = nullptr;
  2700. if (!Js::JavascriptSymbol::Is(symbol))
  2701. {
  2702. return JsErrorPropertyNotSymbol;
  2703. }
  2704. *propertyId = (JsPropertyIdRef)Js::JavascriptSymbol::FromVar(symbol)->GetValue();
  2705. return JsNoError;
  2706. },
  2707. /*allowInObjectBeforeCollectCallback*/true);
  2708. }
  2709. CHAKRA_API JsGetSymbolFromPropertyId(_In_ JsPropertyIdRef propertyId, _Out_ JsValueRef *symbol)
  2710. {
  2711. return ContextAPINoScriptWrapper([&](Js::ScriptContext * scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  2712. PERFORM_JSRT_TTD_RECORD_ACTION_NOT_IMPLEMENTED(scriptContext);
  2713. VALIDATE_INCOMING_PROPERTYID(propertyId);
  2714. PARAM_NOT_NULL(symbol);
  2715. *symbol = nullptr;
  2716. Js::PropertyRecord const * propertyRecord = (Js::PropertyRecord const *)propertyId;
  2717. if (!propertyRecord->IsSymbol())
  2718. {
  2719. return JsErrorPropertyNotSymbol;
  2720. }
  2721. *symbol = scriptContext->GetLibrary()->CreateSymbol(propertyRecord);
  2722. return JsNoError;
  2723. });
  2724. }
  2725. #pragma prefast(suppress:6101, "Prefast doesn't see through the lambda")
  2726. CHAKRA_API JsGetPropertyNameFromId(_In_ JsPropertyIdRef propertyId, _Outptr_result_z_ const WCHAR **name)
  2727. {
  2728. return GlobalAPIWrapper_NoRecord([&]() -> JsErrorCode {
  2729. VALIDATE_INCOMING_PROPERTYID(propertyId);
  2730. PARAM_NOT_NULL(name);
  2731. *name = nullptr;
  2732. Js::PropertyRecord const * propertyRecord = (Js::PropertyRecord const *)propertyId;
  2733. if (propertyRecord->IsSymbol())
  2734. {
  2735. return JsErrorPropertyNotString;
  2736. }
  2737. *name = propertyRecord->GetBuffer();
  2738. return JsNoError;
  2739. });
  2740. }
  2741. CHAKRA_API JsGetPropertyIdType(_In_ JsPropertyIdRef propertyId, _Out_ JsPropertyIdType* propertyIdType)
  2742. {
  2743. return GlobalAPIWrapper_NoRecord([&]() -> JsErrorCode {
  2744. VALIDATE_INCOMING_PROPERTYID(propertyId);
  2745. Js::PropertyRecord const * propertyRecord = (Js::PropertyRecord const *)propertyId;
  2746. if (propertyRecord->IsSymbol())
  2747. {
  2748. *propertyIdType = JsPropertyIdTypeSymbol;
  2749. }
  2750. else
  2751. {
  2752. *propertyIdType = JsPropertyIdTypeString;
  2753. }
  2754. return JsNoError;
  2755. });
  2756. }
  2757. CHAKRA_API JsGetRuntime(_In_ JsContextRef context, _Out_ JsRuntimeHandle *runtime)
  2758. {
  2759. VALIDATE_JSREF(context);
  2760. PARAM_NOT_NULL(runtime);
  2761. *runtime = nullptr;
  2762. if (!JsrtContext::Is(context))
  2763. {
  2764. return JsErrorInvalidArgument;
  2765. }
  2766. *runtime = static_cast<JsrtContext *>(context)->GetRuntime();
  2767. return JsNoError;
  2768. }
  2769. CHAKRA_API JsIdle(_Out_opt_ unsigned int *nextIdleTick)
  2770. {
  2771. PARAM_NOT_NULL(nextIdleTick);
  2772. return ContextAPINoScriptWrapper_NoRecord([&] (Js::ScriptContext * scriptContext) -> JsErrorCode {
  2773. *nextIdleTick = 0;
  2774. if (scriptContext->GetThreadContext()->GetRecycler() && scriptContext->GetThreadContext()->GetRecycler()->IsHeapEnumInProgress())
  2775. {
  2776. return JsErrorHeapEnumInProgress;
  2777. }
  2778. else if (scriptContext->GetThreadContext()->IsInThreadServiceCallback())
  2779. {
  2780. return JsErrorInThreadServiceCallback;
  2781. }
  2782. JsrtContext * context = JsrtContext::GetCurrent();
  2783. JsrtRuntime * runtime = context->GetRuntime();
  2784. if (!runtime->UseIdle())
  2785. {
  2786. return JsErrorIdleNotEnabled;
  2787. }
  2788. unsigned int ticks = runtime->Idle();
  2789. *nextIdleTick = ticks;
  2790. return JsNoError;
  2791. });
  2792. }
  2793. CHAKRA_API JsSetPromiseContinuationCallback(_In_opt_ JsPromiseContinuationCallback promiseContinuationCallback, _In_opt_ void *callbackState)
  2794. {
  2795. return ContextAPINoScriptWrapper_NoRecord([&](Js::ScriptContext *scriptContext) -> JsErrorCode {
  2796. scriptContext->GetLibrary()->SetNativeHostPromiseContinuationFunction((Js::JavascriptLibrary::PromiseContinuationCallback) promiseContinuationCallback, callbackState);
  2797. return JsNoError;
  2798. },
  2799. /*allowInObjectBeforeCollectCallback*/true);
  2800. }
  2801. JsErrorCode RunScriptCore(JsValueRef scriptSource, const byte *script, size_t cb,
  2802. LoadScriptFlag loadScriptFlag, JsSourceContext sourceContext,
  2803. const WCHAR *sourceUrl, bool parseOnly, JsParseScriptAttributes parseAttributes,
  2804. bool isSourceModule, JsValueRef *result)
  2805. {
  2806. Js::JavascriptFunction *scriptFunction;
  2807. CompileScriptException se;
  2808. JsErrorCode errorCode = ContextAPINoScriptWrapper([&](Js::ScriptContext * scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  2809. PARAM_NOT_NULL(script);
  2810. PARAM_NOT_NULL(sourceUrl);
  2811. SourceContextInfo * sourceContextInfo = scriptContext->GetSourceContextInfo(sourceContext, nullptr);
  2812. if (sourceContextInfo == nullptr)
  2813. {
  2814. sourceContextInfo = scriptContext->CreateSourceContextInfo(sourceContext, sourceUrl, wcslen(sourceUrl), nullptr);
  2815. }
  2816. const int chsize = (loadScriptFlag & LoadScriptFlag_Utf8Source) ?
  2817. sizeof(utf8char_t) : sizeof(WCHAR);
  2818. SRCINFO si = {
  2819. /* sourceContextInfo */ sourceContextInfo,
  2820. /* dlnHost */ 0,
  2821. /* ulColumnHost */ 0,
  2822. /* lnMinHost */ 0,
  2823. /* ichMinHost */ 0,
  2824. /* ichLimHost */ static_cast<ULONG>(cb / chsize), // OK to truncate since this is used to limit sourceText in debugDocument/compilation errors.
  2825. /* ulCharOffset */ 0,
  2826. /* mod */ kmodGlobal,
  2827. /* grfsi */ 0
  2828. };
  2829. Js::Utf8SourceInfo* utf8SourceInfo = nullptr;
  2830. if (result != nullptr)
  2831. {
  2832. loadScriptFlag = (LoadScriptFlag)(loadScriptFlag | LoadScriptFlag_Expression);
  2833. }
  2834. bool isLibraryCode = (parseAttributes & JsParseScriptAttributeLibraryCode) == JsParseScriptAttributeLibraryCode;
  2835. if (isLibraryCode)
  2836. {
  2837. loadScriptFlag = (LoadScriptFlag)(loadScriptFlag | LoadScriptFlag_LibraryCode);
  2838. }
  2839. if (isSourceModule)
  2840. {
  2841. loadScriptFlag = (LoadScriptFlag)(loadScriptFlag | LoadScriptFlag_Module);
  2842. }
  2843. #if ENABLE_TTD
  2844. TTD::NSLogEvents::EventLogEntry* parseEvent = nullptr;
  2845. if(PERFORM_JSRT_TTD_RECORD_ACTION_CHECK(scriptContext))
  2846. {
  2847. parseEvent = scriptContext->GetThreadContext()->TTDLog->RecordJsRTCodeParse(_actionEntryPopper,
  2848. loadScriptFlag, ((loadScriptFlag & LoadScriptFlag_Utf8Source) == LoadScriptFlag_Utf8Source),
  2849. script, (uint32)cb, sourceContext, sourceUrl);
  2850. }
  2851. #endif
  2852. scriptFunction = scriptContext->LoadScript(script, cb,
  2853. &si, &se, &utf8SourceInfo,
  2854. Js::Constants::GlobalCode, loadScriptFlag, scriptSource);
  2855. #if ENABLE_TTD
  2856. if(PERFORM_JSRT_TTD_RECORD_ACTION_CHECK(scriptContext))
  2857. {
  2858. _actionEntryPopper.SetResult((Js::Var*)&scriptFunction);
  2859. }
  2860. //
  2861. //TODO: We may (probably?) want to use the debugger source rundown functionality here instead
  2862. //
  2863. if (scriptFunction != nullptr && scriptContext->IsTTDRecordModeEnabled())
  2864. {
  2865. //Make sure we have the body and text information available
  2866. Js::FunctionBody* globalBody = TTD::JsSupport::ForceAndGetFunctionBody(scriptFunction->GetParseableFunctionInfo());
  2867. const TTD::NSSnapValues::TopLevelScriptLoadFunctionBodyResolveInfo* tbfi = scriptContext->GetThreadContext()->TTDLog->AddScriptLoad(globalBody, kmodGlobal, sourceContext, script, (uint32)cb, loadScriptFlag);
  2868. if(parseEvent != nullptr)
  2869. {
  2870. TTD::NSLogEvents::JsRTCodeParseAction_SetBodyCtrId(parseEvent, tbfi->TopLevelBase.TopLevelBodyCtr);
  2871. }
  2872. //walk global body to (1) add functions to pin set (2) build parent map
  2873. BEGIN_JS_RUNTIME_CALL(scriptContext);
  2874. {
  2875. scriptContext->TTDContextInfo->ProcessFunctionBodyOnLoad(globalBody, nullptr);
  2876. scriptContext->TTDContextInfo->RegisterLoadedScript(globalBody, tbfi->TopLevelBase.TopLevelBodyCtr);
  2877. }
  2878. END_JS_RUNTIME_CALL(scriptContext);
  2879. }
  2880. #endif
  2881. JsrtContext * context = JsrtContext::GetCurrent();
  2882. context->OnScriptLoad(scriptFunction, utf8SourceInfo, &se);
  2883. return JsNoError;
  2884. });
  2885. if (errorCode != JsNoError)
  2886. {
  2887. return errorCode;
  2888. }
  2889. return ContextAPIWrapper<false>([&](Js::ScriptContext* scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  2890. if (scriptFunction == nullptr)
  2891. {
  2892. PERFORM_JSRT_TTD_RECORD_ACTION_NOT_IMPLEMENTED(scriptContext);
  2893. HandleScriptCompileError(scriptContext, &se, sourceUrl);
  2894. return JsErrorScriptCompile;
  2895. }
  2896. if (parseOnly)
  2897. {
  2898. PARAM_NOT_NULL(result);
  2899. *result = scriptFunction;
  2900. }
  2901. else
  2902. {
  2903. Js::Arguments args(0, nullptr);
  2904. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  2905. Js::Var varThis;
  2906. if (PHASE_FORCE1(Js::EvalCompilePhase))
  2907. {
  2908. varThis = Js::JavascriptOperators::OP_GetThis(scriptContext->GetLibrary()->GetUndefined(), kmodGlobal, scriptContext);
  2909. args.Info.Flags = (Js::CallFlags)Js::CallFlags::CallFlags_Eval;
  2910. args.Info.Count = 1;
  2911. args.Values = &varThis;
  2912. }
  2913. #endif
  2914. #if ENABLE_TTD
  2915. TTD::TTDJsRTFunctionCallActionPopperRecorder callInfoPopper;
  2916. if(PERFORM_JSRT_TTD_RECORD_ACTION_CHECK(scriptContext))
  2917. {
  2918. TTD::NSLogEvents::EventLogEntry* callEvent = scriptContext->GetThreadContext()->TTDLog->RecordJsRTCallFunction(_actionEntryPopper, scriptContext->GetThreadContext()->TTDRootNestingCount, scriptFunction, args.Info.Count, args.Values);
  2919. callInfoPopper.InitializeForRecording(scriptContext, scriptContext->GetThreadContext()->TTDLog->GetCurrentWallTime(), callEvent);
  2920. if(scriptContext->GetThreadContext()->TTDRootNestingCount == 0)
  2921. {
  2922. TTD::EventLog* elog = scriptContext->GetThreadContext()->TTDLog;
  2923. elog->ResetCallStackForTopLevelCall(elog->GetLastEventTime());
  2924. TTD::ExecutionInfoManager* emanager = scriptContext->GetThreadContext()->TTDExecutionInfo;
  2925. if(emanager != nullptr)
  2926. {
  2927. emanager->ResetCallStackForTopLevelCall(elog->GetLastEventTime());
  2928. }
  2929. }
  2930. }
  2931. #endif
  2932. Js::Var varResult = scriptFunction->CallRootFunction(args, scriptContext, true);
  2933. if (result != nullptr)
  2934. {
  2935. *result = varResult;
  2936. }
  2937. #if ENABLE_TTD
  2938. if(PERFORM_JSRT_TTD_RECORD_ACTION_CHECK(scriptContext))
  2939. {
  2940. _actionEntryPopper.SetResult(result);
  2941. }
  2942. #endif
  2943. }
  2944. return JsNoError;
  2945. });
  2946. }
  2947. JsErrorCode RunScriptCore(const char *script, JsSourceContext sourceContext,
  2948. const char *sourceUrl, bool parseOnly, JsParseScriptAttributes parseAttributes,
  2949. bool isSourceModule, JsValueRef *result)
  2950. {
  2951. utf8::NarrowToWide url((LPCSTR)sourceUrl);
  2952. if (!url)
  2953. {
  2954. return JsErrorOutOfMemory;
  2955. }
  2956. return RunScriptCore(nullptr, reinterpret_cast<const byte*>(script), strlen(script),
  2957. LoadScriptFlag_Utf8Source, sourceContext, url, parseOnly, parseAttributes,
  2958. isSourceModule, result);
  2959. }
  2960. JsErrorCode RunScriptCore(const WCHAR *script, JsSourceContext sourceContext,
  2961. const WCHAR *sourceUrl, bool parseOnly, JsParseScriptAttributes parseAttributes,
  2962. bool isSourceModule, JsValueRef *result)
  2963. {
  2964. return RunScriptCore(nullptr, reinterpret_cast<const byte*>(script),
  2965. wcslen(script) * sizeof(WCHAR),
  2966. LoadScriptFlag_None, sourceContext, sourceUrl, parseOnly,
  2967. parseAttributes, isSourceModule, result);
  2968. }
  2969. #ifdef _WIN32
  2970. CHAKRA_API JsParseScript(_In_z_ const WCHAR * script, _In_ JsSourceContext sourceContext,
  2971. _In_z_ const WCHAR *sourceUrl, _Out_ JsValueRef * result)
  2972. {
  2973. return RunScriptCore(script, sourceContext, sourceUrl, true,
  2974. JsParseScriptAttributeNone, false /*isModule*/, result);
  2975. }
  2976. CHAKRA_API JsParseScriptWithAttributes(
  2977. _In_z_ const WCHAR *script,
  2978. _In_ JsSourceContext sourceContext,
  2979. _In_z_ const WCHAR *sourceUrl,
  2980. _In_ JsParseScriptAttributes parseAttributes,
  2981. _Out_ JsValueRef *result)
  2982. {
  2983. return RunScriptCore(script, sourceContext, sourceUrl, true,
  2984. parseAttributes, false /*isModule*/, result);
  2985. }
  2986. CHAKRA_API JsRunScript(_In_z_ const WCHAR * script, _In_ JsSourceContext sourceContext,
  2987. _In_z_ const WCHAR *sourceUrl, _Out_ JsValueRef * result)
  2988. {
  2989. return RunScriptCore(script, sourceContext, sourceUrl, false,
  2990. JsParseScriptAttributeNone, false /*isModule*/, result);
  2991. }
  2992. CHAKRA_API JsExperimentalApiRunModule(_In_z_ const WCHAR * script,
  2993. _In_ JsSourceContext sourceContext, _In_z_ const WCHAR *sourceUrl,
  2994. _Out_ JsValueRef * result)
  2995. {
  2996. return RunScriptCore(script, sourceContext, sourceUrl, false,
  2997. JsParseScriptAttributeNone, true, result);
  2998. }
  2999. #endif
  3000. JsErrorCode JsSerializeScriptCore(const byte *script, size_t cb,
  3001. LoadScriptFlag loadScriptFlag, BYTE *functionTable, int functionTableSize,
  3002. unsigned char *buffer, unsigned int *bufferSize, JsValueRef scriptSource)
  3003. {
  3004. Js::JavascriptFunction *function;
  3005. CompileScriptException se;
  3006. JsErrorCode errorCode = ContextAPINoScriptWrapper_NoRecord([&](Js::ScriptContext *scriptContext) -> JsErrorCode {
  3007. PARAM_NOT_NULL(script);
  3008. PARAM_NOT_NULL(bufferSize);
  3009. if (*bufferSize > 0)
  3010. {
  3011. PARAM_NOT_NULL(buffer);
  3012. ZeroMemory(buffer, *bufferSize);
  3013. }
  3014. if (scriptContext->IsScriptContextInDebugMode())
  3015. {
  3016. return JsErrorCannotSerializeDebugScript;
  3017. }
  3018. SourceContextInfo * sourceContextInfo = scriptContext->GetSourceContextInfo(JS_SOURCE_CONTEXT_NONE, nullptr);
  3019. Assert(sourceContextInfo != nullptr);
  3020. const int chsize = (loadScriptFlag & LoadScriptFlag_Utf8Source) ? sizeof(utf8char_t) : sizeof(WCHAR);
  3021. SRCINFO si = {
  3022. /* sourceContextInfo */ sourceContextInfo,
  3023. /* dlnHost */ 0,
  3024. /* ulColumnHost */ 0,
  3025. /* lnMinHost */ 0,
  3026. /* ichMinHost */ 0,
  3027. /* ichLimHost */ static_cast<ULONG>(cb / chsize), // OK to truncate since this is used to limit sourceText in debugDocument/compilation errors.
  3028. /* ulCharOffset */ 0,
  3029. /* mod */ kmodGlobal,
  3030. /* grfsi */ 0
  3031. };
  3032. bool isSerializeByteCodeForLibrary = false;
  3033. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  3034. isSerializeByteCodeForLibrary = JsrtContext::GetCurrent()->GetRuntime()->IsSerializeByteCodeForLibrary();
  3035. #endif
  3036. Js::Utf8SourceInfo* sourceInfo = nullptr;
  3037. loadScriptFlag = (LoadScriptFlag)(loadScriptFlag | LoadScriptFlag_disableDeferredParse);
  3038. if (isSerializeByteCodeForLibrary)
  3039. {
  3040. loadScriptFlag = (LoadScriptFlag)(loadScriptFlag | LoadScriptFlag_isByteCodeBufferForLibrary);
  3041. }
  3042. else
  3043. {
  3044. loadScriptFlag = (LoadScriptFlag)(loadScriptFlag | LoadScriptFlag_Expression);
  3045. }
  3046. function = scriptContext->LoadScript(script, cb, &si, &se, &sourceInfo,
  3047. Js::Constants::GlobalCode, loadScriptFlag, scriptSource);
  3048. return JsNoError;
  3049. });
  3050. if (errorCode != JsNoError)
  3051. {
  3052. return errorCode;
  3053. }
  3054. return ContextAPIWrapper_NoRecord<false>([&](Js::ScriptContext* scriptContext) -> JsErrorCode {
  3055. if (function == nullptr)
  3056. {
  3057. HandleScriptCompileError(scriptContext, &se);
  3058. return JsErrorScriptCompile;
  3059. }
  3060. // Could we have a deserialized function in this case?
  3061. // If we are going to serialize it, a check isn't to expensive
  3062. if (CONFIG_FLAG(ForceSerialized) && function->GetFunctionProxy() != nullptr) {
  3063. function->GetFunctionProxy()->EnsureDeserialized();
  3064. }
  3065. Js::FunctionBody *functionBody = function->GetFunctionBody();
  3066. const Js::Utf8SourceInfo *sourceInfo = functionBody->GetUtf8SourceInfo();
  3067. size_t cSourceCodeLength = sourceInfo->GetCbLength(_u("JsSerializeScript"));
  3068. // truncation of code length can lead to accessing random memory. Reject the call.
  3069. if (cSourceCodeLength > DWORD_MAX)
  3070. {
  3071. return JsErrorOutOfMemory;
  3072. }
  3073. LPCUTF8 utf8Code = sourceInfo->GetSource(_u("JsSerializeScript"));
  3074. DWORD dwFlags = 0;
  3075. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  3076. dwFlags = JsrtContext::GetCurrent()->GetRuntime()->IsSerializeByteCodeForLibrary() ? GENERATE_BYTE_CODE_BUFFER_LIBRARY : 0;
  3077. #endif
  3078. BEGIN_TEMP_ALLOCATOR(tempAllocator, scriptContext, _u("ByteCodeSerializer"));
  3079. // We cast buffer size to DWORD* because on Windows, DWORD = unsigned long = unsigned int
  3080. // On 64-bit clang on linux, this is not true, unsigned long is larger than unsigned int
  3081. // However, the PAL defines DWORD for us on linux as unsigned int so the cast is safe here.
  3082. HRESULT hr = Js::ByteCodeSerializer::SerializeToBuffer(scriptContext,
  3083. tempAllocator, static_cast<DWORD>(cSourceCodeLength), utf8Code,
  3084. functionBody, functionBody->GetHostSrcInfo(), false, &buffer,
  3085. (DWORD*) bufferSize, dwFlags);
  3086. END_TEMP_ALLOCATOR(tempAllocator, scriptContext);
  3087. if (SUCCEEDED(hr))
  3088. {
  3089. return JsNoError;
  3090. }
  3091. else
  3092. {
  3093. return JsErrorScriptCompile;
  3094. }
  3095. });
  3096. }
  3097. CHAKRA_API JsSerializeScript(_In_z_ const WCHAR *script, _Out_writes_to_opt_(*bufferSize,
  3098. *bufferSize) unsigned char *buffer,
  3099. _Inout_ unsigned int *bufferSize)
  3100. {
  3101. return JsSerializeScriptCore((const byte*)script, wcslen(script) * sizeof(WCHAR),
  3102. LoadScriptFlag_None, nullptr, 0, buffer, bufferSize, nullptr);
  3103. }
  3104. template <typename TLoadCallback, typename TUnloadCallback>
  3105. JsErrorCode RunSerializedScriptCore(
  3106. TLoadCallback scriptLoadCallback, TUnloadCallback scriptUnloadCallback,
  3107. JsSourceContext scriptLoadSourceContext, // only used by scriptLoadCallback
  3108. unsigned char *buffer, JsValueRef bufferVal,
  3109. JsSourceContext sourceContext, const WCHAR *sourceUrl,
  3110. bool parseOnly, JsValueRef *result)
  3111. {
  3112. Js::JavascriptFunction *function;
  3113. JsErrorCode errorCode = ContextAPINoScriptWrapper_NoRecord([&](Js::ScriptContext *scriptContext) -> JsErrorCode {
  3114. if (result != nullptr)
  3115. {
  3116. *result = nullptr;
  3117. }
  3118. PARAM_NOT_NULL(buffer);
  3119. PARAM_NOT_NULL(sourceUrl);
  3120. Js::ISourceHolder *sourceHolder = nullptr;
  3121. PARAM_NOT_NULL(scriptLoadCallback);
  3122. PARAM_NOT_NULL(scriptUnloadCallback);
  3123. typedef Js::JsrtSourceHolder<TLoadCallback, TUnloadCallback> TSourceHolder;
  3124. sourceHolder = RecyclerNewFinalized(scriptContext->GetRecycler(), TSourceHolder,
  3125. scriptLoadCallback, scriptUnloadCallback, scriptLoadSourceContext, bufferVal);
  3126. SourceContextInfo *sourceContextInfo;
  3127. SRCINFO *hsi;
  3128. Field(Js::FunctionBody*) functionBody = nullptr;
  3129. HRESULT hr;
  3130. sourceContextInfo = scriptContext->GetSourceContextInfo(sourceContext, nullptr);
  3131. if (sourceContextInfo == nullptr)
  3132. {
  3133. sourceContextInfo = scriptContext->CreateSourceContextInfo(sourceContext, sourceUrl,
  3134. wcslen(sourceUrl), nullptr);
  3135. }
  3136. SRCINFO si = {
  3137. /* sourceContextInfo */ sourceContextInfo,
  3138. /* dlnHost */ 0,
  3139. /* ulColumnHost */ 0,
  3140. /* lnMinHost */ 0,
  3141. /* ichMinHost */ 0,
  3142. /* ichLimHost */ 0, // xplat-todo: need to compute this?
  3143. /* ulCharOffset */ 0,
  3144. /* mod */ kmodGlobal,
  3145. /* grfsi */ 0
  3146. };
  3147. uint32 flags = 0;
  3148. if (CONFIG_FLAG(CreateFunctionProxy) && !scriptContext->IsProfiling())
  3149. {
  3150. flags = fscrAllowFunctionProxy;
  3151. }
  3152. hsi = scriptContext->AddHostSrcInfo(&si);
  3153. hr = Js::ByteCodeSerializer::DeserializeFromBuffer(scriptContext, flags, sourceHolder,
  3154. hsi, buffer, nullptr, &functionBody);
  3155. if (FAILED(hr))
  3156. {
  3157. return JsErrorBadSerializedScript;
  3158. }
  3159. function = scriptContext->GetLibrary()->CreateScriptFunction(functionBody);
  3160. JsrtContext * context = JsrtContext::GetCurrent();
  3161. context->OnScriptLoad(function, functionBody->GetUtf8SourceInfo(), nullptr);
  3162. return JsNoError;
  3163. });
  3164. if (errorCode != JsNoError)
  3165. {
  3166. return errorCode;
  3167. }
  3168. return ContextAPIWrapper_NoRecord<false>([&](Js::ScriptContext* scriptContext) -> JsErrorCode {
  3169. if (parseOnly)
  3170. {
  3171. PARAM_NOT_NULL(result);
  3172. *result = function;
  3173. }
  3174. else
  3175. {
  3176. Js::Var varResult = function->CallRootFunction(Js::Arguments(0, nullptr), scriptContext, true);
  3177. if (result != nullptr)
  3178. {
  3179. *result = varResult;
  3180. }
  3181. }
  3182. return JsNoError;
  3183. });
  3184. }
  3185. static void CHAKRA_CALLBACK DummyScriptUnloadCallback(_In_ JsSourceContext sourceContext)
  3186. {
  3187. // Do nothing
  3188. }
  3189. #ifdef _WIN32
  3190. static bool CHAKRA_CALLBACK DummyScriptLoadSourceCallback(_In_ JsSourceContext sourceContext, _Outptr_result_z_ const WCHAR** scriptBuffer)
  3191. {
  3192. // sourceContext is actually the script source pointer
  3193. *scriptBuffer = reinterpret_cast<const WCHAR*>(sourceContext);
  3194. return true;
  3195. }
  3196. CHAKRA_API JsParseSerializedScript(_In_z_ const WCHAR * script, _In_ unsigned char *buffer,
  3197. _In_ JsSourceContext sourceContext,
  3198. _In_z_ const WCHAR *sourceUrl,
  3199. _Out_ JsValueRef * result)
  3200. {
  3201. return RunSerializedScriptCore(
  3202. DummyScriptLoadSourceCallback, DummyScriptUnloadCallback,
  3203. reinterpret_cast<JsSourceContext>(script), // use script source pointer as scriptLoadSourceContext
  3204. buffer, nullptr, sourceContext, sourceUrl, true, result);
  3205. }
  3206. CHAKRA_API JsRunSerializedScript(_In_z_ const WCHAR * script, _In_ unsigned char *buffer,
  3207. _In_ JsSourceContext sourceContext,
  3208. _In_z_ const WCHAR *sourceUrl,
  3209. _Out_ JsValueRef * result)
  3210. {
  3211. return RunSerializedScriptCore(
  3212. DummyScriptLoadSourceCallback, DummyScriptUnloadCallback,
  3213. reinterpret_cast<JsSourceContext>(script), // use script source pointer as scriptLoadSourceContext
  3214. buffer, nullptr, sourceContext, sourceUrl, false, result);
  3215. }
  3216. CHAKRA_API JsParseSerializedScriptWithCallback(_In_ JsSerializedScriptLoadSourceCallback scriptLoadCallback,
  3217. _In_ JsSerializedScriptUnloadCallback scriptUnloadCallback,
  3218. _In_ unsigned char *buffer, _In_ JsSourceContext sourceContext,
  3219. _In_z_ const WCHAR *sourceUrl, _Out_ JsValueRef * result)
  3220. {
  3221. return RunSerializedScriptCore(
  3222. scriptLoadCallback, scriptUnloadCallback,
  3223. sourceContext, // use the same user provided sourceContext as scriptLoadSourceContext
  3224. buffer, nullptr, sourceContext, sourceUrl, true, result);
  3225. }
  3226. CHAKRA_API JsRunSerializedScriptWithCallback(_In_ JsSerializedScriptLoadSourceCallback scriptLoadCallback,
  3227. _In_ JsSerializedScriptUnloadCallback scriptUnloadCallback,
  3228. _In_ unsigned char *buffer, _In_ JsSourceContext sourceContext,
  3229. _In_z_ const WCHAR *sourceUrl, _Out_opt_ JsValueRef * result)
  3230. {
  3231. return RunSerializedScriptCore(
  3232. scriptLoadCallback, scriptUnloadCallback,
  3233. sourceContext, // use the same user provided sourceContext as scriptLoadSourceContext
  3234. buffer, nullptr, sourceContext, sourceUrl, false, result);
  3235. }
  3236. #endif // _WIN32
  3237. /////////////////////
  3238. CHAKRA_API JsTTDCreateRecordRuntime(_In_ JsRuntimeAttributes attributes, _In_ bool enableDebugging, _In_ size_t snapInterval, _In_ size_t snapHistoryLength,
  3239. _In_ TTDOpenResourceStreamCallback openResourceStream, _In_ JsTTDWriteBytesToStreamCallback writeBytesToStream, _In_ JsTTDFlushAndCloseStreamCallback flushAndCloseStream,
  3240. _In_opt_ JsThreadServiceCallback threadService, _Out_ JsRuntimeHandle *runtime)
  3241. {
  3242. #if !ENABLE_TTD
  3243. return JsErrorCategoryUsage;
  3244. #else
  3245. if(snapInterval > UINT32_MAX || snapHistoryLength > UINT32_MAX)
  3246. {
  3247. return JsErrorInvalidArgument;
  3248. }
  3249. return CreateRuntimeCore(attributes, nullptr, 0, true, false, enableDebugging, (uint32)snapInterval, (uint32)snapHistoryLength,
  3250. openResourceStream, nullptr, writeBytesToStream, flushAndCloseStream,
  3251. threadService, runtime);
  3252. #endif
  3253. }
  3254. CHAKRA_API JsTTDCreateReplayRuntime(_In_ JsRuntimeAttributes attributes, _In_reads_(infoUriCount) const char* infoUri, _In_ size_t infoUriCount, _In_ bool enableDebugging,
  3255. _In_ TTDOpenResourceStreamCallback openResourceStream, _In_ JsTTDReadBytesFromStreamCallback readBytesFromStream, _In_ JsTTDFlushAndCloseStreamCallback flushAndCloseStream,
  3256. _In_opt_ JsThreadServiceCallback threadService, _Out_ JsRuntimeHandle *runtime)
  3257. {
  3258. #if !ENABLE_TTD
  3259. return JsErrorCategoryUsage;
  3260. #else
  3261. return CreateRuntimeCore(attributes, infoUri, infoUriCount, false, true, enableDebugging, UINT_MAX, UINT_MAX,
  3262. openResourceStream, readBytesFromStream, nullptr, flushAndCloseStream,
  3263. threadService, runtime);
  3264. #endif
  3265. }
  3266. CHAKRA_API JsTTDCreateContext(_In_ JsRuntimeHandle runtimeHandle, _In_ bool useRuntimeTTDMode, _Out_ JsContextRef *newContext)
  3267. {
  3268. #if !ENABLE_TTD
  3269. return JsErrorCategoryUsage;
  3270. #else
  3271. return GlobalAPIWrapper_NoRecord([&]() -> JsErrorCode {
  3272. PARAM_NOT_NULL(newContext);
  3273. VALIDATE_INCOMING_RUNTIME_HANDLE(runtimeHandle);
  3274. JsrtRuntime * runtime = JsrtRuntime::FromHandle(runtimeHandle);
  3275. ThreadContext * threadContext = runtime->GetThreadContext();
  3276. TTDAssert(threadContext->IsRuntimeInTTDMode(), "Need to create in TTD Mode.");
  3277. bool inRecord = false;
  3278. bool activelyRecording = false;
  3279. bool inReplay = false;
  3280. TTDRecorder dummyActionEntryPopper;
  3281. if(useRuntimeTTDMode)
  3282. {
  3283. threadContext->TTDLog->GetModesForExplicitContextCreate(inRecord, activelyRecording, inReplay);
  3284. }
  3285. return CreateContextCore(runtimeHandle, dummyActionEntryPopper, inRecord, activelyRecording, inReplay, newContext);
  3286. });
  3287. #endif
  3288. }
  3289. CHAKRA_API JsTTDNotifyContextDestroy(_In_ JsContextRef context)
  3290. {
  3291. #if !ENABLE_TTD
  3292. return JsErrorCategoryUsage;
  3293. #else
  3294. ThreadContext* threadContext = ThreadContext::GetContextForCurrentThread();
  3295. if(threadContext && threadContext->IsRuntimeInTTDMode())
  3296. {
  3297. Js::ScriptContext* ctx = static_cast<JsrtContext*>(context)->GetScriptContext();
  3298. threadContext->TTDContext->NotifyCtxDestroyInRecord(ctx);
  3299. }
  3300. return JsNoError;
  3301. #endif
  3302. }
  3303. CHAKRA_API JsTTDStart()
  3304. {
  3305. #if !ENABLE_TTD
  3306. return JsErrorCategoryUsage;
  3307. #else
  3308. JsrtContext *currentContext = JsrtContext::GetCurrent();
  3309. JsErrorCode cCheck = CheckContext(currentContext, JSRT_MAYBE_TRUE);
  3310. TTDAssert(cCheck == JsNoError, "Must have valid context when starting TTD.");
  3311. Js::ScriptContext* scriptContext = currentContext->GetScriptContext();
  3312. TTDAssert(scriptContext->IsTTDRecordOrReplayModeEnabled(), "Need to create in TTD Record Mode.");
  3313. #if ENABLE_NATIVE_CODEGEN
  3314. TTDAssert(JITManager::GetJITManager() == nullptr || !JITManager::GetJITManager()->IsOOPJITEnabled(), "TTD cannot run with OOP JIT yet!!!");
  3315. #endif
  3316. return GlobalAPIWrapper_NoRecord([&]() -> JsErrorCode
  3317. {
  3318. if(scriptContext->IsTTDRecordModeEnabled())
  3319. {
  3320. scriptContext->GetThreadContext()->TTDLog->DoSnapshotExtract();
  3321. }
  3322. //Want to verify that we are at top-level of dispatch
  3323. scriptContext->GetThreadContext()->TTDLog->PushMode(TTD::TTDMode::CurrentlyEnabled);
  3324. return JsNoError;
  3325. });
  3326. #endif
  3327. }
  3328. CHAKRA_API JsTTDStop()
  3329. {
  3330. #if !ENABLE_TTD
  3331. return JsErrorCategoryUsage;
  3332. #else
  3333. JsrtContext *currentContext = JsrtContext::GetCurrent();
  3334. JsErrorCode cCheck = CheckContext(currentContext, JSRT_MAYBE_TRUE);
  3335. TTDAssert(cCheck == JsNoError, "Must have valid context when starting TTD.");
  3336. Js::ScriptContext* scriptContext = currentContext->GetScriptContext();
  3337. TTDAssert(scriptContext->IsTTDRecordOrReplayModeEnabled(), "Need to create in TTD mode.");
  3338. return GlobalAPIWrapper_NoRecord([&]() -> JsErrorCode
  3339. {
  3340. scriptContext->GetThreadContext()->TTDLog->PopMode(TTD::TTDMode::CurrentlyEnabled);
  3341. if(scriptContext->IsTTDRecordModeEnabled())
  3342. {
  3343. scriptContext->GetThreadContext()->TTDLog->UnloadAllLogData();
  3344. }
  3345. return JsNoError;
  3346. });
  3347. #endif
  3348. }
  3349. CHAKRA_API JsTTDPauseTimeTravelBeforeRuntimeOperation()
  3350. {
  3351. #if !ENABLE_TTD
  3352. return JsErrorCategoryUsage;
  3353. #else
  3354. JsrtContext *currentContext = JsrtContext::GetCurrent();
  3355. JsErrorCode cCheck = CheckContext(currentContext, JSRT_MAYBE_TRUE);
  3356. TTDAssert(cCheck == JsNoError, "Must have valid context when changing debugger mode.");
  3357. Js::ScriptContext* scriptContext = currentContext->GetScriptContext();
  3358. ThreadContext* threadContext = scriptContext->GetThreadContext();
  3359. if(threadContext->IsRuntimeInTTDMode())
  3360. {
  3361. threadContext->TTDLog->PushMode(TTD::TTDMode::ExcludedExecutionDebuggerAction);
  3362. }
  3363. return JsNoError;
  3364. #endif
  3365. }
  3366. CHAKRA_API JsTTDReStartTimeTravelAfterRuntimeOperation()
  3367. {
  3368. #if !ENABLE_TTD
  3369. return JsErrorCategoryUsage;
  3370. #else
  3371. JsrtContext *currentContext = JsrtContext::GetCurrent();
  3372. JsErrorCode cCheck = CheckContext(currentContext, JSRT_MAYBE_TRUE);
  3373. TTDAssert(cCheck == JsNoError, "Must have valid context when changing debugger mode.");
  3374. Js::ScriptContext* scriptContext = currentContext->GetScriptContext();
  3375. ThreadContext* threadContext = scriptContext->GetThreadContext();
  3376. if(threadContext->IsRuntimeInTTDMode())
  3377. {
  3378. threadContext->TTDLog->PopMode(TTD::TTDMode::ExcludedExecutionDebuggerAction);
  3379. }
  3380. return JsNoError;
  3381. #endif
  3382. }
  3383. CHAKRA_API JsTTDNotifyYield()
  3384. {
  3385. #if !ENABLE_TTD
  3386. return JsErrorCategoryUsage;
  3387. #else
  3388. JsrtContext *currentContext = JsrtContext::GetCurrent();
  3389. JsErrorCode cCheck = CheckContext(currentContext, JSRT_MAYBE_TRUE);
  3390. if(cCheck != JsNoError)
  3391. {
  3392. return JsNoError; //we are ok just aren't going to do any TTD related work
  3393. }
  3394. Js::ScriptContext* scriptContext = currentContext->GetScriptContext();
  3395. return GlobalAPIWrapper_NoRecord([&]() -> JsErrorCode
  3396. {
  3397. if(scriptContext->IsTTDRecordModeEnabled())
  3398. {
  3399. scriptContext->GetThreadContext()->TTDLog->RecordJsRTEventLoopYieldPoint();
  3400. }
  3401. return JsNoError;
  3402. });
  3403. #endif
  3404. }
  3405. CHAKRA_API JsTTDNotifyLongLivedReferenceAdd(_In_ JsValueRef value)
  3406. {
  3407. #if !ENABLE_TTD
  3408. return JsErrorCategoryUsage;
  3409. #else
  3410. return GlobalAPIWrapper([&](TTDRecorder& _actionEntryPopper) -> JsErrorCode
  3411. {
  3412. ThreadContext* threadContext = ThreadContext::GetContextForCurrentThread();
  3413. if(threadContext == nullptr)
  3414. {
  3415. return JsErrorNoCurrentContext;
  3416. }
  3417. Js::RecyclableObject* obj = Js::RecyclableObject::FromVar(value);
  3418. if(obj->GetScriptContext()->IsTTDRecordModeEnabled())
  3419. {
  3420. if(obj->GetScriptContext()->ShouldPerformRecordAction())
  3421. {
  3422. threadContext->TTDLog->RecordJsRTAddWeakRootRef(_actionEntryPopper, (Js::Var)value);
  3423. }
  3424. threadContext->TTDContext->AddRootRef_Record(TTD_CONVERT_OBJ_TO_LOG_PTR_ID(obj), obj);
  3425. }
  3426. return JsNoError;
  3427. });
  3428. #endif
  3429. }
  3430. CHAKRA_API JsTTDHostExit(_In_ int statusCode)
  3431. {
  3432. #if !ENABLE_TTD
  3433. return JsErrorCategoryUsage;
  3434. #else
  3435. return ContextAPIWrapper<JSRT_MAYBE_TRUE>([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  3436. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTHostExitProcess, statusCode);
  3437. return JsNoError;
  3438. });
  3439. #endif
  3440. }
  3441. CHAKRA_API JsTTDRawBufferCopySyncIndirect(_In_ JsValueRef dst, _In_ size_t dstIndex, _In_ JsValueRef src, _In_ size_t srcIndex, _In_ size_t count)
  3442. {
  3443. #if !ENABLE_TTD
  3444. return JsErrorCategoryUsage;
  3445. #else
  3446. if(dstIndex > UINT32_MAX || srcIndex > UINT32_MAX || count > UINT32_MAX)
  3447. {
  3448. return JsErrorInvalidArgument;
  3449. }
  3450. return ContextAPIWrapper<JSRT_MAYBE_TRUE>([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  3451. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTRawBufferCopySync, dst, (uint32)dstIndex, src, (uint32)srcIndex, (uint32)count);
  3452. return JsNoError;
  3453. });
  3454. #endif
  3455. }
  3456. CHAKRA_API JsTTDRawBufferModifySyncIndirect(_In_ JsValueRef buffer, _In_ size_t index, _In_ size_t count)
  3457. {
  3458. #if !ENABLE_TTD
  3459. return JsErrorCategoryUsage;
  3460. #else
  3461. if(index > UINT32_MAX || count > UINT32_MAX)
  3462. {
  3463. return JsErrorInvalidArgument;
  3464. }
  3465. return ContextAPIWrapper<JSRT_MAYBE_TRUE>([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  3466. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTRawBufferModifySync, buffer, (uint32)index, (uint32)count);
  3467. return JsNoError;
  3468. });
  3469. #endif
  3470. }
  3471. CHAKRA_API JsTTDRawBufferAsyncModificationRegister(_In_ JsValueRef instance, _In_ byte* initialModPos)
  3472. {
  3473. #if !ENABLE_TTD
  3474. return JsErrorCategoryUsage;
  3475. #else
  3476. JsValueRef addRefObj = nullptr;
  3477. JsErrorCode addRefResult = ContextAPIWrapper<JSRT_MAYBE_TRUE>([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  3478. if (scriptContext->IsTTDRecordModeEnabled())
  3479. {
  3480. TTDAssert(Js::ArrayBuffer::Is(instance), "Not array buffer object!!!");
  3481. Js::ArrayBuffer* dstBuff = Js::ArrayBuffer::FromVar(instance);
  3482. addRefObj = dstBuff;
  3483. TTDAssert(dstBuff->GetBuffer() <= initialModPos && initialModPos < dstBuff->GetBuffer() + dstBuff->GetByteLength(), "Not array buffer object!!!");
  3484. TTDAssert(initialModPos - dstBuff->GetBuffer() < UINT32_MAX, "This is really big!!!");
  3485. ptrdiff_t index = initialModPos - Js::ArrayBuffer::FromVar(instance)->GetBuffer();
  3486. scriptContext->TTDContextInfo->AddToAsyncPendingList(dstBuff, (uint32)index);
  3487. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTRawBufferAsyncModificationRegister, instance, (uint32)index);
  3488. }
  3489. return JsNoError;
  3490. });
  3491. if(addRefResult != JsNoError)
  3492. {
  3493. return addRefResult;
  3494. }
  3495. //We need to root add ref so we can find this during replay!!!
  3496. if(addRefObj == nullptr)
  3497. {
  3498. return JsNoError;
  3499. }
  3500. else
  3501. {
  3502. return JsAddRef(addRefObj, nullptr);
  3503. }
  3504. #endif
  3505. }
  3506. CHAKRA_API JsTTDRawBufferAsyncModifyComplete(_In_ byte* finalModPos)
  3507. {
  3508. #if !ENABLE_TTD
  3509. return JsErrorCategoryUsage;
  3510. #else
  3511. JsValueRef releaseObj = nullptr;
  3512. JsErrorCode releaseStatus = ContextAPIWrapper<JSRT_MAYBE_TRUE>([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  3513. if (scriptContext->IsTTDRecordModeEnabled())
  3514. {
  3515. TTD::TTDPendingAsyncBufferModification pendingAsyncInfo = { 0 };
  3516. scriptContext->TTDContextInfo->GetFromAsyncPendingList(&pendingAsyncInfo, finalModPos);
  3517. Js::ArrayBuffer* dstBuff = Js::ArrayBuffer::FromVar(pendingAsyncInfo.ArrayBufferVar);
  3518. releaseObj = dstBuff;
  3519. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTRawBufferAsyncModifyComplete, pendingAsyncInfo, finalModPos);
  3520. }
  3521. return JsNoError;
  3522. });
  3523. if(releaseStatus != JsNoError)
  3524. {
  3525. return releaseStatus;
  3526. }
  3527. //We need to root release ref so we can free this in replay if needed!!!
  3528. if(releaseObj == nullptr)
  3529. {
  3530. return JsNoError;
  3531. }
  3532. else
  3533. {
  3534. return JsRelease(releaseObj, nullptr);
  3535. }
  3536. #endif
  3537. }
  3538. CHAKRA_API JsTTDCheckAndAssertIfTTDRunning(_In_ const char* msg)
  3539. {
  3540. #if ENABLE_TTD
  3541. JsrtContext* context = JsrtContext::GetCurrent();
  3542. TTDAssert(context == nullptr || !context->GetScriptContext()->ShouldPerformRecordAction(), msg);
  3543. #endif
  3544. return JsNoError;
  3545. }
  3546. CHAKRA_API JsTTDGetSnapTimeTopLevelEventMove(_In_ JsRuntimeHandle runtimeHandle,
  3547. _In_ JsTTDMoveMode moveMode, _In_opt_ uint32_t kthEvent,
  3548. _Inout_ int64_t* targetEventTime, _Out_ int64_t* targetStartSnapTime,
  3549. _Out_opt_ int64_t* targetEndSnapTime)
  3550. {
  3551. #if !ENABLE_TTD
  3552. return JsErrorCategoryUsage;
  3553. #else
  3554. JsrtRuntime* runtime = JsrtRuntime::FromHandle(runtimeHandle);
  3555. ThreadContext* threadContext = runtime->GetThreadContext();
  3556. *targetStartSnapTime = -1;
  3557. if(targetEndSnapTime != nullptr)
  3558. {
  3559. *targetEndSnapTime = -1;
  3560. }
  3561. TTDAssert(threadContext->IsRuntimeInTTDMode(), "Should only happen in TT debugging mode.");
  3562. //If we requested a move to a specific event then extract the event count and try to find it
  3563. if((moveMode & JsTTDMoveMode::JsTTDMoveFirstEvent) == JsTTDMoveMode::JsTTDMoveFirstEvent)
  3564. {
  3565. *targetEventTime = threadContext->TTDLog->GetFirstEventTimeInLog();
  3566. if(*targetEventTime == -1)
  3567. {
  3568. return JsErrorCategoryUsage;
  3569. }
  3570. }
  3571. else if((moveMode & JsTTDMoveMode::JsTTDMoveLastEvent) == JsTTDMoveMode::JsTTDMoveLastEvent)
  3572. {
  3573. *targetEventTime = threadContext->TTDLog->GetLastEventTimeInLog();
  3574. if(*targetEventTime == -1)
  3575. {
  3576. return JsErrorCategoryUsage;
  3577. }
  3578. }
  3579. else if((moveMode & JsTTDMoveMode::JsTTDMoveKthEvent) == JsTTDMoveMode::JsTTDMoveKthEvent)
  3580. {
  3581. *targetEventTime = threadContext->TTDLog->GetKthEventTimeInLog(kthEvent);
  3582. if(*targetEventTime == -1)
  3583. {
  3584. return JsErrorCategoryUsage;
  3585. }
  3586. }
  3587. else
  3588. {
  3589. ;
  3590. }
  3591. #ifdef __APPLE__
  3592. //TODO: Explicit cast of ptr since compiler gets confused -- resolve in PAL later
  3593. static_assert(sizeof(int64_t) == sizeof(int64), "int64_t and int64 size mis-match");
  3594. *targetStartSnapTime = threadContext->TTDLog->FindSnapTimeForEventTime(*targetEventTime, (int64*)targetEndSnapTime);
  3595. #else
  3596. *targetStartSnapTime = threadContext->TTDLog->FindSnapTimeForEventTime(*targetEventTime, targetEndSnapTime);
  3597. #endif
  3598. return JsNoError;
  3599. #endif
  3600. }
  3601. CHAKRA_API JsTTDGetSnapShotBoundInterval(_In_ JsRuntimeHandle runtimeHandle, _In_ int64_t targetEventTime, _Out_ int64_t* startSnapTime, _Out_ int64_t* endSnapTime)
  3602. {
  3603. #if !ENABLE_TTD
  3604. return JsErrorCategoryUsage;
  3605. #else
  3606. JsrtRuntime* runtime = JsrtRuntime::FromHandle(runtimeHandle);
  3607. ThreadContext* threadContext = runtime->GetThreadContext();
  3608. TTDAssert(threadContext->IsRuntimeInTTDMode(), "Should only happen in TT debugging mode.");
  3609. #ifdef __APPLE__
  3610. //TODO: Explicit cast of ptr since compiler gets confused -- resolve in PAL later
  3611. static_assert(sizeof(int64_t) == sizeof(int64), "int64_t and int64 size mis-match");
  3612. threadContext->TTDLog->GetSnapShotBoundInterval(targetEventTime, (int64*)startSnapTime, (int64*)endSnapTime);
  3613. #else
  3614. threadContext->TTDLog->GetSnapShotBoundInterval(targetEventTime, startSnapTime, endSnapTime);
  3615. #endif
  3616. return JsNoError;
  3617. #endif
  3618. }
  3619. CHAKRA_API JsTTDGetPreviousSnapshotInterval(_In_ JsRuntimeHandle runtimeHandle, _In_ int64_t currentSnapStartTime, _Out_ int64_t* previousSnapTime)
  3620. {
  3621. #if !ENABLE_TTD
  3622. return JsErrorCategoryUsage;
  3623. #else
  3624. JsrtRuntime * runtime = JsrtRuntime::FromHandle(runtimeHandle);
  3625. ThreadContext * threadContext = runtime->GetThreadContext();
  3626. TTDAssert(threadContext->IsRuntimeInTTDMode(), "Should only happen in TT debugging mode.");
  3627. *previousSnapTime = threadContext->TTDLog->GetPreviousSnapshotInterval(currentSnapStartTime);
  3628. return JsNoError;
  3629. #endif
  3630. }
  3631. #if ENABLE_TTD
  3632. //Helper method for resetting breakpoint info around snapshot inflate
  3633. JsErrorCode TTDHandleBreakpointInfoAndInflate(int64_t snapTime, JsrtRuntime* runtime, ThreadContext* threadContext)
  3634. {
  3635. return GlobalAPIWrapper_NoRecord([&]() -> JsErrorCode
  3636. {
  3637. if(threadContext->TTDLog->IsDebugModeFlagSet())
  3638. {
  3639. threadContext->TTDExecutionInfo->LoadPreservedBPInfo(threadContext);
  3640. }
  3641. threadContext->TTDLog->DoSnapshotInflate(snapTime);
  3642. threadContext->TTDLog->ResetCallStackForTopLevelCall(-1);
  3643. if(threadContext->TTDExecutionInfo != nullptr)
  3644. {
  3645. threadContext->TTDExecutionInfo->ResetCallStackForTopLevelCall(-1);
  3646. }
  3647. return JsNoError;
  3648. });
  3649. }
  3650. #endif
  3651. CHAKRA_API JsTTDPreExecuteSnapShotInterval(_In_ JsRuntimeHandle runtimeHandle, _In_ int64_t startSnapTime, _In_ int64_t endSnapTime, _In_ JsTTDMoveMode moveMode, _Out_ int64_t* newTargetEventTime)
  3652. {
  3653. #if !ENABLE_TTD
  3654. return JsErrorCategoryUsage;
  3655. #else
  3656. *newTargetEventTime = -1;
  3657. JsrtRuntime* runtime = JsrtRuntime::FromHandle(runtimeHandle);
  3658. ThreadContext* threadContext = runtime->GetThreadContext();
  3659. TTDAssert(threadContext->IsRuntimeInTTDMode(), "Should only happen in TT debugging mode.");
  3660. TTD::EventLog* elog = threadContext->TTDLog;
  3661. TTD::ExecutionInfoManager* emanager = threadContext->TTDExecutionInfo;
  3662. JsErrorCode res = JsNoError;
  3663. JsErrorCode inflateStatus = TTDHandleBreakpointInfoAndInflate(startSnapTime, runtime, threadContext);
  3664. if(inflateStatus != JsNoError)
  3665. {
  3666. return inflateStatus;
  3667. }
  3668. //If we are in the "active" segment set the continue breakpoint
  3669. if((moveMode & JsTTDMoveMode::JsTTDMoveScanIntervalForContinueInActiveBreakpointSegment) == JsTTDMoveMode::JsTTDMoveScanIntervalForContinueInActiveBreakpointSegment)
  3670. {
  3671. GlobalAPIWrapper_NoRecord([&]() -> JsErrorCode
  3672. {
  3673. emanager->SetBPInfoForActiveSegmentContinueScan(threadContext->TTDContext);
  3674. return JsNoError;
  3675. });
  3676. }
  3677. elog->PushMode(TTD::TTDMode::DebuggerSuppressBreakpoints);
  3678. elog->PushMode(TTD::TTDMode::DebuggerLogBreakpoints);
  3679. try
  3680. {
  3681. if(endSnapTime == -1)
  3682. {
  3683. elog->ReplayRootEventsToTime(TTD_EVENT_MAXTIME);
  3684. }
  3685. else
  3686. {
  3687. elog->ReplayRootEventsToTime(endSnapTime);
  3688. }
  3689. }
  3690. catch(TTD::TTDebuggerAbortException abortException)
  3691. {
  3692. //If we hit the end of the log or we hit a terminal exception that is fine -- anything else is a problem
  3693. if(!abortException.IsEndOfLog() && !abortException.IsTopLevelException())
  3694. {
  3695. res = JsErrorFatal;
  3696. }
  3697. }
  3698. catch(...) //we are replaying something that should be known to execute successfully so encountering any error is very bad
  3699. {
  3700. res = JsErrorFatal;
  3701. TTDAssert(false, "Unexpected fatal Error");
  3702. }
  3703. elog->PopMode(TTD::TTDMode::DebuggerLogBreakpoints);
  3704. elog->PopMode(TTD::TTDMode::DebuggerSuppressBreakpoints);
  3705. //If we are in the "active" segment un-set the continue breakpoint
  3706. if((moveMode & JsTTDMoveMode::JsTTDMoveScanIntervalForContinueInActiveBreakpointSegment) == JsTTDMoveMode::JsTTDMoveScanIntervalForContinueInActiveBreakpointSegment)
  3707. {
  3708. GlobalAPIWrapper_NoRecord([&]() -> JsErrorCode
  3709. {
  3710. emanager->ClearBPInfoForActiveSegmentContinueScan(threadContext->TTDContext);
  3711. return JsNoError;
  3712. });
  3713. }
  3714. if((moveMode & JsTTDMoveMode::JsTTDMoveScanIntervalForContinue) == JsTTDMoveMode::JsTTDMoveScanIntervalForContinue)
  3715. {
  3716. bool bpFound = emanager->TryFindAndSetPreviousBP();
  3717. if(bpFound)
  3718. {
  3719. *newTargetEventTime = emanager->GetPendingTTDBPTargetEventTime();
  3720. }
  3721. }
  3722. return res;
  3723. #endif
  3724. }
  3725. CHAKRA_API JsTTDMoveToTopLevelEvent(_In_ JsRuntimeHandle runtimeHandle, _In_ JsTTDMoveMode moveMode, _In_ int64_t snapshotTime, _In_ int64_t eventTime)
  3726. {
  3727. #if !ENABLE_TTD
  3728. return JsErrorCategoryUsage;
  3729. #else
  3730. JsrtRuntime* runtime = JsrtRuntime::FromHandle(runtimeHandle);
  3731. ThreadContext* threadContext = runtime->GetThreadContext();
  3732. TTDAssert(threadContext->IsRuntimeInTTDMode(), "Should only happen in TT debugging mode.");
  3733. TTD::EventLog* elog = threadContext->TTDLog;
  3734. JsErrorCode res = JsNoError;
  3735. JsErrorCode inflateStatus = TTDHandleBreakpointInfoAndInflate(snapshotTime, runtime, threadContext);
  3736. if(inflateStatus != JsNoError)
  3737. {
  3738. return inflateStatus;
  3739. }
  3740. elog->PushMode(TTD::TTDMode::DebuggerSuppressBreakpoints);
  3741. try
  3742. {
  3743. elog->ReplayRootEventsToTime(eventTime);
  3744. elog->DoRtrSnapIfNeeded();
  3745. }
  3746. catch(...) //we are replaying something that should be known to execute successfully so encountering any error is very bad
  3747. {
  3748. res = JsErrorFatal;
  3749. TTDAssert(false, "Unexpected fatal Error");
  3750. }
  3751. elog->PopMode(TTD::TTDMode::DebuggerSuppressBreakpoints);
  3752. return res;
  3753. #endif
  3754. }
  3755. CHAKRA_API JsTTDReplayExecution(_Inout_ JsTTDMoveMode* moveMode, _Out_ int64_t* rootEventTime)
  3756. {
  3757. #if !ENABLE_TTD
  3758. return JsErrorCategoryUsage;
  3759. #else
  3760. JsrtContext *currentContext = JsrtContext::GetCurrent();
  3761. JsErrorCode cCheck = CheckContext(currentContext, JSRT_MAYBE_TRUE);
  3762. TTDAssert(cCheck == JsNoError, "This shouldn't happen!!!");
  3763. Js::ScriptContext* scriptContext = currentContext->GetScriptContext();
  3764. ThreadContext* threadContext = scriptContext->GetThreadContext();
  3765. TTDAssert(threadContext->IsRuntimeInTTDMode(), "Should only happen in TT debugging mode.");
  3766. TTD::EventLog* elog = threadContext->TTDLog;
  3767. TTD::ExecutionInfoManager* emanager = threadContext->TTDExecutionInfo;
  3768. if(emanager != nullptr)
  3769. {
  3770. JsErrorCode bpstatus = GlobalAPIWrapper_NoRecord([&]() -> JsErrorCode
  3771. {
  3772. if((*moveMode & JsTTDMoveMode::JsTTDMoveBreakOnEntry) == JsTTDMoveMode::JsTTDMoveBreakOnEntry)
  3773. {
  3774. emanager->SetBreakOnFirstUserCode();
  3775. }
  3776. //Set the active BP info from the manager (so we will hit the BP in step back operations)
  3777. emanager->SetActiveBPInfoAsNeeded(threadContext->TTDContext);
  3778. return JsNoError;
  3779. });
  3780. if(bpstatus != JsNoError)
  3781. {
  3782. return bpstatus;
  3783. }
  3784. }
  3785. *moveMode = JsTTDMoveMode::JsTTDMoveNone;
  3786. *rootEventTime = -1;
  3787. JsErrorCode res = JsNoError;
  3788. try
  3789. {
  3790. elog->ReplayRootEventsToTime(TTD_EVENT_MAXTIME);
  3791. }
  3792. catch(TTD::TTDebuggerAbortException abortException)
  3793. {
  3794. //if the debugger bails out with a move time request set info on the requested event time here
  3795. //rest of breakpoint info should have been set by the debugger callback before aborting
  3796. if (abortException.IsEventTimeMove() || abortException.IsTopLevelException())
  3797. {
  3798. *moveMode = (JsTTDMoveMode)abortException.GetMoveMode();
  3799. *rootEventTime = abortException.GetTargetEventTime();
  3800. //Check if we are tracking execution and, if so, set the exception location so we can access it later
  3801. if(emanager != nullptr && abortException.IsTopLevelException())
  3802. {
  3803. emanager->SetPendingTTDUnhandledException();
  3804. }
  3805. }
  3806. res = abortException.IsTopLevelException() ? JsErrorCategoryScript : JsNoError;
  3807. }
  3808. catch(...)
  3809. {
  3810. res = JsErrorFatal;
  3811. TTDAssert(false, "Unexpected fatal Error");
  3812. }
  3813. return res;
  3814. #endif
  3815. }
  3816. #ifdef _CHAKRACOREBUILD
  3817. template <class SrcChar, class DstChar>
  3818. static void CastCopy(const SrcChar* src, DstChar* dst, size_t count)
  3819. {
  3820. const SrcChar* end = src + count;
  3821. while (src < end)
  3822. {
  3823. *dst++ = static_cast<DstChar>(*src++);
  3824. }
  3825. }
  3826. CHAKRA_API JsCreateString(
  3827. _In_ const char *content,
  3828. _In_ size_t length,
  3829. _Out_ JsValueRef *value)
  3830. {
  3831. PARAM_NOT_NULL(content);
  3832. PARAM_NOT_NULL(value);
  3833. *value = JS_INVALID_REFERENCE;
  3834. if (length == static_cast<size_t>(-1))
  3835. {
  3836. length = strlen(content);
  3837. }
  3838. if (length > MaxCharCount)
  3839. {
  3840. return JsErrorOutOfMemory;
  3841. }
  3842. return ContextAPINoScriptWrapper([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  3843. Js::JavascriptString *stringValue = Js::LiteralStringWithPropertyStringPtr::
  3844. NewFromCString(content, (CharCount)length, scriptContext->GetLibrary());
  3845. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTCreateString, stringValue->GetSz(), stringValue->GetLength());
  3846. *value = stringValue;
  3847. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, value);
  3848. return JsNoError;
  3849. });
  3850. }
  3851. CHAKRA_API JsCreateStringUtf16(
  3852. _In_ const uint16_t *content,
  3853. _In_ size_t length,
  3854. _Out_ JsValueRef *value)
  3855. {
  3856. PARAM_NOT_NULL(content);
  3857. PARAM_NOT_NULL(value);
  3858. *value = JS_INVALID_REFERENCE;
  3859. if (length == static_cast<size_t>(-1))
  3860. {
  3861. length = wcslen((const char16 *)content);
  3862. }
  3863. if (length > static_cast<CharCount>(-1))
  3864. {
  3865. return JsErrorOutOfMemory;
  3866. }
  3867. return ContextAPINoScriptWrapper([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  3868. Js::JavascriptString *stringValue = Js::LiteralStringWithPropertyStringPtr::
  3869. NewFromWideString((const char16 *)content, (CharCount)length, scriptContext->GetLibrary());
  3870. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTCreateString, stringValue->GetSz(), stringValue->GetLength());
  3871. *value = stringValue;
  3872. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, value);
  3873. return JsNoError;
  3874. });
  3875. }
  3876. template <class CopyFunc>
  3877. JsErrorCode WriteStringCopy(
  3878. JsValueRef value,
  3879. int start,
  3880. int length,
  3881. _Out_opt_ size_t* written,
  3882. const CopyFunc& copyFunc)
  3883. {
  3884. if (written)
  3885. {
  3886. *written = 0; // init to 0 for default
  3887. }
  3888. const char16* str = nullptr;
  3889. size_t strLength = 0;
  3890. JsErrorCode errorCode = JsStringToPointer(value, &str, &strLength);
  3891. if (errorCode != JsNoError)
  3892. {
  3893. return errorCode;
  3894. }
  3895. if (start < 0 || (size_t)start > strLength)
  3896. {
  3897. return JsErrorInvalidArgument; // start out of range, no chars written
  3898. }
  3899. size_t count = min(static_cast<size_t>(length), strLength - start);
  3900. if (count == 0)
  3901. {
  3902. return JsNoError; // no chars written
  3903. }
  3904. errorCode = copyFunc(str + start, count, written);
  3905. if (errorCode != JsNoError)
  3906. {
  3907. return errorCode;
  3908. }
  3909. if (written)
  3910. {
  3911. *written = count;
  3912. }
  3913. return JsNoError;
  3914. }
  3915. CHAKRA_API JsCopyStringUtf16(
  3916. _In_ JsValueRef value,
  3917. _In_ int start,
  3918. _In_ int length,
  3919. _Out_opt_ uint16_t* buffer,
  3920. _Out_opt_ size_t* written)
  3921. {
  3922. PARAM_NOT_NULL(value);
  3923. VALIDATE_JSREF(value);
  3924. return WriteStringCopy(value, start, length, written,
  3925. [buffer](const char16* src, size_t count, size_t *needed)
  3926. {
  3927. if (buffer)
  3928. {
  3929. memmove(buffer, src, sizeof(char16) * count);
  3930. }
  3931. return JsNoError;
  3932. });
  3933. }
  3934. CHAKRA_API JsCopyString(
  3935. _In_ JsValueRef value,
  3936. _Out_opt_ char* buffer,
  3937. _In_ size_t bufferSize,
  3938. _Out_opt_ size_t* length)
  3939. {
  3940. PARAM_NOT_NULL(value);
  3941. VALIDATE_JSREF(value);
  3942. const char16* str = nullptr;
  3943. size_t strLength = 0;
  3944. JsErrorCode errorCode = JsStringToPointer(value, &str, &strLength);
  3945. if (errorCode != JsNoError)
  3946. {
  3947. return errorCode;
  3948. }
  3949. utf8::WideToNarrow utf8Str(str, strLength, buffer, bufferSize);
  3950. if (length)
  3951. {
  3952. *length = utf8Str.Length();
  3953. }
  3954. return JsNoError;
  3955. }
  3956. _ALWAYSINLINE JsErrorCode CompileRun(
  3957. JsValueRef scriptVal,
  3958. JsSourceContext sourceContext,
  3959. JsValueRef sourceUrl,
  3960. JsParseScriptAttributes parseAttributes,
  3961. _Out_ JsValueRef *result,
  3962. bool parseOnly)
  3963. {
  3964. PARAM_NOT_NULL(scriptVal);
  3965. VALIDATE_JSREF(scriptVal);
  3966. PARAM_NOT_NULL(sourceUrl);
  3967. bool isExternalArray = Js::ExternalArrayBuffer::Is(scriptVal),
  3968. isString = false;
  3969. bool isUtf8 = !(parseAttributes & JsParseScriptAttributeArrayBufferIsUtf16Encoded);
  3970. LoadScriptFlag scriptFlag = LoadScriptFlag_None;
  3971. const byte* script;
  3972. size_t cb;
  3973. const WCHAR *url;
  3974. if (isExternalArray)
  3975. {
  3976. script = ((Js::ExternalArrayBuffer*)(scriptVal))->GetBuffer();
  3977. cb = ((Js::ExternalArrayBuffer*)(scriptVal))->GetByteLength();
  3978. scriptFlag = (LoadScriptFlag)(isUtf8 ?
  3979. LoadScriptFlag_ExternalArrayBuffer | LoadScriptFlag_Utf8Source :
  3980. LoadScriptFlag_ExternalArrayBuffer);
  3981. }
  3982. else
  3983. {
  3984. isString = Js::JavascriptString::Is(scriptVal);
  3985. if (!isString)
  3986. {
  3987. return JsErrorInvalidArgument;
  3988. }
  3989. }
  3990. JsErrorCode error = GlobalAPIWrapper_NoRecord([&]() -> JsErrorCode {
  3991. if (isString)
  3992. {
  3993. Js::JavascriptString* jsString = Js::JavascriptString::FromVar(scriptVal);
  3994. script = (const byte*)jsString->GetSz();
  3995. // JavascriptString is 2 bytes (WCHAR/char16)
  3996. cb = jsString->GetLength() * sizeof(WCHAR);
  3997. }
  3998. if (!Js::JavascriptString::Is(sourceUrl))
  3999. {
  4000. return JsErrorInvalidArgument;
  4001. }
  4002. url = Js::JavascriptString::FromVar(sourceUrl)->GetSz();
  4003. return JsNoError;
  4004. });
  4005. if (error != JsNoError)
  4006. {
  4007. return error;
  4008. }
  4009. return RunScriptCore(scriptVal, script, cb, scriptFlag,
  4010. sourceContext, url, parseOnly, parseAttributes, false, result);
  4011. }
  4012. CHAKRA_API JsParse(
  4013. _In_ JsValueRef scriptVal,
  4014. _In_ JsSourceContext sourceContext,
  4015. _In_ JsValueRef sourceUrl,
  4016. _In_ JsParseScriptAttributes parseAttributes,
  4017. _Out_ JsValueRef *result)
  4018. {
  4019. return CompileRun(scriptVal, sourceContext, sourceUrl, parseAttributes,
  4020. result, true);
  4021. }
  4022. CHAKRA_API JsRun(
  4023. _In_ JsValueRef scriptVal,
  4024. _In_ JsSourceContext sourceContext,
  4025. _In_ JsValueRef sourceUrl,
  4026. _In_ JsParseScriptAttributes parseAttributes,
  4027. _Out_ JsValueRef *result)
  4028. {
  4029. return CompileRun(scriptVal, sourceContext, sourceUrl, parseAttributes,
  4030. result, false);
  4031. }
  4032. CHAKRA_API JsCreatePropertyId(
  4033. _In_z_ const char *name,
  4034. _In_ size_t length,
  4035. _Out_ JsPropertyIdRef *propertyId)
  4036. {
  4037. PARAM_NOT_NULL(name);
  4038. utf8::NarrowToWide wname(name, length);
  4039. if (!wname)
  4040. {
  4041. return JsErrorOutOfMemory;
  4042. }
  4043. return JsGetPropertyIdFromNameInternal(wname, wname.Length(), propertyId);
  4044. }
  4045. CHAKRA_API JsCopyPropertyId(
  4046. _In_ JsPropertyIdRef propertyId,
  4047. _Out_ char* buffer,
  4048. _In_ size_t bufferSize,
  4049. _Out_ size_t* length)
  4050. {
  4051. PARAM_NOT_NULL(propertyId);
  4052. const char16* str = nullptr;
  4053. JsErrorCode errorCode = JsGetPropertyNameFromId(propertyId, &str);
  4054. if (errorCode != JsNoError)
  4055. {
  4056. return errorCode;
  4057. }
  4058. utf8::WideToNarrow utf8Str(str);
  4059. if (!buffer)
  4060. {
  4061. if (length)
  4062. {
  4063. *length = utf8Str.Length();
  4064. }
  4065. }
  4066. else
  4067. {
  4068. size_t count = min(bufferSize, utf8Str.Length());
  4069. // Try to copy whole characters if buffer size insufficient
  4070. auto maxFitChars = utf8::ByteIndexIntoCharacterIndex(
  4071. (LPCUTF8)(const char*)utf8Str, count,
  4072. utf8::DecodeOptions::doChunkedEncoding);
  4073. count = utf8::CharacterIndexToByteIndex(
  4074. (LPCUTF8)(const char*)utf8Str, utf8Str.Length(), maxFitChars);
  4075. memmove(buffer, utf8Str, sizeof(char) * count);
  4076. if (length)
  4077. {
  4078. *length = count;
  4079. }
  4080. }
  4081. return JsNoError;
  4082. }
  4083. CHAKRA_API JsSerialize(
  4084. _In_ JsValueRef scriptVal,
  4085. _Out_ JsValueRef *bufferVal,
  4086. _In_ JsParseScriptAttributes parseAttributes)
  4087. {
  4088. PARAM_NOT_NULL(scriptVal);
  4089. PARAM_NOT_NULL(bufferVal);
  4090. VALIDATE_JSREF(scriptVal);
  4091. *bufferVal = nullptr;
  4092. bool isExternalArray = Js::ExternalArrayBuffer::Is(scriptVal),
  4093. isString = false;
  4094. bool isUtf8 = !(parseAttributes & JsParseScriptAttributeArrayBufferIsUtf16Encoded);
  4095. if (!isExternalArray)
  4096. {
  4097. isString = Js::JavascriptString::Is(scriptVal);
  4098. if (!isString)
  4099. {
  4100. return JsErrorInvalidArgument;
  4101. }
  4102. }
  4103. LoadScriptFlag scriptFlag;
  4104. const byte* script = isExternalArray ?
  4105. ((Js::ExternalArrayBuffer*)(scriptVal))->GetBuffer() :
  4106. (const byte*)((Js::JavascriptString*)(scriptVal))->GetSz();
  4107. const size_t cb = isExternalArray ?
  4108. ((Js::ExternalArrayBuffer*)(scriptVal))->GetByteLength() :
  4109. ((Js::JavascriptString*)(scriptVal))->GetLength();
  4110. if (isExternalArray && isUtf8)
  4111. {
  4112. scriptFlag = (LoadScriptFlag) (LoadScriptFlag_ExternalArrayBuffer | LoadScriptFlag_Utf8Source);
  4113. }
  4114. else if (isUtf8)
  4115. {
  4116. scriptFlag = (LoadScriptFlag) (LoadScriptFlag_Utf8Source);
  4117. }
  4118. else
  4119. {
  4120. scriptFlag = LoadScriptFlag_None;
  4121. }
  4122. unsigned int bufferSize = 0;
  4123. JsErrorCode errorCode = JsSerializeScriptCore(script, cb, scriptFlag, nullptr,
  4124. 0, nullptr, &bufferSize, scriptVal);
  4125. if (errorCode != JsNoError)
  4126. {
  4127. return errorCode;
  4128. }
  4129. if (bufferSize == 0)
  4130. {
  4131. return JsErrorScriptCompile;
  4132. }
  4133. if ((errorCode = JsCreateArrayBuffer(bufferSize, bufferVal)) == JsNoError)
  4134. {
  4135. byte* buffer = ((Js::ArrayBuffer*)(*bufferVal))->GetBuffer();
  4136. errorCode = JsSerializeScriptCore(script, cb, scriptFlag, nullptr,
  4137. 0, buffer, &bufferSize, scriptVal);
  4138. }
  4139. return errorCode;
  4140. }
  4141. CHAKRA_API JsParseSerialized(
  4142. _In_ JsValueRef bufferVal,
  4143. _In_ JsSerializedLoadScriptCallback scriptLoadCallback,
  4144. _In_ JsSourceContext sourceContext,
  4145. _In_ JsValueRef sourceUrl,
  4146. _Out_ JsValueRef *result)
  4147. {
  4148. PARAM_NOT_NULL(bufferVal);
  4149. PARAM_NOT_NULL(sourceUrl);
  4150. const WCHAR *url;
  4151. if (Js::JavascriptString::Is(sourceUrl))
  4152. {
  4153. url = ((Js::JavascriptString*)(sourceUrl))->GetSz();
  4154. }
  4155. else
  4156. {
  4157. return JsErrorInvalidArgument;
  4158. }
  4159. // JsParseSerialized only accepts ArrayBuffer (incl. ExternalArrayBuffer)
  4160. if (!Js::ExternalArrayBuffer::Is(bufferVal))
  4161. {
  4162. return JsErrorInvalidArgument;
  4163. }
  4164. byte* buffer = Js::ArrayBuffer::FromVar(bufferVal)->GetBuffer();
  4165. return RunSerializedScriptCore(
  4166. scriptLoadCallback, DummyScriptUnloadCallback,
  4167. sourceContext,// use the same user provided sourceContext as scriptLoadSourceContext
  4168. buffer, bufferVal, sourceContext, url, true, result);
  4169. }
  4170. CHAKRA_API JsRunSerialized(
  4171. _In_ JsValueRef bufferVal,
  4172. _In_ JsSerializedLoadScriptCallback scriptLoadCallback,
  4173. _In_ JsSourceContext sourceContext,
  4174. _In_ JsValueRef sourceUrl,
  4175. _Out_ JsValueRef *result)
  4176. {
  4177. PARAM_NOT_NULL(bufferVal);
  4178. const WCHAR *url;
  4179. if (sourceUrl && Js::JavascriptString::Is(sourceUrl))
  4180. {
  4181. url = ((Js::JavascriptString*)(sourceUrl))->GetSz();
  4182. }
  4183. else
  4184. {
  4185. return JsErrorInvalidArgument;
  4186. }
  4187. // JsParseSerialized only accepts ArrayBuffer (incl. ExternalArrayBuffer)
  4188. if (!Js::ExternalArrayBuffer::Is(bufferVal))
  4189. {
  4190. return JsErrorInvalidArgument;
  4191. }
  4192. byte* buffer = Js::ArrayBuffer::FromVar(bufferVal)->GetBuffer();
  4193. return RunSerializedScriptCore(
  4194. scriptLoadCallback, DummyScriptUnloadCallback,
  4195. sourceContext, // use the same user provided sourceContext as scriptLoadSourceContext
  4196. buffer, bufferVal, sourceContext, url, false, result);
  4197. }
  4198. CHAKRA_API JsCreatePromise(_Out_ JsValueRef *promise, _Out_ JsValueRef *resolve, _Out_ JsValueRef *reject)
  4199. {
  4200. return ContextAPIWrapper<JSRT_MAYBE_TRUE>([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  4201. PERFORM_JSRT_TTD_RECORD_ACTION_NOT_IMPLEMENTED(scriptContext);
  4202. PARAM_NOT_NULL(promise);
  4203. PARAM_NOT_NULL(resolve);
  4204. PARAM_NOT_NULL(reject);
  4205. *promise = nullptr;
  4206. *resolve = nullptr;
  4207. *reject = nullptr;
  4208. Js::JavascriptPromiseResolveOrRejectFunction *jsResolve = nullptr;
  4209. Js::JavascriptPromiseResolveOrRejectFunction *jsReject = nullptr;
  4210. Js::JavascriptPromise *jsPromise = scriptContext->GetLibrary()->CreatePromise();
  4211. Js::JavascriptPromise::InitializePromise(jsPromise, &jsResolve, &jsReject, scriptContext);
  4212. *promise = (JsValueRef)jsPromise;
  4213. *resolve = (JsValueRef)jsResolve;
  4214. *reject = (JsValueRef)jsReject;
  4215. return JsNoError;
  4216. });
  4217. }
  4218. CHAKRA_API JsGetPromiseState(_In_ JsValueRef promise, _Out_ JsPromiseState *state)
  4219. {
  4220. return ContextAPIWrapper<JSRT_MAYBE_TRUE>([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  4221. PERFORM_JSRT_TTD_RECORD_ACTION_NOT_IMPLEMENTED(scriptContext);
  4222. VALIDATE_INCOMING_REFERENCE(promise, scriptContext);
  4223. PARAM_NOT_NULL(state);
  4224. *state = JsPromiseState_Pending;
  4225. if (!Js::JavascriptPromise::Is(promise))
  4226. {
  4227. return JsErrorInvalidArgument;
  4228. }
  4229. Js::JavascriptPromise *jsPromise = Js::JavascriptPromise::FromVar(promise);
  4230. Js::JavascriptPromise::PromiseStatus status = jsPromise->GetStatus();
  4231. switch (status)
  4232. {
  4233. case Js::JavascriptPromise::PromiseStatus::PromiseStatusCode_HasRejection:
  4234. *state = JsPromiseState_Rejected;
  4235. break;
  4236. case Js::JavascriptPromise::PromiseStatus::PromiseStatusCode_HasResolution:
  4237. *state = JsPromiseState_Fulfilled;
  4238. break;
  4239. }
  4240. return JsNoError;
  4241. });
  4242. }
  4243. CHAKRA_API JsGetPromiseResult(_In_ JsValueRef promise, _Out_ JsValueRef *result)
  4244. {
  4245. return ContextAPIWrapper<JSRT_MAYBE_TRUE>([&](Js::ScriptContext *scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  4246. PERFORM_JSRT_TTD_RECORD_ACTION_NOT_IMPLEMENTED(scriptContext);
  4247. VALIDATE_INCOMING_REFERENCE(promise, scriptContext);
  4248. PARAM_NOT_NULL(result);
  4249. *result = JS_INVALID_REFERENCE;
  4250. if (!Js::JavascriptPromise::Is(promise))
  4251. {
  4252. return JsErrorInvalidArgument;
  4253. }
  4254. Js::JavascriptPromise *jsPromise = Js::JavascriptPromise::FromVar(promise);
  4255. Js::Var jsResult = jsPromise->GetResult();
  4256. if (jsResult == nullptr)
  4257. {
  4258. return JsErrorInvalidArgument;
  4259. }
  4260. *result = (JsValueRef)jsResult;
  4261. return JsNoError;
  4262. });
  4263. }
  4264. CHAKRA_API JsCreateWeakReference(
  4265. _In_ JsValueRef value,
  4266. _Out_ JsWeakRef* weakRef)
  4267. {
  4268. VALIDATE_JSREF(value);
  4269. PARAM_NOT_NULL(weakRef);
  4270. *weakRef = nullptr;
  4271. if (Js::TaggedNumber::Is(value))
  4272. {
  4273. return JsNoWeakRefRequired;
  4274. }
  4275. return GlobalAPIWrapper_NoRecord([&]() -> JsErrorCode {
  4276. ThreadContext* threadContext = ThreadContext::GetContextForCurrentThread();
  4277. if (threadContext == nullptr)
  4278. {
  4279. return JsErrorNoCurrentContext;
  4280. }
  4281. Recycler* recycler = threadContext->GetRecycler();
  4282. if (recycler->IsInObjectBeforeCollectCallback())
  4283. {
  4284. return JsErrorInObjectBeforeCollectCallback;
  4285. }
  4286. RecyclerHeapObjectInfo dummyObjectInfo;
  4287. if (!recycler->FindHeapObject(value, Memory::FindHeapObjectFlags::FindHeapObjectFlags_NoFlags, dummyObjectInfo))
  4288. {
  4289. // value is not recyler-allocated
  4290. return JsErrorInvalidArgument;
  4291. }
  4292. recycler->FindOrCreateWeakReferenceHandle<char>(
  4293. reinterpret_cast<char*>(value),
  4294. reinterpret_cast<Memory::RecyclerWeakReference<char>**>(weakRef));
  4295. return JsNoError;
  4296. });
  4297. }
  4298. CHAKRA_API JsGetWeakReferenceValue(
  4299. _In_ JsWeakRef weakRef,
  4300. _Out_ JsValueRef* value)
  4301. {
  4302. VALIDATE_JSREF(weakRef);
  4303. PARAM_NOT_NULL(value);
  4304. *value = JS_INVALID_REFERENCE;
  4305. return GlobalAPIWrapper_NoRecord([&]() -> JsErrorCode {
  4306. Memory::RecyclerWeakReference<char>* recyclerWeakReference =
  4307. reinterpret_cast<Memory::RecyclerWeakReference<char>*>(weakRef);
  4308. *value = reinterpret_cast<JsValueRef>(recyclerWeakReference->Get());
  4309. return JsNoError;
  4310. });
  4311. }
  4312. CHAKRA_API JsGetAndClearExceptionWithMetadata(_Out_ JsValueRef *metadata)
  4313. {
  4314. PARAM_NOT_NULL(metadata);
  4315. *metadata = nullptr;
  4316. JsrtContext *currentContext = JsrtContext::GetCurrent();
  4317. if (currentContext == nullptr)
  4318. {
  4319. return JsErrorNoCurrentContext;
  4320. }
  4321. Js::ScriptContext *scriptContext = currentContext->GetScriptContext();
  4322. Assert(scriptContext != nullptr);
  4323. if (scriptContext->GetRecycler() && scriptContext->GetRecycler()->IsHeapEnumInProgress())
  4324. {
  4325. return JsErrorHeapEnumInProgress;
  4326. }
  4327. else if (scriptContext->GetThreadContext()->IsInThreadServiceCallback())
  4328. {
  4329. return JsErrorInThreadServiceCallback;
  4330. }
  4331. if (scriptContext->GetThreadContext()->IsExecutionDisabled())
  4332. {
  4333. return JsErrorInDisabledState;
  4334. }
  4335. HRESULT hr = S_OK;
  4336. Js::JavascriptExceptionObject *recordedException = nullptr;
  4337. BEGIN_TRANSLATE_OOM_TO_HRESULT
  4338. if (scriptContext->HasRecordedException())
  4339. {
  4340. recordedException = scriptContext->GetAndClearRecordedException();
  4341. }
  4342. END_TRANSLATE_OOM_TO_HRESULT(hr)
  4343. if (hr == E_OUTOFMEMORY)
  4344. {
  4345. recordedException = scriptContext->GetThreadContext()->GetRecordedException();
  4346. }
  4347. if (recordedException == nullptr)
  4348. {
  4349. return JsErrorInvalidArgument;
  4350. }
  4351. Js::Var exception = recordedException->GetThrownObject(nullptr);
  4352. if (exception == nullptr)
  4353. {
  4354. // TODO: How does this early bailout impact TTD?
  4355. return JsErrorInvalidArgument;
  4356. }
  4357. return ContextAPIWrapper<false>([&](Js::ScriptContext* scriptContext, TTDRecorder& _actionEntryPopper) -> JsErrorCode {
  4358. Js::Var exceptionMetadata = Js::JavascriptExceptionMetadata::CreateMetadataVar(scriptContext);
  4359. Js::JavascriptOperators::OP_SetProperty(exceptionMetadata, Js::PropertyIds::exception, exception, scriptContext);
  4360. Js::FunctionBody *functionBody = recordedException->GetFunctionBody();
  4361. if (functionBody == nullptr)
  4362. {
  4363. // This is probably a parse error. We can get the error location metadata from the thrown object.
  4364. Js::JavascriptExceptionMetadata::PopulateMetadataFromCompileException(exceptionMetadata, exception, scriptContext);
  4365. }
  4366. else
  4367. {
  4368. if (!Js::JavascriptExceptionMetadata::PopulateMetadataFromException(exceptionMetadata, recordedException, scriptContext))
  4369. {
  4370. return JsErrorInvalidArgument;
  4371. }
  4372. }
  4373. *metadata = exceptionMetadata;
  4374. #if ENABLE_TTD
  4375. if (hr != E_OUTOFMEMORY)
  4376. {
  4377. PERFORM_JSRT_TTD_RECORD_ACTION(scriptContext, RecordJsRTGetAndClearExceptionWithMetadata);
  4378. PERFORM_JSRT_TTD_RECORD_ACTION_RESULT(scriptContext, metadata);
  4379. }
  4380. #endif
  4381. return JsNoError;
  4382. });
  4383. }
  4384. CHAKRA_API JsCopyStringOneByte(
  4385. _In_ JsValueRef value,
  4386. _In_ int start,
  4387. _In_ int length,
  4388. _Out_opt_ char* buffer,
  4389. _Out_opt_ size_t* written)
  4390. {
  4391. PARAM_NOT_NULL(value);
  4392. VALIDATE_JSREF(value);
  4393. return WriteStringCopy(value, start, length, written,
  4394. [buffer](const char16* src, size_t count, size_t *needed)
  4395. {
  4396. if (buffer)
  4397. {
  4398. for (size_t i = 0; i < count; i++)
  4399. {
  4400. buffer[i] = (char)src[i];
  4401. }
  4402. }
  4403. return JsNoError;
  4404. });
  4405. }
  4406. CHAKRA_API JsGetDataViewInfo(
  4407. _In_ JsValueRef dataView,
  4408. _Out_opt_ JsValueRef *arrayBuffer,
  4409. _Out_opt_ unsigned int *byteOffset,
  4410. _Out_opt_ unsigned int *byteLength)
  4411. {
  4412. VALIDATE_JSREF(dataView);
  4413. BEGIN_JSRT_NO_EXCEPTION
  4414. {
  4415. if (!Js::DataView::Is(dataView))
  4416. {
  4417. RETURN_NO_EXCEPTION(JsErrorInvalidArgument);
  4418. }
  4419. Js::DataView* dv = Js::DataView::FromVar(dataView);
  4420. if (arrayBuffer != nullptr) {
  4421. *arrayBuffer = dv->GetArrayBuffer();
  4422. }
  4423. if (byteOffset != nullptr) {
  4424. *byteOffset = dv->GetByteOffset();
  4425. }
  4426. if (byteLength != nullptr) {
  4427. *byteLength = dv->GetLength();
  4428. }
  4429. }
  4430. #if ENABLE_TTD
  4431. Js::ScriptContext* scriptContext = Js::RecyclableObject::FromVar(dataView)->GetScriptContext();
  4432. if(PERFORM_JSRT_TTD_RECORD_ACTION_CHECK(scriptContext) && arrayBuffer != nullptr)
  4433. {
  4434. scriptContext->GetThreadContext()->TTDLog->RecordJsRTGetDataViewInfo(dataView, *arrayBuffer);
  4435. }
  4436. #endif
  4437. END_JSRT_NO_EXCEPTION
  4438. }
  4439. CHAKRA_API JsSetHostPromiseRejectionTracker(_In_ JsHostPromiseRejectionTrackerCallback promiseRejectionTrackerCallback, _In_opt_ void *callbackState)
  4440. {
  4441. return ContextAPINoScriptWrapper_NoRecord([&](Js::ScriptContext *scriptContext) -> JsErrorCode {
  4442. scriptContext->GetLibrary()->SetNativeHostPromiseRejectionTrackerCallback((Js::JavascriptLibrary::HostPromiseRejectionTrackerCallback) promiseRejectionTrackerCallback, callbackState);
  4443. return JsNoError;
  4444. },
  4445. /*allowInObjectBeforeCollectCallback*/true);
  4446. }
  4447. CHAKRA_API JsGetProxyProperties (_In_ JsValueRef object, _Out_ bool* isProxy, _Out_opt_ JsValueRef* target, _Out_opt_ JsValueRef* handler)
  4448. {
  4449. return ContextAPINoScriptWrapper_NoRecord([&](Js::ScriptContext * scriptContext) -> JsErrorCode {
  4450. VALIDATE_INCOMING_REFERENCE(object, scriptContext);
  4451. PARAM_NOT_NULL(isProxy);
  4452. if (target != nullptr)
  4453. {
  4454. *target = JS_INVALID_REFERENCE;
  4455. }
  4456. if (handler != nullptr)
  4457. {
  4458. *handler = JS_INVALID_REFERENCE;
  4459. }
  4460. *isProxy = Js::JavascriptProxy::Is(object);
  4461. if (!*isProxy)
  4462. {
  4463. return JsNoError;
  4464. }
  4465. Js::JavascriptProxy* proxy = Js::JavascriptProxy::UnsafeFromVar(object);
  4466. bool revoked = proxy->IsRevoked();
  4467. if (target != nullptr && !revoked)
  4468. {
  4469. *target = static_cast<JsValueRef>(proxy->GetTarget());
  4470. }
  4471. if (handler != nullptr && !revoked)
  4472. {
  4473. *handler = static_cast<JsValueRef>(proxy->GetHandler());
  4474. }
  4475. return JsNoError;
  4476. },
  4477. /*allowInObjectBeforeCollectCallback*/true);
  4478. }
  4479. #endif // _CHAKRACOREBUILD