nan.h 86 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892
  1. /*********************************************************************
  2. * NAN - Native Abstractions for Node.js
  3. *
  4. * Copyright (c) 2018 NAN contributors:
  5. * - Rod Vagg <https://github.com/rvagg>
  6. * - Benjamin Byholm <https://github.com/kkoopa>
  7. * - Trevor Norris <https://github.com/trevnorris>
  8. * - Nathan Rajlich <https://github.com/TooTallNate>
  9. * - Brett Lawson <https://github.com/brett19>
  10. * - Ben Noordhuis <https://github.com/bnoordhuis>
  11. * - David Siegel <https://github.com/agnat>
  12. * - Michael Ira Krufky <https://github.com/mkrufky>
  13. *
  14. * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
  15. *
  16. * Version 2.14.0: current Node 12.2.0, Node 12: 0.12.18, Node 10: 0.10.48, iojs: 3.3.1
  17. *
  18. * See https://github.com/nodejs/nan for the latest update to this file
  19. **********************************************************************************/
  20. #ifndef NAN_H_
  21. #define NAN_H_
  22. #include <node_version.h>
  23. #define NODE_0_10_MODULE_VERSION 11
  24. #define NODE_0_12_MODULE_VERSION 14
  25. #define ATOM_0_21_MODULE_VERSION 41
  26. #define IOJS_1_0_MODULE_VERSION 42
  27. #define IOJS_1_1_MODULE_VERSION 43
  28. #define IOJS_2_0_MODULE_VERSION 44
  29. #define IOJS_3_0_MODULE_VERSION 45
  30. #define NODE_4_0_MODULE_VERSION 46
  31. #define NODE_5_0_MODULE_VERSION 47
  32. #define NODE_6_0_MODULE_VERSION 48
  33. #define NODE_7_0_MODULE_VERSION 51
  34. #define NODE_8_0_MODULE_VERSION 57
  35. #define NODE_9_0_MODULE_VERSION 59
  36. #define NODE_10_0_MODULE_VERSION 64
  37. #define NODE_11_0_MODULE_VERSION 67
  38. #define NODE_12_0_MODULE_VERSION 72
  39. #ifdef _MSC_VER
  40. # define NAN_HAS_CPLUSPLUS_11 (_MSC_VER >= 1800)
  41. #else
  42. # define NAN_HAS_CPLUSPLUS_11 (__cplusplus >= 201103L)
  43. #endif
  44. #if NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION && !NAN_HAS_CPLUSPLUS_11
  45. # error This version of node/NAN/v8 requires a C++11 compiler
  46. #endif
  47. #include <uv.h>
  48. #include <node.h>
  49. #include <node_buffer.h>
  50. #include <node_object_wrap.h>
  51. #include <algorithm>
  52. #include <cstring>
  53. #include <climits>
  54. #include <cstdlib>
  55. #include <utility>
  56. #if defined(_MSC_VER)
  57. # pragma warning( push )
  58. # pragma warning( disable : 4530 )
  59. # include <queue>
  60. # include <string>
  61. # include <vector>
  62. # pragma warning( pop )
  63. #else
  64. # include <queue>
  65. # include <string>
  66. # include <vector>
  67. #endif
  68. // uv helpers
  69. #ifdef UV_VERSION_MAJOR
  70. # ifndef UV_VERSION_PATCH
  71. # define UV_VERSION_PATCH 0
  72. # endif
  73. # define NAUV_UVVERSION ((UV_VERSION_MAJOR << 16) | \
  74. (UV_VERSION_MINOR << 8) | \
  75. (UV_VERSION_PATCH))
  76. #else
  77. # define NAUV_UVVERSION 0x000b00
  78. #endif
  79. #if NAUV_UVVERSION < 0x000b0b
  80. # ifdef WIN32
  81. # include <windows.h>
  82. # else
  83. # include <pthread.h>
  84. # endif
  85. #endif
  86. namespace Nan {
  87. #define NAN_CONCAT(a, b) NAN_CONCAT_HELPER(a, b)
  88. #define NAN_CONCAT_HELPER(a, b) a##b
  89. #define NAN_INLINE inline // TODO(bnoordhuis) Remove in v3.0.0.
  90. #if defined(__GNUC__) && \
  91. !(defined(V8_DISABLE_DEPRECATIONS) && V8_DISABLE_DEPRECATIONS)
  92. # define NAN_DEPRECATED __attribute__((deprecated))
  93. #elif defined(_MSC_VER) && \
  94. !(defined(V8_DISABLE_DEPRECATIONS) && V8_DISABLE_DEPRECATIONS)
  95. # define NAN_DEPRECATED __declspec(deprecated)
  96. #else
  97. # define NAN_DEPRECATED
  98. #endif
  99. #if NAN_HAS_CPLUSPLUS_11
  100. # define NAN_DISALLOW_ASSIGN(CLASS) void operator=(const CLASS&) = delete;
  101. # define NAN_DISALLOW_COPY(CLASS) CLASS(const CLASS&) = delete;
  102. # define NAN_DISALLOW_MOVE(CLASS) \
  103. CLASS(CLASS&&) = delete; /* NOLINT(build/c++11) */ \
  104. void operator=(CLASS&&) = delete;
  105. #else
  106. # define NAN_DISALLOW_ASSIGN(CLASS) void operator=(const CLASS&);
  107. # define NAN_DISALLOW_COPY(CLASS) CLASS(const CLASS&);
  108. # define NAN_DISALLOW_MOVE(CLASS)
  109. #endif
  110. #define NAN_DISALLOW_ASSIGN_COPY(CLASS) \
  111. NAN_DISALLOW_ASSIGN(CLASS) \
  112. NAN_DISALLOW_COPY(CLASS)
  113. #define NAN_DISALLOW_ASSIGN_MOVE(CLASS) \
  114. NAN_DISALLOW_ASSIGN(CLASS) \
  115. NAN_DISALLOW_MOVE(CLASS)
  116. #define NAN_DISALLOW_COPY_MOVE(CLASS) \
  117. NAN_DISALLOW_COPY(CLASS) \
  118. NAN_DISALLOW_MOVE(CLASS)
  119. #define NAN_DISALLOW_ASSIGN_COPY_MOVE(CLASS) \
  120. NAN_DISALLOW_ASSIGN(CLASS) \
  121. NAN_DISALLOW_COPY(CLASS) \
  122. NAN_DISALLOW_MOVE(CLASS)
  123. #define TYPE_CHECK(T, S) \
  124. while (false) { \
  125. *(static_cast<T *volatile *>(0)) = static_cast<S*>(0); \
  126. }
  127. //=== RegistrationFunction =====================================================
  128. #if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
  129. typedef v8::Handle<v8::Object> ADDON_REGISTER_FUNCTION_ARGS_TYPE;
  130. #else
  131. typedef v8::Local<v8::Object> ADDON_REGISTER_FUNCTION_ARGS_TYPE;
  132. #endif
  133. #define NAN_MODULE_INIT(name) \
  134. void name(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target)
  135. #if NODE_MAJOR_VERSION >= 10 || \
  136. NODE_MAJOR_VERSION == 9 && NODE_MINOR_VERSION >= 3
  137. #define NAN_MODULE_WORKER_ENABLED(module_name, registration) \
  138. extern "C" NODE_MODULE_EXPORT void \
  139. NAN_CONCAT(node_register_module_v, NODE_MODULE_VERSION)( \
  140. v8::Local<v8::Object> exports, v8::Local<v8::Value> module, \
  141. v8::Local<v8::Context> context) \
  142. { \
  143. registration(exports); \
  144. }
  145. #else
  146. #define NAN_MODULE_WORKER_ENABLED(module_name, registration) \
  147. NODE_MODULE(module_name, registration)
  148. #endif
  149. //=== CallbackInfo =============================================================
  150. #include "nan_callbacks.h" // NOLINT(build/include)
  151. //==============================================================================
  152. #if (NODE_MODULE_VERSION < NODE_0_12_MODULE_VERSION)
  153. typedef v8::Script UnboundScript;
  154. typedef v8::Script BoundScript;
  155. #else
  156. typedef v8::UnboundScript UnboundScript;
  157. typedef v8::Script BoundScript;
  158. #endif
  159. #if (NODE_MODULE_VERSION < ATOM_0_21_MODULE_VERSION)
  160. typedef v8::String::ExternalAsciiStringResource
  161. ExternalOneByteStringResource;
  162. #else
  163. typedef v8::String::ExternalOneByteStringResource
  164. ExternalOneByteStringResource;
  165. #endif
  166. #if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION)
  167. template<typename T>
  168. class NonCopyablePersistentTraits :
  169. public v8::NonCopyablePersistentTraits<T> {};
  170. template<typename T>
  171. class CopyablePersistentTraits :
  172. public v8::CopyablePersistentTraits<T> {};
  173. template<typename T>
  174. class PersistentBase :
  175. public v8::PersistentBase<T> {};
  176. template<typename T, typename M = v8::NonCopyablePersistentTraits<T> >
  177. class Persistent;
  178. #else
  179. template<typename T> class NonCopyablePersistentTraits;
  180. template<typename T> class PersistentBase;
  181. template<typename T, typename P> class WeakCallbackData;
  182. template<typename T, typename M = NonCopyablePersistentTraits<T> >
  183. class Persistent;
  184. #endif // NODE_MODULE_VERSION
  185. template<typename T>
  186. class Maybe {
  187. public:
  188. inline bool IsNothing() const { return !has_value_; }
  189. inline bool IsJust() const { return has_value_; }
  190. inline T ToChecked() const { return FromJust(); }
  191. inline void Check() const { FromJust(); }
  192. inline bool To(T* out) const {
  193. if (IsJust()) *out = value_;
  194. return IsJust();
  195. }
  196. inline T FromJust() const {
  197. #if defined(V8_ENABLE_CHECKS)
  198. assert(IsJust() && "FromJust is Nothing");
  199. #endif // V8_ENABLE_CHECKS
  200. return value_;
  201. }
  202. inline T FromMaybe(const T& default_value) const {
  203. return has_value_ ? value_ : default_value;
  204. }
  205. inline bool operator==(const Maybe &other) const {
  206. return (IsJust() == other.IsJust()) &&
  207. (!IsJust() || FromJust() == other.FromJust());
  208. }
  209. inline bool operator!=(const Maybe &other) const {
  210. return !operator==(other);
  211. }
  212. #if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \
  213. (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
  214. // Allow implicit conversions from v8::Maybe<T> to Nan::Maybe<T>.
  215. Maybe(const v8::Maybe<T>& that) // NOLINT(runtime/explicit)
  216. : has_value_(that.IsJust())
  217. , value_(that.FromMaybe(T())) {}
  218. #endif
  219. private:
  220. Maybe() : has_value_(false) {}
  221. explicit Maybe(const T& t) : has_value_(true), value_(t) {}
  222. bool has_value_;
  223. T value_;
  224. template<typename U>
  225. friend Maybe<U> Nothing();
  226. template<typename U>
  227. friend Maybe<U> Just(const U& u);
  228. };
  229. template<typename T>
  230. inline Maybe<T> Nothing() {
  231. return Maybe<T>();
  232. }
  233. template<typename T>
  234. inline Maybe<T> Just(const T& t) {
  235. return Maybe<T>(t);
  236. }
  237. #if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \
  238. (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
  239. # include "nan_maybe_43_inl.h" // NOLINT(build/include)
  240. #else
  241. # include "nan_maybe_pre_43_inl.h" // NOLINT(build/include)
  242. #endif
  243. #include "nan_converters.h" // NOLINT(build/include)
  244. #include "nan_new.h" // NOLINT(build/include)
  245. #if NAUV_UVVERSION < 0x000b17
  246. #define NAUV_WORK_CB(func) \
  247. void func(uv_async_t *async, int)
  248. #else
  249. #define NAUV_WORK_CB(func) \
  250. void func(uv_async_t *async)
  251. #endif
  252. #if NAUV_UVVERSION >= 0x000b0b
  253. typedef uv_key_t nauv_key_t;
  254. inline int nauv_key_create(nauv_key_t *key) {
  255. return uv_key_create(key);
  256. }
  257. inline void nauv_key_delete(nauv_key_t *key) {
  258. uv_key_delete(key);
  259. }
  260. inline void* nauv_key_get(nauv_key_t *key) {
  261. return uv_key_get(key);
  262. }
  263. inline void nauv_key_set(nauv_key_t *key, void *value) {
  264. uv_key_set(key, value);
  265. }
  266. #else
  267. /* Implement thread local storage for older versions of libuv.
  268. * This is essentially a backport of libuv commit 5d2434bf
  269. * written by Ben Noordhuis, adjusted for names and inline.
  270. */
  271. #ifndef WIN32
  272. typedef pthread_key_t nauv_key_t;
  273. inline int nauv_key_create(nauv_key_t* key) {
  274. return -pthread_key_create(key, NULL);
  275. }
  276. inline void nauv_key_delete(nauv_key_t* key) {
  277. if (pthread_key_delete(*key))
  278. abort();
  279. }
  280. inline void* nauv_key_get(nauv_key_t* key) {
  281. return pthread_getspecific(*key);
  282. }
  283. inline void nauv_key_set(nauv_key_t* key, void* value) {
  284. if (pthread_setspecific(*key, value))
  285. abort();
  286. }
  287. #else
  288. typedef struct {
  289. DWORD tls_index;
  290. } nauv_key_t;
  291. inline int nauv_key_create(nauv_key_t* key) {
  292. key->tls_index = TlsAlloc();
  293. if (key->tls_index == TLS_OUT_OF_INDEXES)
  294. return UV_ENOMEM;
  295. return 0;
  296. }
  297. inline void nauv_key_delete(nauv_key_t* key) {
  298. if (TlsFree(key->tls_index) == FALSE)
  299. abort();
  300. key->tls_index = TLS_OUT_OF_INDEXES;
  301. }
  302. inline void* nauv_key_get(nauv_key_t* key) {
  303. void* value = TlsGetValue(key->tls_index);
  304. if (value == NULL)
  305. if (GetLastError() != ERROR_SUCCESS)
  306. abort();
  307. return value;
  308. }
  309. inline void nauv_key_set(nauv_key_t* key, void* value) {
  310. if (TlsSetValue(key->tls_index, value) == FALSE)
  311. abort();
  312. }
  313. #endif
  314. #endif
  315. #if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
  316. template<typename T>
  317. v8::Local<T> New(v8::Handle<T>);
  318. #endif
  319. #if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \
  320. (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
  321. typedef v8::WeakCallbackType WeakCallbackType;
  322. #else
  323. struct WeakCallbackType {
  324. enum E {kParameter, kInternalFields};
  325. E type;
  326. WeakCallbackType(E other) : type(other) {} // NOLINT(runtime/explicit)
  327. inline bool operator==(E other) { return other == this->type; }
  328. inline bool operator!=(E other) { return !operator==(other); }
  329. };
  330. #endif
  331. template<typename P> class WeakCallbackInfo;
  332. #if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
  333. # include "nan_persistent_12_inl.h" // NOLINT(build/include)
  334. #else
  335. # include "nan_persistent_pre_12_inl.h" // NOLINT(build/include)
  336. #endif
  337. namespace imp {
  338. static const size_t kMaxLength = 0x3fffffff;
  339. // v8::String::REPLACE_INVALID_UTF8 was introduced
  340. // in node.js v0.10.29 and v0.8.27.
  341. #if NODE_MAJOR_VERSION > 0 || \
  342. NODE_MINOR_VERSION > 10 || \
  343. NODE_MINOR_VERSION == 10 && NODE_PATCH_VERSION >= 29 || \
  344. NODE_MINOR_VERSION == 8 && NODE_PATCH_VERSION >= 27
  345. static const unsigned kReplaceInvalidUtf8 = v8::String::REPLACE_INVALID_UTF8;
  346. #else
  347. static const unsigned kReplaceInvalidUtf8 = 0;
  348. #endif
  349. } // end of namespace imp
  350. //=== HandleScope ==============================================================
  351. class HandleScope {
  352. v8::HandleScope scope;
  353. public:
  354. #if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
  355. inline HandleScope() : scope(v8::Isolate::GetCurrent()) {}
  356. inline static int NumberOfHandles() {
  357. return v8::HandleScope::NumberOfHandles(v8::Isolate::GetCurrent());
  358. }
  359. #else
  360. inline HandleScope() : scope() {}
  361. inline static int NumberOfHandles() {
  362. return v8::HandleScope::NumberOfHandles();
  363. }
  364. #endif
  365. private:
  366. // Make it hard to create heap-allocated or illegal handle scopes by
  367. // disallowing certain operations.
  368. HandleScope(const HandleScope &);
  369. void operator=(const HandleScope &);
  370. void *operator new(size_t size);
  371. void operator delete(void *, size_t) {
  372. abort();
  373. }
  374. };
  375. class EscapableHandleScope {
  376. public:
  377. #if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
  378. inline EscapableHandleScope() : scope(v8::Isolate::GetCurrent()) {}
  379. inline static int NumberOfHandles() {
  380. return v8::EscapableHandleScope::NumberOfHandles(v8::Isolate::GetCurrent());
  381. }
  382. template<typename T>
  383. inline v8::Local<T> Escape(v8::Local<T> value) {
  384. return scope.Escape(value);
  385. }
  386. private:
  387. v8::EscapableHandleScope scope;
  388. #else
  389. inline EscapableHandleScope() : scope() {}
  390. inline static int NumberOfHandles() {
  391. return v8::HandleScope::NumberOfHandles();
  392. }
  393. template<typename T>
  394. inline v8::Local<T> Escape(v8::Local<T> value) {
  395. return scope.Close(value);
  396. }
  397. private:
  398. v8::HandleScope scope;
  399. #endif
  400. private:
  401. // Make it hard to create heap-allocated or illegal handle scopes by
  402. // disallowing certain operations.
  403. EscapableHandleScope(const EscapableHandleScope &);
  404. void operator=(const EscapableHandleScope &);
  405. void *operator new(size_t size);
  406. void operator delete(void *, size_t) {
  407. abort();
  408. }
  409. };
  410. //=== TryCatch =================================================================
  411. class TryCatch {
  412. v8::TryCatch try_catch_;
  413. friend void FatalException(const TryCatch&);
  414. public:
  415. #if NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION
  416. TryCatch() : try_catch_(v8::Isolate::GetCurrent()) {}
  417. #endif
  418. inline bool HasCaught() const { return try_catch_.HasCaught(); }
  419. inline bool CanContinue() const { return try_catch_.CanContinue(); }
  420. inline v8::Local<v8::Value> ReThrow() {
  421. #if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
  422. return New(try_catch_.ReThrow());
  423. #else
  424. return try_catch_.ReThrow();
  425. #endif
  426. }
  427. inline v8::Local<v8::Value> Exception() const {
  428. return try_catch_.Exception();
  429. }
  430. #if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \
  431. (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
  432. inline v8::MaybeLocal<v8::Value> StackTrace() const {
  433. v8::Isolate *isolate = v8::Isolate::GetCurrent();
  434. v8::EscapableHandleScope scope(isolate);
  435. return scope.Escape(try_catch_.StackTrace(isolate->GetCurrentContext())
  436. .FromMaybe(v8::Local<v8::Value>()));
  437. }
  438. #else
  439. inline MaybeLocal<v8::Value> StackTrace() const {
  440. return try_catch_.StackTrace();
  441. }
  442. #endif
  443. inline v8::Local<v8::Message> Message() const {
  444. return try_catch_.Message();
  445. }
  446. inline void Reset() { try_catch_.Reset(); }
  447. inline void SetVerbose(bool value) { try_catch_.SetVerbose(value); }
  448. inline void SetCaptureMessage(bool value) {
  449. try_catch_.SetCaptureMessage(value);
  450. }
  451. };
  452. v8::Local<v8::Value> MakeCallback(v8::Local<v8::Object> target,
  453. v8::Local<v8::Function> func,
  454. int argc,
  455. v8::Local<v8::Value>* argv);
  456. v8::Local<v8::Value> MakeCallback(v8::Local<v8::Object> target,
  457. v8::Local<v8::String> symbol,
  458. int argc,
  459. v8::Local<v8::Value>* argv);
  460. v8::Local<v8::Value> MakeCallback(v8::Local<v8::Object> target,
  461. const char* method,
  462. int argc,
  463. v8::Local<v8::Value>* argv);
  464. // === AsyncResource ===========================================================
  465. class AsyncResource {
  466. public:
  467. AsyncResource(
  468. v8::Local<v8::String> name
  469. , v8::Local<v8::Object> resource = New<v8::Object>()) {
  470. #if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  471. v8::Isolate* isolate = v8::Isolate::GetCurrent();
  472. if (resource.IsEmpty()) {
  473. resource = New<v8::Object>();
  474. }
  475. context = node::EmitAsyncInit(isolate, resource, name);
  476. #endif
  477. }
  478. AsyncResource(
  479. const char* name
  480. , v8::Local<v8::Object> resource = New<v8::Object>()) {
  481. #if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  482. v8::Isolate* isolate = v8::Isolate::GetCurrent();
  483. if (resource.IsEmpty()) {
  484. resource = New<v8::Object>();
  485. }
  486. v8::Local<v8::String> name_string =
  487. New<v8::String>(name).ToLocalChecked();
  488. context = node::EmitAsyncInit(isolate, resource, name_string);
  489. #endif
  490. }
  491. ~AsyncResource() {
  492. #if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  493. v8::Isolate* isolate = v8::Isolate::GetCurrent();
  494. node::EmitAsyncDestroy(isolate, context);
  495. #endif
  496. }
  497. inline MaybeLocal<v8::Value> runInAsyncScope(
  498. v8::Local<v8::Object> target
  499. , v8::Local<v8::Function> func
  500. , int argc
  501. , v8::Local<v8::Value>* argv) {
  502. #if NODE_MODULE_VERSION < NODE_9_0_MODULE_VERSION
  503. return MakeCallback(target, func, argc, argv);
  504. #else
  505. return node::MakeCallback(
  506. v8::Isolate::GetCurrent(), target, func, argc, argv, context);
  507. #endif
  508. }
  509. inline MaybeLocal<v8::Value> runInAsyncScope(
  510. v8::Local<v8::Object> target
  511. , v8::Local<v8::String> symbol
  512. , int argc
  513. , v8::Local<v8::Value>* argv) {
  514. #if NODE_MODULE_VERSION < NODE_9_0_MODULE_VERSION
  515. return MakeCallback(target, symbol, argc, argv);
  516. #else
  517. return node::MakeCallback(
  518. v8::Isolate::GetCurrent(), target, symbol, argc, argv, context);
  519. #endif
  520. }
  521. inline MaybeLocal<v8::Value> runInAsyncScope(
  522. v8::Local<v8::Object> target
  523. , const char* method
  524. , int argc
  525. , v8::Local<v8::Value>* argv) {
  526. #if NODE_MODULE_VERSION < NODE_9_0_MODULE_VERSION
  527. return MakeCallback(target, method, argc, argv);
  528. #else
  529. return node::MakeCallback(
  530. v8::Isolate::GetCurrent(), target, method, argc, argv, context);
  531. #endif
  532. }
  533. private:
  534. NAN_DISALLOW_ASSIGN_COPY_MOVE(AsyncResource)
  535. #if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  536. node::async_context context;
  537. #endif
  538. };
  539. inline uv_loop_t* GetCurrentEventLoop() {
  540. #if NODE_MAJOR_VERSION >= 10 || \
  541. NODE_MAJOR_VERSION == 9 && NODE_MINOR_VERSION >= 3 || \
  542. NODE_MAJOR_VERSION == 8 && NODE_MINOR_VERSION >= 10
  543. return node::GetCurrentEventLoop(v8::Isolate::GetCurrent());
  544. #else
  545. return uv_default_loop();
  546. #endif
  547. }
  548. //============ =================================================================
  549. /* node 0.12 */
  550. #if NODE_MODULE_VERSION >= NODE_0_12_MODULE_VERSION
  551. inline
  552. void SetCounterFunction(v8::CounterLookupCallback cb) {
  553. v8::Isolate::GetCurrent()->SetCounterFunction(cb);
  554. }
  555. inline
  556. void SetCreateHistogramFunction(v8::CreateHistogramCallback cb) {
  557. v8::Isolate::GetCurrent()->SetCreateHistogramFunction(cb);
  558. }
  559. inline
  560. void SetAddHistogramSampleFunction(v8::AddHistogramSampleCallback cb) {
  561. v8::Isolate::GetCurrent()->SetAddHistogramSampleFunction(cb);
  562. }
  563. #if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \
  564. (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
  565. inline bool IdleNotification(int idle_time_in_ms) {
  566. return v8::Isolate::GetCurrent()->IdleNotificationDeadline(
  567. idle_time_in_ms * 0.001);
  568. }
  569. # else
  570. inline bool IdleNotification(int idle_time_in_ms) {
  571. return v8::Isolate::GetCurrent()->IdleNotification(idle_time_in_ms);
  572. }
  573. #endif
  574. inline void LowMemoryNotification() {
  575. v8::Isolate::GetCurrent()->LowMemoryNotification();
  576. }
  577. inline void ContextDisposedNotification() {
  578. v8::Isolate::GetCurrent()->ContextDisposedNotification();
  579. }
  580. #else
  581. inline
  582. void SetCounterFunction(v8::CounterLookupCallback cb) {
  583. v8::V8::SetCounterFunction(cb);
  584. }
  585. inline
  586. void SetCreateHistogramFunction(v8::CreateHistogramCallback cb) {
  587. v8::V8::SetCreateHistogramFunction(cb);
  588. }
  589. inline
  590. void SetAddHistogramSampleFunction(v8::AddHistogramSampleCallback cb) {
  591. v8::V8::SetAddHistogramSampleFunction(cb);
  592. }
  593. inline bool IdleNotification(int idle_time_in_ms) {
  594. return v8::V8::IdleNotification(idle_time_in_ms);
  595. }
  596. inline void LowMemoryNotification() {
  597. v8::V8::LowMemoryNotification();
  598. }
  599. inline void ContextDisposedNotification() {
  600. v8::V8::ContextDisposedNotification();
  601. }
  602. #endif
  603. #if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION) // Node 0.12
  604. inline v8::Local<v8::Primitive> Undefined() {
  605. # if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
  606. EscapableHandleScope scope;
  607. return scope.Escape(New(v8::Undefined(v8::Isolate::GetCurrent())));
  608. # else
  609. return v8::Undefined(v8::Isolate::GetCurrent());
  610. # endif
  611. }
  612. inline v8::Local<v8::Primitive> Null() {
  613. # if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
  614. EscapableHandleScope scope;
  615. return scope.Escape(New(v8::Null(v8::Isolate::GetCurrent())));
  616. # else
  617. return v8::Null(v8::Isolate::GetCurrent());
  618. # endif
  619. }
  620. inline v8::Local<v8::Boolean> True() {
  621. # if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
  622. EscapableHandleScope scope;
  623. return scope.Escape(New(v8::True(v8::Isolate::GetCurrent())));
  624. # else
  625. return v8::True(v8::Isolate::GetCurrent());
  626. # endif
  627. }
  628. inline v8::Local<v8::Boolean> False() {
  629. # if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
  630. EscapableHandleScope scope;
  631. return scope.Escape(New(v8::False(v8::Isolate::GetCurrent())));
  632. # else
  633. return v8::False(v8::Isolate::GetCurrent());
  634. # endif
  635. }
  636. inline v8::Local<v8::String> EmptyString() {
  637. return v8::String::Empty(v8::Isolate::GetCurrent());
  638. }
  639. inline int AdjustExternalMemory(int bc) {
  640. return static_cast<int>(
  641. v8::Isolate::GetCurrent()->AdjustAmountOfExternalAllocatedMemory(bc));
  642. }
  643. inline void SetTemplate(
  644. v8::Local<v8::Template> templ
  645. , const char *name
  646. , v8::Local<v8::Data> value) {
  647. templ->Set(v8::Isolate::GetCurrent(), name, value);
  648. }
  649. inline void SetTemplate(
  650. v8::Local<v8::Template> templ
  651. , v8::Local<v8::String> name
  652. , v8::Local<v8::Data> value
  653. , v8::PropertyAttribute attributes) {
  654. templ->Set(name, value, attributes);
  655. }
  656. inline v8::Local<v8::Context> GetCurrentContext() {
  657. return v8::Isolate::GetCurrent()->GetCurrentContext();
  658. }
  659. inline void* GetInternalFieldPointer(
  660. v8::Local<v8::Object> object
  661. , int index) {
  662. return object->GetAlignedPointerFromInternalField(index);
  663. }
  664. inline void SetInternalFieldPointer(
  665. v8::Local<v8::Object> object
  666. , int index
  667. , void* value) {
  668. object->SetAlignedPointerInInternalField(index, value);
  669. }
  670. # define NAN_GC_CALLBACK(name) \
  671. void name(v8::Isolate *isolate, v8::GCType type, v8::GCCallbackFlags flags)
  672. #if NODE_MODULE_VERSION <= NODE_4_0_MODULE_VERSION
  673. typedef v8::Isolate::GCEpilogueCallback GCEpilogueCallback;
  674. typedef v8::Isolate::GCPrologueCallback GCPrologueCallback;
  675. #else
  676. typedef v8::Isolate::GCCallback GCEpilogueCallback;
  677. typedef v8::Isolate::GCCallback GCPrologueCallback;
  678. #endif
  679. inline void AddGCEpilogueCallback(
  680. GCEpilogueCallback callback
  681. , v8::GCType gc_type_filter = v8::kGCTypeAll) {
  682. v8::Isolate::GetCurrent()->AddGCEpilogueCallback(callback, gc_type_filter);
  683. }
  684. inline void RemoveGCEpilogueCallback(
  685. GCEpilogueCallback callback) {
  686. v8::Isolate::GetCurrent()->RemoveGCEpilogueCallback(callback);
  687. }
  688. inline void AddGCPrologueCallback(
  689. GCPrologueCallback callback
  690. , v8::GCType gc_type_filter = v8::kGCTypeAll) {
  691. v8::Isolate::GetCurrent()->AddGCPrologueCallback(callback, gc_type_filter);
  692. }
  693. inline void RemoveGCPrologueCallback(
  694. GCPrologueCallback callback) {
  695. v8::Isolate::GetCurrent()->RemoveGCPrologueCallback(callback);
  696. }
  697. inline void GetHeapStatistics(
  698. v8::HeapStatistics *heap_statistics) {
  699. v8::Isolate::GetCurrent()->GetHeapStatistics(heap_statistics);
  700. }
  701. # define X(NAME) \
  702. inline v8::Local<v8::Value> NAME(const char *msg) { \
  703. EscapableHandleScope scope; \
  704. return scope.Escape(v8::Exception::NAME(New(msg).ToLocalChecked())); \
  705. } \
  706. \
  707. inline \
  708. v8::Local<v8::Value> NAME(v8::Local<v8::String> msg) { \
  709. return v8::Exception::NAME(msg); \
  710. } \
  711. \
  712. inline void Throw ## NAME(const char *msg) { \
  713. HandleScope scope; \
  714. v8::Isolate::GetCurrent()->ThrowException( \
  715. v8::Exception::NAME(New(msg).ToLocalChecked())); \
  716. } \
  717. \
  718. inline void Throw ## NAME(v8::Local<v8::String> msg) { \
  719. HandleScope scope; \
  720. v8::Isolate::GetCurrent()->ThrowException( \
  721. v8::Exception::NAME(msg)); \
  722. }
  723. X(Error)
  724. X(RangeError)
  725. X(ReferenceError)
  726. X(SyntaxError)
  727. X(TypeError)
  728. # undef X
  729. inline void ThrowError(v8::Local<v8::Value> error) {
  730. v8::Isolate::GetCurrent()->ThrowException(error);
  731. }
  732. inline MaybeLocal<v8::Object> NewBuffer(
  733. char *data
  734. , size_t length
  735. #if NODE_MODULE_VERSION > IOJS_2_0_MODULE_VERSION
  736. , node::Buffer::FreeCallback callback
  737. #else
  738. , node::smalloc::FreeCallback callback
  739. #endif
  740. , void *hint
  741. ) {
  742. // arbitrary buffer lengths requires
  743. // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION
  744. assert(length <= imp::kMaxLength && "too large buffer");
  745. #if NODE_MODULE_VERSION > IOJS_2_0_MODULE_VERSION
  746. return node::Buffer::New(
  747. v8::Isolate::GetCurrent(), data, length, callback, hint);
  748. #else
  749. return node::Buffer::New(v8::Isolate::GetCurrent(), data, length, callback,
  750. hint);
  751. #endif
  752. }
  753. inline MaybeLocal<v8::Object> CopyBuffer(
  754. const char *data
  755. , uint32_t size
  756. ) {
  757. // arbitrary buffer lengths requires
  758. // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION
  759. assert(size <= imp::kMaxLength && "too large buffer");
  760. #if NODE_MODULE_VERSION > IOJS_2_0_MODULE_VERSION
  761. return node::Buffer::Copy(
  762. v8::Isolate::GetCurrent(), data, size);
  763. #else
  764. return node::Buffer::New(v8::Isolate::GetCurrent(), data, size);
  765. #endif
  766. }
  767. inline MaybeLocal<v8::Object> NewBuffer(uint32_t size) {
  768. // arbitrary buffer lengths requires
  769. // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION
  770. assert(size <= imp::kMaxLength && "too large buffer");
  771. #if NODE_MODULE_VERSION > IOJS_2_0_MODULE_VERSION
  772. return node::Buffer::New(
  773. v8::Isolate::GetCurrent(), size);
  774. #else
  775. return node::Buffer::New(v8::Isolate::GetCurrent(), size);
  776. #endif
  777. }
  778. inline MaybeLocal<v8::Object> NewBuffer(
  779. char* data
  780. , uint32_t size
  781. ) {
  782. // arbitrary buffer lengths requires
  783. // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION
  784. assert(size <= imp::kMaxLength && "too large buffer");
  785. #if NODE_MODULE_VERSION > IOJS_2_0_MODULE_VERSION
  786. return node::Buffer::New(v8::Isolate::GetCurrent(), data, size);
  787. #else
  788. return node::Buffer::Use(v8::Isolate::GetCurrent(), data, size);
  789. #endif
  790. }
  791. #if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \
  792. (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
  793. inline MaybeLocal<v8::String>
  794. NewOneByteString(const uint8_t * value, int length = -1) {
  795. return v8::String::NewFromOneByte(v8::Isolate::GetCurrent(), value,
  796. v8::NewStringType::kNormal, length);
  797. }
  798. inline MaybeLocal<BoundScript> CompileScript(
  799. v8::Local<v8::String> s
  800. , const v8::ScriptOrigin& origin
  801. ) {
  802. v8::Isolate *isolate = v8::Isolate::GetCurrent();
  803. v8::EscapableHandleScope scope(isolate);
  804. v8::ScriptCompiler::Source source(s, origin);
  805. return scope.Escape(
  806. v8::ScriptCompiler::Compile(isolate->GetCurrentContext(), &source)
  807. .FromMaybe(v8::Local<BoundScript>()));
  808. }
  809. inline MaybeLocal<BoundScript> CompileScript(
  810. v8::Local<v8::String> s
  811. ) {
  812. v8::Isolate *isolate = v8::Isolate::GetCurrent();
  813. v8::EscapableHandleScope scope(isolate);
  814. v8::ScriptCompiler::Source source(s);
  815. return scope.Escape(
  816. v8::ScriptCompiler::Compile(isolate->GetCurrentContext(), &source)
  817. .FromMaybe(v8::Local<BoundScript>()));
  818. }
  819. inline MaybeLocal<v8::Value> RunScript(
  820. v8::Local<UnboundScript> script
  821. ) {
  822. v8::Isolate *isolate = v8::Isolate::GetCurrent();
  823. v8::EscapableHandleScope scope(isolate);
  824. return scope.Escape(script->BindToCurrentContext()
  825. ->Run(isolate->GetCurrentContext())
  826. .FromMaybe(v8::Local<v8::Value>()));
  827. }
  828. inline MaybeLocal<v8::Value> RunScript(
  829. v8::Local<BoundScript> script
  830. ) {
  831. v8::Isolate *isolate = v8::Isolate::GetCurrent();
  832. v8::EscapableHandleScope scope(isolate);
  833. return scope.Escape(script->Run(isolate->GetCurrentContext())
  834. .FromMaybe(v8::Local<v8::Value>()));
  835. }
  836. #else
  837. inline MaybeLocal<v8::String>
  838. NewOneByteString(const uint8_t * value, int length = -1) {
  839. return v8::String::NewFromOneByte(v8::Isolate::GetCurrent(), value,
  840. v8::String::kNormalString, length);
  841. }
  842. inline MaybeLocal<BoundScript> CompileScript(
  843. v8::Local<v8::String> s
  844. , const v8::ScriptOrigin& origin
  845. ) {
  846. v8::ScriptCompiler::Source source(s, origin);
  847. return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &source);
  848. }
  849. inline MaybeLocal<BoundScript> CompileScript(
  850. v8::Local<v8::String> s
  851. ) {
  852. v8::ScriptCompiler::Source source(s);
  853. return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &source);
  854. }
  855. inline MaybeLocal<v8::Value> RunScript(
  856. v8::Local<UnboundScript> script
  857. ) {
  858. EscapableHandleScope scope;
  859. return scope.Escape(script->BindToCurrentContext()->Run());
  860. }
  861. inline MaybeLocal<v8::Value> RunScript(
  862. v8::Local<BoundScript> script
  863. ) {
  864. return script->Run();
  865. }
  866. #endif
  867. NAN_DEPRECATED inline v8::Local<v8::Value> MakeCallback(
  868. v8::Local<v8::Object> target
  869. , v8::Local<v8::Function> func
  870. , int argc
  871. , v8::Local<v8::Value>* argv) {
  872. #if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
  873. EscapableHandleScope scope;
  874. return scope.Escape(New(node::MakeCallback(
  875. v8::Isolate::GetCurrent(), target, func, argc, argv)));
  876. #else
  877. # if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  878. AsyncResource res("nan:makeCallback");
  879. return res.runInAsyncScope(target, func, argc, argv)
  880. .FromMaybe(v8::Local<v8::Value>());
  881. # else
  882. return node::MakeCallback(
  883. v8::Isolate::GetCurrent(), target, func, argc, argv);
  884. # endif // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  885. #endif // NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
  886. }
  887. NAN_DEPRECATED inline v8::Local<v8::Value> MakeCallback(
  888. v8::Local<v8::Object> target
  889. , v8::Local<v8::String> symbol
  890. , int argc
  891. , v8::Local<v8::Value>* argv) {
  892. #if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
  893. EscapableHandleScope scope;
  894. return scope.Escape(New(node::MakeCallback(
  895. v8::Isolate::GetCurrent(), target, symbol, argc, argv)));
  896. #else
  897. # if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  898. AsyncResource res("nan:makeCallback");
  899. return res.runInAsyncScope(target, symbol, argc, argv)
  900. .FromMaybe(v8::Local<v8::Value>());
  901. # else
  902. return node::MakeCallback(
  903. v8::Isolate::GetCurrent(), target, symbol, argc, argv);
  904. # endif // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  905. #endif // NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
  906. }
  907. NAN_DEPRECATED inline v8::Local<v8::Value> MakeCallback(
  908. v8::Local<v8::Object> target
  909. , const char* method
  910. , int argc
  911. , v8::Local<v8::Value>* argv) {
  912. #if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
  913. EscapableHandleScope scope;
  914. return scope.Escape(New(node::MakeCallback(
  915. v8::Isolate::GetCurrent(), target, method, argc, argv)));
  916. #else
  917. # if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  918. AsyncResource res("nan:makeCallback");
  919. return res.runInAsyncScope(target, method, argc, argv)
  920. .FromMaybe(v8::Local<v8::Value>());
  921. # else
  922. return node::MakeCallback(
  923. v8::Isolate::GetCurrent(), target, method, argc, argv);
  924. # endif // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  925. #endif // NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
  926. }
  927. inline void FatalException(const TryCatch& try_catch) {
  928. node::FatalException(v8::Isolate::GetCurrent(), try_catch.try_catch_);
  929. }
  930. inline v8::Local<v8::Value> ErrnoException(
  931. int errorno
  932. , const char* syscall = NULL
  933. , const char* message = NULL
  934. , const char* path = NULL) {
  935. return node::ErrnoException(v8::Isolate::GetCurrent(), errorno, syscall,
  936. message, path);
  937. }
  938. NAN_DEPRECATED inline v8::Local<v8::Value> NanErrnoException(
  939. int errorno
  940. , const char* syscall = NULL
  941. , const char* message = NULL
  942. , const char* path = NULL) {
  943. return ErrnoException(errorno, syscall, message, path);
  944. }
  945. template<typename T>
  946. inline void SetIsolateData(
  947. v8::Isolate *isolate
  948. , T *data
  949. ) {
  950. isolate->SetData(0, data);
  951. }
  952. template<typename T>
  953. inline T *GetIsolateData(
  954. v8::Isolate *isolate
  955. ) {
  956. return static_cast<T*>(isolate->GetData(0));
  957. }
  958. class Utf8String {
  959. public:
  960. inline explicit Utf8String(v8::Local<v8::Value> from) :
  961. length_(0), str_(str_st_) {
  962. HandleScope scope;
  963. if (!from.IsEmpty()) {
  964. #if NODE_MAJOR_VERSION >= 10
  965. v8::Local<v8::Context> context = GetCurrentContext();
  966. v8::Local<v8::String> string =
  967. from->ToString(context).FromMaybe(v8::Local<v8::String>());
  968. #else
  969. v8::Local<v8::String> string = from->ToString();
  970. #endif
  971. if (!string.IsEmpty()) {
  972. size_t len = 3 * string->Length() + 1;
  973. assert(len <= INT_MAX);
  974. if (len > sizeof (str_st_)) {
  975. str_ = static_cast<char*>(malloc(len));
  976. assert(str_ != 0);
  977. }
  978. const int flags =
  979. v8::String::NO_NULL_TERMINATION | imp::kReplaceInvalidUtf8;
  980. #if NODE_MAJOR_VERSION >= 11
  981. length_ = string->WriteUtf8(v8::Isolate::GetCurrent(), str_,
  982. static_cast<int>(len), 0, flags);
  983. #else
  984. // See https://github.com/nodejs/nan/issues/832.
  985. // Disable the warning as there is no way around it.
  986. #ifdef _MSC_VER
  987. #pragma warning(push)
  988. #pragma warning(disable : 4996)
  989. #endif
  990. #ifdef __GNUC__
  991. #pragma GCC diagnostic push
  992. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  993. #endif
  994. length_ = string->WriteUtf8(str_, static_cast<int>(len), 0, flags);
  995. #ifdef __GNUC__
  996. #pragma GCC diagnostic pop
  997. #endif
  998. #ifdef _MSC_VER
  999. #pragma warning(pop)
  1000. #endif
  1001. #endif // NODE_MAJOR_VERSION < 11
  1002. str_[length_] = '\0';
  1003. }
  1004. }
  1005. }
  1006. inline int length() const {
  1007. return length_;
  1008. }
  1009. inline char* operator*() { return str_; }
  1010. inline const char* operator*() const { return str_; }
  1011. inline ~Utf8String() {
  1012. if (str_ != str_st_) {
  1013. free(str_);
  1014. }
  1015. }
  1016. private:
  1017. NAN_DISALLOW_ASSIGN_COPY_MOVE(Utf8String)
  1018. int length_;
  1019. char *str_;
  1020. char str_st_[1024];
  1021. };
  1022. #else // Node 0.8 and 0.10
  1023. inline v8::Local<v8::Primitive> Undefined() {
  1024. EscapableHandleScope scope;
  1025. return scope.Escape(New(v8::Undefined()));
  1026. }
  1027. inline v8::Local<v8::Primitive> Null() {
  1028. EscapableHandleScope scope;
  1029. return scope.Escape(New(v8::Null()));
  1030. }
  1031. inline v8::Local<v8::Boolean> True() {
  1032. EscapableHandleScope scope;
  1033. return scope.Escape(New(v8::True()));
  1034. }
  1035. inline v8::Local<v8::Boolean> False() {
  1036. EscapableHandleScope scope;
  1037. return scope.Escape(New(v8::False()));
  1038. }
  1039. inline v8::Local<v8::String> EmptyString() {
  1040. return v8::String::Empty();
  1041. }
  1042. inline int AdjustExternalMemory(int bc) {
  1043. return static_cast<int>(v8::V8::AdjustAmountOfExternalAllocatedMemory(bc));
  1044. }
  1045. inline void SetTemplate(
  1046. v8::Local<v8::Template> templ
  1047. , const char *name
  1048. , v8::Local<v8::Data> value) {
  1049. templ->Set(name, value);
  1050. }
  1051. inline void SetTemplate(
  1052. v8::Local<v8::Template> templ
  1053. , v8::Local<v8::String> name
  1054. , v8::Local<v8::Data> value
  1055. , v8::PropertyAttribute attributes) {
  1056. templ->Set(name, value, attributes);
  1057. }
  1058. inline v8::Local<v8::Context> GetCurrentContext() {
  1059. return v8::Context::GetCurrent();
  1060. }
  1061. inline void* GetInternalFieldPointer(
  1062. v8::Local<v8::Object> object
  1063. , int index) {
  1064. return object->GetPointerFromInternalField(index);
  1065. }
  1066. inline void SetInternalFieldPointer(
  1067. v8::Local<v8::Object> object
  1068. , int index
  1069. , void* value) {
  1070. object->SetPointerInInternalField(index, value);
  1071. }
  1072. # define NAN_GC_CALLBACK(name) \
  1073. void name(v8::GCType type, v8::GCCallbackFlags flags)
  1074. inline void AddGCEpilogueCallback(
  1075. v8::GCEpilogueCallback callback
  1076. , v8::GCType gc_type_filter = v8::kGCTypeAll) {
  1077. v8::V8::AddGCEpilogueCallback(callback, gc_type_filter);
  1078. }
  1079. inline void RemoveGCEpilogueCallback(
  1080. v8::GCEpilogueCallback callback) {
  1081. v8::V8::RemoveGCEpilogueCallback(callback);
  1082. }
  1083. inline void AddGCPrologueCallback(
  1084. v8::GCPrologueCallback callback
  1085. , v8::GCType gc_type_filter = v8::kGCTypeAll) {
  1086. v8::V8::AddGCPrologueCallback(callback, gc_type_filter);
  1087. }
  1088. inline void RemoveGCPrologueCallback(
  1089. v8::GCPrologueCallback callback) {
  1090. v8::V8::RemoveGCPrologueCallback(callback);
  1091. }
  1092. inline void GetHeapStatistics(
  1093. v8::HeapStatistics *heap_statistics) {
  1094. v8::V8::GetHeapStatistics(heap_statistics);
  1095. }
  1096. # define X(NAME) \
  1097. inline v8::Local<v8::Value> NAME(const char *msg) { \
  1098. EscapableHandleScope scope; \
  1099. return scope.Escape(v8::Exception::NAME(New(msg).ToLocalChecked())); \
  1100. } \
  1101. \
  1102. inline \
  1103. v8::Local<v8::Value> NAME(v8::Local<v8::String> msg) { \
  1104. return v8::Exception::NAME(msg); \
  1105. } \
  1106. \
  1107. inline void Throw ## NAME(const char *msg) { \
  1108. HandleScope scope; \
  1109. v8::ThrowException(v8::Exception::NAME(New(msg).ToLocalChecked())); \
  1110. } \
  1111. \
  1112. inline \
  1113. void Throw ## NAME(v8::Local<v8::String> errmsg) { \
  1114. HandleScope scope; \
  1115. v8::ThrowException(v8::Exception::NAME(errmsg)); \
  1116. }
  1117. X(Error)
  1118. X(RangeError)
  1119. X(ReferenceError)
  1120. X(SyntaxError)
  1121. X(TypeError)
  1122. # undef X
  1123. inline void ThrowError(v8::Local<v8::Value> error) {
  1124. v8::ThrowException(error);
  1125. }
  1126. inline MaybeLocal<v8::Object> NewBuffer(
  1127. char *data
  1128. , size_t length
  1129. , node::Buffer::free_callback callback
  1130. , void *hint
  1131. ) {
  1132. EscapableHandleScope scope;
  1133. // arbitrary buffer lengths requires
  1134. // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION
  1135. assert(length <= imp::kMaxLength && "too large buffer");
  1136. return scope.Escape(
  1137. New(node::Buffer::New(data, length, callback, hint)->handle_));
  1138. }
  1139. inline MaybeLocal<v8::Object> CopyBuffer(
  1140. const char *data
  1141. , uint32_t size
  1142. ) {
  1143. EscapableHandleScope scope;
  1144. // arbitrary buffer lengths requires
  1145. // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION
  1146. assert(size <= imp::kMaxLength && "too large buffer");
  1147. #if NODE_MODULE_VERSION >= NODE_0_10_MODULE_VERSION
  1148. return scope.Escape(New(node::Buffer::New(data, size)->handle_));
  1149. #else
  1150. return scope.Escape(
  1151. New(node::Buffer::New(const_cast<char *>(data), size)->handle_));
  1152. #endif
  1153. }
  1154. inline MaybeLocal<v8::Object> NewBuffer(uint32_t size) {
  1155. // arbitrary buffer lengths requires
  1156. // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION
  1157. EscapableHandleScope scope;
  1158. assert(size <= imp::kMaxLength && "too large buffer");
  1159. return scope.Escape(New(node::Buffer::New(size)->handle_));
  1160. }
  1161. inline void FreeData(char *data, void *hint) {
  1162. (void) hint; // unused
  1163. delete[] data;
  1164. }
  1165. inline MaybeLocal<v8::Object> NewBuffer(
  1166. char* data
  1167. , uint32_t size
  1168. ) {
  1169. EscapableHandleScope scope;
  1170. // arbitrary buffer lengths requires
  1171. // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION
  1172. assert(size <= imp::kMaxLength && "too large buffer");
  1173. return scope.Escape(
  1174. New(node::Buffer::New(data, size, FreeData, NULL)->handle_));
  1175. }
  1176. namespace imp {
  1177. inline void
  1178. widenString(std::vector<uint16_t> *ws, const uint8_t *s, int l) {
  1179. size_t len = static_cast<size_t>(l);
  1180. if (l < 0) {
  1181. len = strlen(reinterpret_cast<const char*>(s));
  1182. }
  1183. assert(len <= INT_MAX && "string too long");
  1184. ws->resize(len);
  1185. std::copy(s, s + len, ws->begin()); // NOLINT(build/include_what_you_use)
  1186. }
  1187. } // end of namespace imp
  1188. inline MaybeLocal<v8::String>
  1189. NewOneByteString(const uint8_t * value, int length = -1) {
  1190. std::vector<uint16_t> wideString; // NOLINT(build/include_what_you_use)
  1191. imp::widenString(&wideString, value, length);
  1192. return v8::String::New(wideString.data(),
  1193. static_cast<int>(wideString.size()));
  1194. }
  1195. inline MaybeLocal<BoundScript> CompileScript(
  1196. v8::Local<v8::String> s
  1197. , const v8::ScriptOrigin& origin
  1198. ) {
  1199. return v8::Script::Compile(s, const_cast<v8::ScriptOrigin *>(&origin));
  1200. }
  1201. inline MaybeLocal<BoundScript> CompileScript(
  1202. v8::Local<v8::String> s
  1203. ) {
  1204. return v8::Script::Compile(s);
  1205. }
  1206. inline
  1207. MaybeLocal<v8::Value> RunScript(v8::Local<v8::Script> script) {
  1208. return script->Run();
  1209. }
  1210. inline v8::Local<v8::Value> MakeCallback(
  1211. v8::Local<v8::Object> target
  1212. , v8::Local<v8::Function> func
  1213. , int argc
  1214. , v8::Local<v8::Value>* argv) {
  1215. v8::HandleScope scope;
  1216. return scope.Close(New(node::MakeCallback(target, func, argc, argv)));
  1217. }
  1218. inline v8::Local<v8::Value> MakeCallback(
  1219. v8::Local<v8::Object> target
  1220. , v8::Local<v8::String> symbol
  1221. , int argc
  1222. , v8::Local<v8::Value>* argv) {
  1223. v8::HandleScope scope;
  1224. return scope.Close(New(node::MakeCallback(target, symbol, argc, argv)));
  1225. }
  1226. inline v8::Local<v8::Value> MakeCallback(
  1227. v8::Local<v8::Object> target
  1228. , const char* method
  1229. , int argc
  1230. , v8::Local<v8::Value>* argv) {
  1231. v8::HandleScope scope;
  1232. return scope.Close(New(node::MakeCallback(target, method, argc, argv)));
  1233. }
  1234. inline void FatalException(const TryCatch& try_catch) {
  1235. node::FatalException(const_cast<v8::TryCatch &>(try_catch.try_catch_));
  1236. }
  1237. inline v8::Local<v8::Value> ErrnoException(
  1238. int errorno
  1239. , const char* syscall = NULL
  1240. , const char* message = NULL
  1241. , const char* path = NULL) {
  1242. return node::ErrnoException(errorno, syscall, message, path);
  1243. }
  1244. NAN_DEPRECATED inline v8::Local<v8::Value> NanErrnoException(
  1245. int errorno
  1246. , const char* syscall = NULL
  1247. , const char* message = NULL
  1248. , const char* path = NULL) {
  1249. return ErrnoException(errorno, syscall, message, path);
  1250. }
  1251. template<typename T>
  1252. inline void SetIsolateData(
  1253. v8::Isolate *isolate
  1254. , T *data
  1255. ) {
  1256. isolate->SetData(data);
  1257. }
  1258. template<typename T>
  1259. inline T *GetIsolateData(
  1260. v8::Isolate *isolate
  1261. ) {
  1262. return static_cast<T*>(isolate->GetData());
  1263. }
  1264. class Utf8String {
  1265. public:
  1266. inline explicit Utf8String(v8::Local<v8::Value> from) :
  1267. length_(0), str_(str_st_) {
  1268. v8::HandleScope scope;
  1269. if (!from.IsEmpty()) {
  1270. v8::Local<v8::String> string = from->ToString();
  1271. if (!string.IsEmpty()) {
  1272. size_t len = 3 * string->Length() + 1;
  1273. assert(len <= INT_MAX);
  1274. if (len > sizeof (str_st_)) {
  1275. str_ = static_cast<char*>(malloc(len));
  1276. assert(str_ != 0);
  1277. }
  1278. const int flags =
  1279. v8::String::NO_NULL_TERMINATION | imp::kReplaceInvalidUtf8;
  1280. length_ = string->WriteUtf8(str_, static_cast<int>(len), 0, flags);
  1281. str_[length_] = '\0';
  1282. }
  1283. }
  1284. }
  1285. inline int length() const {
  1286. return length_;
  1287. }
  1288. inline char* operator*() { return str_; }
  1289. inline const char* operator*() const { return str_; }
  1290. inline ~Utf8String() {
  1291. if (str_ != str_st_) {
  1292. free(str_);
  1293. }
  1294. }
  1295. private:
  1296. NAN_DISALLOW_ASSIGN_COPY_MOVE(Utf8String)
  1297. int length_;
  1298. char *str_;
  1299. char str_st_[1024];
  1300. };
  1301. #endif // NODE_MODULE_VERSION
  1302. typedef void (*FreeCallback)(char *data, void *hint);
  1303. typedef const FunctionCallbackInfo<v8::Value>& NAN_METHOD_ARGS_TYPE;
  1304. typedef void NAN_METHOD_RETURN_TYPE;
  1305. typedef const PropertyCallbackInfo<v8::Value>& NAN_GETTER_ARGS_TYPE;
  1306. typedef void NAN_GETTER_RETURN_TYPE;
  1307. typedef const PropertyCallbackInfo<void>& NAN_SETTER_ARGS_TYPE;
  1308. typedef void NAN_SETTER_RETURN_TYPE;
  1309. typedef const PropertyCallbackInfo<v8::Value>&
  1310. NAN_PROPERTY_GETTER_ARGS_TYPE;
  1311. typedef void NAN_PROPERTY_GETTER_RETURN_TYPE;
  1312. typedef const PropertyCallbackInfo<v8::Value>&
  1313. NAN_PROPERTY_SETTER_ARGS_TYPE;
  1314. typedef void NAN_PROPERTY_SETTER_RETURN_TYPE;
  1315. typedef const PropertyCallbackInfo<v8::Array>&
  1316. NAN_PROPERTY_ENUMERATOR_ARGS_TYPE;
  1317. typedef void NAN_PROPERTY_ENUMERATOR_RETURN_TYPE;
  1318. typedef const PropertyCallbackInfo<v8::Boolean>&
  1319. NAN_PROPERTY_DELETER_ARGS_TYPE;
  1320. typedef void NAN_PROPERTY_DELETER_RETURN_TYPE;
  1321. typedef const PropertyCallbackInfo<v8::Integer>&
  1322. NAN_PROPERTY_QUERY_ARGS_TYPE;
  1323. typedef void NAN_PROPERTY_QUERY_RETURN_TYPE;
  1324. typedef const PropertyCallbackInfo<v8::Value>& NAN_INDEX_GETTER_ARGS_TYPE;
  1325. typedef void NAN_INDEX_GETTER_RETURN_TYPE;
  1326. typedef const PropertyCallbackInfo<v8::Value>& NAN_INDEX_SETTER_ARGS_TYPE;
  1327. typedef void NAN_INDEX_SETTER_RETURN_TYPE;
  1328. typedef const PropertyCallbackInfo<v8::Array>&
  1329. NAN_INDEX_ENUMERATOR_ARGS_TYPE;
  1330. typedef void NAN_INDEX_ENUMERATOR_RETURN_TYPE;
  1331. typedef const PropertyCallbackInfo<v8::Boolean>&
  1332. NAN_INDEX_DELETER_ARGS_TYPE;
  1333. typedef void NAN_INDEX_DELETER_RETURN_TYPE;
  1334. typedef const PropertyCallbackInfo<v8::Integer>&
  1335. NAN_INDEX_QUERY_ARGS_TYPE;
  1336. typedef void NAN_INDEX_QUERY_RETURN_TYPE;
  1337. #define NAN_METHOD(name) \
  1338. Nan::NAN_METHOD_RETURN_TYPE name(Nan::NAN_METHOD_ARGS_TYPE info)
  1339. #define NAN_GETTER(name) \
  1340. Nan::NAN_GETTER_RETURN_TYPE name( \
  1341. v8::Local<v8::String> property \
  1342. , Nan::NAN_GETTER_ARGS_TYPE info)
  1343. #define NAN_SETTER(name) \
  1344. Nan::NAN_SETTER_RETURN_TYPE name( \
  1345. v8::Local<v8::String> property \
  1346. , v8::Local<v8::Value> value \
  1347. , Nan::NAN_SETTER_ARGS_TYPE info)
  1348. #define NAN_PROPERTY_GETTER(name) \
  1349. Nan::NAN_PROPERTY_GETTER_RETURN_TYPE name( \
  1350. v8::Local<v8::String> property \
  1351. , Nan::NAN_PROPERTY_GETTER_ARGS_TYPE info)
  1352. #define NAN_PROPERTY_SETTER(name) \
  1353. Nan::NAN_PROPERTY_SETTER_RETURN_TYPE name( \
  1354. v8::Local<v8::String> property \
  1355. , v8::Local<v8::Value> value \
  1356. , Nan::NAN_PROPERTY_SETTER_ARGS_TYPE info)
  1357. #define NAN_PROPERTY_ENUMERATOR(name) \
  1358. Nan::NAN_PROPERTY_ENUMERATOR_RETURN_TYPE name( \
  1359. Nan::NAN_PROPERTY_ENUMERATOR_ARGS_TYPE info)
  1360. #define NAN_PROPERTY_DELETER(name) \
  1361. Nan::NAN_PROPERTY_DELETER_RETURN_TYPE name( \
  1362. v8::Local<v8::String> property \
  1363. , Nan::NAN_PROPERTY_DELETER_ARGS_TYPE info)
  1364. #define NAN_PROPERTY_QUERY(name) \
  1365. Nan::NAN_PROPERTY_QUERY_RETURN_TYPE name( \
  1366. v8::Local<v8::String> property \
  1367. , Nan::NAN_PROPERTY_QUERY_ARGS_TYPE info)
  1368. # define NAN_INDEX_GETTER(name) \
  1369. Nan::NAN_INDEX_GETTER_RETURN_TYPE name( \
  1370. uint32_t index \
  1371. , Nan::NAN_INDEX_GETTER_ARGS_TYPE info)
  1372. #define NAN_INDEX_SETTER(name) \
  1373. Nan::NAN_INDEX_SETTER_RETURN_TYPE name( \
  1374. uint32_t index \
  1375. , v8::Local<v8::Value> value \
  1376. , Nan::NAN_INDEX_SETTER_ARGS_TYPE info)
  1377. #define NAN_INDEX_ENUMERATOR(name) \
  1378. Nan::NAN_INDEX_ENUMERATOR_RETURN_TYPE \
  1379. name(Nan::NAN_INDEX_ENUMERATOR_ARGS_TYPE info)
  1380. #define NAN_INDEX_DELETER(name) \
  1381. Nan::NAN_INDEX_DELETER_RETURN_TYPE name( \
  1382. uint32_t index \
  1383. , Nan::NAN_INDEX_DELETER_ARGS_TYPE info)
  1384. #define NAN_INDEX_QUERY(name) \
  1385. Nan::NAN_INDEX_QUERY_RETURN_TYPE name( \
  1386. uint32_t index \
  1387. , Nan::NAN_INDEX_QUERY_ARGS_TYPE info)
  1388. class Callback {
  1389. public:
  1390. Callback() {}
  1391. explicit Callback(const v8::Local<v8::Function> &fn) : handle_(fn) {}
  1392. ~Callback() {
  1393. handle_.Reset();
  1394. }
  1395. bool operator==(const Callback &other) const {
  1396. return handle_ == other.handle_;
  1397. }
  1398. bool operator!=(const Callback &other) const {
  1399. return !operator==(other);
  1400. }
  1401. inline
  1402. v8::Local<v8::Function> operator*() const { return GetFunction(); }
  1403. NAN_DEPRECATED inline v8::Local<v8::Value> operator()(
  1404. v8::Local<v8::Object> target
  1405. , int argc = 0
  1406. , v8::Local<v8::Value> argv[] = 0) const {
  1407. #if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
  1408. v8::Isolate *isolate = v8::Isolate::GetCurrent();
  1409. # if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  1410. AsyncResource async("nan:Callback:operator()");
  1411. return Call_(isolate, target, argc, argv, &async)
  1412. .FromMaybe(v8::Local<v8::Value>());
  1413. # else
  1414. return Call_(isolate, target, argc, argv);
  1415. # endif // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  1416. #else
  1417. return Call_(target, argc, argv);
  1418. #endif // NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
  1419. }
  1420. NAN_DEPRECATED inline v8::Local<v8::Value> operator()(
  1421. int argc = 0
  1422. , v8::Local<v8::Value> argv[] = 0) const {
  1423. #if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
  1424. v8::Isolate *isolate = v8::Isolate::GetCurrent();
  1425. v8::EscapableHandleScope scope(isolate);
  1426. # if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  1427. AsyncResource async("nan:Callback:operator()");
  1428. return scope.Escape(Call_(isolate, isolate->GetCurrentContext()->Global(),
  1429. argc, argv, &async)
  1430. .FromMaybe(v8::Local<v8::Value>()));
  1431. # else
  1432. return scope.Escape(
  1433. Call_(isolate, isolate->GetCurrentContext()->Global(), argc, argv));
  1434. # endif // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  1435. #else
  1436. v8::HandleScope scope;
  1437. return scope.Close(Call_(v8::Context::GetCurrent()->Global(), argc, argv));
  1438. #endif // NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
  1439. }
  1440. inline MaybeLocal<v8::Value> operator()(
  1441. AsyncResource* resource
  1442. , int argc = 0
  1443. , v8::Local<v8::Value> argv[] = 0) const {
  1444. return this->Call(argc, argv, resource);
  1445. }
  1446. inline MaybeLocal<v8::Value> operator()(
  1447. AsyncResource* resource
  1448. , v8::Local<v8::Object> target
  1449. , int argc = 0
  1450. , v8::Local<v8::Value> argv[] = 0) const {
  1451. return this->Call(target, argc, argv, resource);
  1452. }
  1453. // TODO(kkoopa): remove
  1454. inline void SetFunction(const v8::Local<v8::Function> &fn) {
  1455. Reset(fn);
  1456. }
  1457. inline void Reset(const v8::Local<v8::Function> &fn) {
  1458. handle_.Reset(fn);
  1459. }
  1460. inline void Reset() {
  1461. handle_.Reset();
  1462. }
  1463. inline v8::Local<v8::Function> GetFunction() const {
  1464. return New(handle_);
  1465. }
  1466. inline bool IsEmpty() const {
  1467. return handle_.IsEmpty();
  1468. }
  1469. // Deprecated: For async callbacks Use the versions that accept an
  1470. // AsyncResource. If this callback does not correspond to an async resource,
  1471. // that is, it is a synchronous function call on a non-empty JS stack, you
  1472. // should Nan::Call instead.
  1473. NAN_DEPRECATED inline v8::Local<v8::Value>
  1474. Call(v8::Local<v8::Object> target
  1475. , int argc
  1476. , v8::Local<v8::Value> argv[]) const {
  1477. #if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
  1478. v8::Isolate *isolate = v8::Isolate::GetCurrent();
  1479. # if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  1480. AsyncResource async("nan:Callback:Call");
  1481. return Call_(isolate, target, argc, argv, &async)
  1482. .FromMaybe(v8::Local<v8::Value>());
  1483. # else
  1484. return Call_(isolate, target, argc, argv);
  1485. # endif // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  1486. #else
  1487. return Call_(target, argc, argv);
  1488. #endif
  1489. }
  1490. // Deprecated: For async callbacks Use the versions that accept an
  1491. // AsyncResource. If this callback does not correspond to an async resource,
  1492. // that is, it is a synchronous function call on a non-empty JS stack, you
  1493. // should Nan::Call instead.
  1494. NAN_DEPRECATED inline v8::Local<v8::Value>
  1495. Call(int argc, v8::Local<v8::Value> argv[]) const {
  1496. #if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
  1497. v8::Isolate *isolate = v8::Isolate::GetCurrent();
  1498. v8::EscapableHandleScope scope(isolate);
  1499. # if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  1500. AsyncResource async("nan:Callback:Call");
  1501. return scope.Escape(Call_(isolate, isolate->GetCurrentContext()->Global(),
  1502. argc, argv, &async)
  1503. .FromMaybe(v8::Local<v8::Value>()));
  1504. # else
  1505. return scope.Escape(
  1506. Call_(isolate, isolate->GetCurrentContext()->Global(), argc, argv));
  1507. # endif // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  1508. #else
  1509. v8::HandleScope scope;
  1510. return scope.Close(Call_(v8::Context::GetCurrent()->Global(), argc, argv));
  1511. #endif
  1512. }
  1513. inline MaybeLocal<v8::Value>
  1514. Call(v8::Local<v8::Object> target
  1515. , int argc
  1516. , v8::Local<v8::Value> argv[]
  1517. , AsyncResource* resource) const {
  1518. #if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  1519. v8::Isolate* isolate = v8::Isolate::GetCurrent();
  1520. return Call_(isolate, target, argc, argv, resource);
  1521. #elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
  1522. v8::Isolate *isolate = v8::Isolate::GetCurrent();
  1523. return Call_(isolate, target, argc, argv);
  1524. #else
  1525. return Call_(target, argc, argv);
  1526. #endif
  1527. }
  1528. inline MaybeLocal<v8::Value>
  1529. Call(int argc, v8::Local<v8::Value> argv[], AsyncResource* resource) const {
  1530. #if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  1531. v8::Isolate* isolate = v8::Isolate::GetCurrent();
  1532. return Call(isolate->GetCurrentContext()->Global(), argc, argv, resource);
  1533. #elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
  1534. v8::Isolate *isolate = v8::Isolate::GetCurrent();
  1535. v8::EscapableHandleScope scope(isolate);
  1536. return scope.Escape(
  1537. Call_(isolate, isolate->GetCurrentContext()->Global(), argc, argv));
  1538. #else
  1539. v8::HandleScope scope;
  1540. return scope.Close(Call_(v8::Context::GetCurrent()->Global(), argc, argv));
  1541. #endif
  1542. }
  1543. private:
  1544. NAN_DISALLOW_ASSIGN_COPY_MOVE(Callback)
  1545. Persistent<v8::Function> handle_;
  1546. #if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
  1547. MaybeLocal<v8::Value> Call_(v8::Isolate *isolate
  1548. , v8::Local<v8::Object> target
  1549. , int argc
  1550. , v8::Local<v8::Value> argv[]
  1551. , AsyncResource* resource) const {
  1552. EscapableHandleScope scope;
  1553. v8::Local<v8::Function> func = New(handle_);
  1554. auto maybe = resource->runInAsyncScope(target, func, argc, argv);
  1555. v8::Local<v8::Value> local;
  1556. if (!maybe.ToLocal(&local)) return MaybeLocal<v8::Value>();
  1557. return scope.Escape(local);
  1558. }
  1559. #elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
  1560. v8::Local<v8::Value> Call_(v8::Isolate *isolate
  1561. , v8::Local<v8::Object> target
  1562. , int argc
  1563. , v8::Local<v8::Value> argv[]) const {
  1564. EscapableHandleScope scope;
  1565. v8::Local<v8::Function> callback = New(handle_);
  1566. # if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
  1567. return scope.Escape(New(node::MakeCallback(
  1568. isolate
  1569. , target
  1570. , callback
  1571. , argc
  1572. , argv
  1573. )));
  1574. # else
  1575. return scope.Escape(node::MakeCallback(
  1576. isolate
  1577. , target
  1578. , callback
  1579. , argc
  1580. , argv
  1581. ));
  1582. # endif
  1583. }
  1584. #else
  1585. v8::Local<v8::Value> Call_(v8::Local<v8::Object> target
  1586. , int argc
  1587. , v8::Local<v8::Value> argv[]) const {
  1588. EscapableHandleScope scope;
  1589. v8::Local<v8::Function> callback = New(handle_);
  1590. return scope.Escape(New(node::MakeCallback(
  1591. target
  1592. , callback
  1593. , argc
  1594. , argv
  1595. )));
  1596. }
  1597. #endif
  1598. };
  1599. inline MaybeLocal<v8::Value> Call(
  1600. const Nan::Callback& callback
  1601. , v8::Local<v8::Object> recv
  1602. , int argc
  1603. , v8::Local<v8::Value> argv[]) {
  1604. return Call(*callback, recv, argc, argv);
  1605. }
  1606. inline MaybeLocal<v8::Value> Call(
  1607. const Nan::Callback& callback
  1608. , int argc
  1609. , v8::Local<v8::Value> argv[]) {
  1610. #if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
  1611. v8::Isolate* isolate = v8::Isolate::GetCurrent();
  1612. v8::EscapableHandleScope scope(isolate);
  1613. return scope.Escape(
  1614. Call(*callback, isolate->GetCurrentContext()->Global(), argc, argv)
  1615. .FromMaybe(v8::Local<v8::Value>()));
  1616. #else
  1617. EscapableHandleScope scope;
  1618. return scope.Escape(
  1619. Call(*callback, v8::Context::GetCurrent()->Global(), argc, argv)
  1620. .FromMaybe(v8::Local<v8::Value>()));
  1621. #endif
  1622. }
  1623. inline MaybeLocal<v8::Value> Call(
  1624. v8::Local<v8::String> symbol
  1625. , v8::Local<v8::Object> recv
  1626. , int argc
  1627. , v8::Local<v8::Value> argv[]) {
  1628. EscapableHandleScope scope;
  1629. v8::Local<v8::Value> fn_v =
  1630. Get(recv, symbol).FromMaybe(v8::Local<v8::Value>());
  1631. if (fn_v.IsEmpty() || !fn_v->IsFunction()) return v8::Local<v8::Value>();
  1632. v8::Local<v8::Function> fn = fn_v.As<v8::Function>();
  1633. return scope.Escape(
  1634. Call(fn, recv, argc, argv).FromMaybe(v8::Local<v8::Value>()));
  1635. }
  1636. inline MaybeLocal<v8::Value> Call(
  1637. const char* method
  1638. , v8::Local<v8::Object> recv
  1639. , int argc
  1640. , v8::Local<v8::Value> argv[]) {
  1641. EscapableHandleScope scope;
  1642. v8::Local<v8::String> method_string =
  1643. New<v8::String>(method).ToLocalChecked();
  1644. return scope.Escape(
  1645. Call(method_string, recv, argc, argv).FromMaybe(v8::Local<v8::Value>()));
  1646. }
  1647. /* abstract */ class AsyncWorker {
  1648. public:
  1649. explicit AsyncWorker(Callback *callback_,
  1650. const char* resource_name = "nan:AsyncWorker")
  1651. : callback(callback_), errmsg_(NULL) {
  1652. request.data = this;
  1653. HandleScope scope;
  1654. v8::Local<v8::Object> obj = New<v8::Object>();
  1655. persistentHandle.Reset(obj);
  1656. async_resource = new AsyncResource(resource_name, obj);
  1657. }
  1658. virtual ~AsyncWorker() {
  1659. HandleScope scope;
  1660. if (!persistentHandle.IsEmpty())
  1661. persistentHandle.Reset();
  1662. delete callback;
  1663. delete[] errmsg_;
  1664. delete async_resource;
  1665. }
  1666. virtual void WorkComplete() {
  1667. HandleScope scope;
  1668. if (errmsg_ == NULL)
  1669. HandleOKCallback();
  1670. else
  1671. HandleErrorCallback();
  1672. delete callback;
  1673. callback = NULL;
  1674. }
  1675. inline void SaveToPersistent(
  1676. const char *key, const v8::Local<v8::Value> &value) {
  1677. HandleScope scope;
  1678. Set(New(persistentHandle), New(key).ToLocalChecked(), value).FromJust();
  1679. }
  1680. inline void SaveToPersistent(
  1681. const v8::Local<v8::String> &key, const v8::Local<v8::Value> &value) {
  1682. HandleScope scope;
  1683. Set(New(persistentHandle), key, value).FromJust();
  1684. }
  1685. inline void SaveToPersistent(
  1686. uint32_t index, const v8::Local<v8::Value> &value) {
  1687. HandleScope scope;
  1688. Set(New(persistentHandle), index, value).FromJust();
  1689. }
  1690. inline v8::Local<v8::Value> GetFromPersistent(const char *key) const {
  1691. EscapableHandleScope scope;
  1692. return scope.Escape(
  1693. Get(New(persistentHandle), New(key).ToLocalChecked())
  1694. .FromMaybe(v8::Local<v8::Value>()));
  1695. }
  1696. inline v8::Local<v8::Value>
  1697. GetFromPersistent(const v8::Local<v8::String> &key) const {
  1698. EscapableHandleScope scope;
  1699. return scope.Escape(
  1700. Get(New(persistentHandle), key)
  1701. .FromMaybe(v8::Local<v8::Value>()));
  1702. }
  1703. inline v8::Local<v8::Value> GetFromPersistent(uint32_t index) const {
  1704. EscapableHandleScope scope;
  1705. return scope.Escape(
  1706. Get(New(persistentHandle), index)
  1707. .FromMaybe(v8::Local<v8::Value>()));
  1708. }
  1709. virtual void Execute() = 0;
  1710. uv_work_t request;
  1711. virtual void Destroy() {
  1712. delete this;
  1713. }
  1714. protected:
  1715. Persistent<v8::Object> persistentHandle;
  1716. Callback *callback;
  1717. AsyncResource *async_resource;
  1718. virtual void HandleOKCallback() {
  1719. HandleScope scope;
  1720. callback->Call(0, NULL, async_resource);
  1721. }
  1722. virtual void HandleErrorCallback() {
  1723. HandleScope scope;
  1724. v8::Local<v8::Value> argv[] = {
  1725. v8::Exception::Error(New<v8::String>(ErrorMessage()).ToLocalChecked())
  1726. };
  1727. callback->Call(1, argv, async_resource);
  1728. }
  1729. void SetErrorMessage(const char *msg) {
  1730. delete[] errmsg_;
  1731. size_t size = strlen(msg) + 1;
  1732. errmsg_ = new char[size];
  1733. memcpy(errmsg_, msg, size);
  1734. }
  1735. const char* ErrorMessage() const {
  1736. return errmsg_;
  1737. }
  1738. private:
  1739. NAN_DISALLOW_ASSIGN_COPY_MOVE(AsyncWorker)
  1740. char *errmsg_;
  1741. };
  1742. /* abstract */ class AsyncBareProgressWorkerBase : public AsyncWorker {
  1743. public:
  1744. explicit AsyncBareProgressWorkerBase(
  1745. Callback *callback_,
  1746. const char* resource_name = "nan:AsyncBareProgressWorkerBase")
  1747. : AsyncWorker(callback_, resource_name) {
  1748. uv_async_init(
  1749. GetCurrentEventLoop()
  1750. , &async
  1751. , AsyncProgress_
  1752. );
  1753. async.data = this;
  1754. }
  1755. virtual ~AsyncBareProgressWorkerBase() {
  1756. }
  1757. virtual void WorkProgress() = 0;
  1758. virtual void Destroy() {
  1759. uv_close(reinterpret_cast<uv_handle_t*>(&async), AsyncClose_);
  1760. }
  1761. private:
  1762. inline static NAUV_WORK_CB(AsyncProgress_) {
  1763. AsyncBareProgressWorkerBase *worker =
  1764. static_cast<AsyncBareProgressWorkerBase*>(async->data);
  1765. worker->WorkProgress();
  1766. }
  1767. inline static void AsyncClose_(uv_handle_t* handle) {
  1768. AsyncBareProgressWorkerBase *worker =
  1769. static_cast<AsyncBareProgressWorkerBase*>(handle->data);
  1770. delete worker;
  1771. }
  1772. protected:
  1773. uv_async_t async;
  1774. };
  1775. template<class T>
  1776. /* abstract */
  1777. class AsyncBareProgressWorker : public AsyncBareProgressWorkerBase {
  1778. public:
  1779. explicit AsyncBareProgressWorker(
  1780. Callback *callback_,
  1781. const char* resource_name = "nan:AsyncBareProgressWorker")
  1782. : AsyncBareProgressWorkerBase(callback_, resource_name) {
  1783. uv_mutex_init(&async_lock);
  1784. }
  1785. virtual ~AsyncBareProgressWorker() {
  1786. uv_mutex_destroy(&async_lock);
  1787. }
  1788. class ExecutionProgress {
  1789. friend class AsyncBareProgressWorker;
  1790. public:
  1791. void Signal() const {
  1792. uv_mutex_lock(&that_->async_lock);
  1793. uv_async_send(&that_->async);
  1794. uv_mutex_unlock(&that_->async_lock);
  1795. }
  1796. void Send(const T* data, size_t count) const {
  1797. that_->SendProgress_(data, count);
  1798. }
  1799. private:
  1800. explicit ExecutionProgress(AsyncBareProgressWorker *that) : that_(that) {}
  1801. NAN_DISALLOW_ASSIGN_COPY_MOVE(ExecutionProgress)
  1802. AsyncBareProgressWorker* const that_;
  1803. };
  1804. virtual void Execute(const ExecutionProgress& progress) = 0;
  1805. virtual void HandleProgressCallback(const T *data, size_t size) = 0;
  1806. protected:
  1807. uv_mutex_t async_lock;
  1808. private:
  1809. void Execute() /*final override*/ {
  1810. ExecutionProgress progress(this);
  1811. Execute(progress);
  1812. }
  1813. virtual void SendProgress_(const T *data, size_t count) = 0;
  1814. };
  1815. template<class T>
  1816. /* abstract */
  1817. class AsyncProgressWorkerBase : public AsyncBareProgressWorker<T> {
  1818. public:
  1819. explicit AsyncProgressWorkerBase(
  1820. Callback *callback_,
  1821. const char* resource_name = "nan:AsyncProgressWorkerBase")
  1822. : AsyncBareProgressWorker<T>(callback_, resource_name), asyncdata_(NULL),
  1823. asyncsize_(0) {
  1824. }
  1825. virtual ~AsyncProgressWorkerBase() {
  1826. delete[] asyncdata_;
  1827. }
  1828. void WorkProgress() {
  1829. uv_mutex_lock(&this->async_lock);
  1830. T *data = asyncdata_;
  1831. size_t size = asyncsize_;
  1832. asyncdata_ = NULL;
  1833. asyncsize_ = 0;
  1834. uv_mutex_unlock(&this->async_lock);
  1835. // Don't send progress events after we've already completed.
  1836. if (this->callback) {
  1837. this->HandleProgressCallback(data, size);
  1838. }
  1839. delete[] data;
  1840. }
  1841. private:
  1842. void SendProgress_(const T *data, size_t count) {
  1843. T *new_data = new T[count];
  1844. {
  1845. T *it = new_data;
  1846. std::copy(data, data + count, it);
  1847. }
  1848. uv_mutex_lock(&this->async_lock);
  1849. T *old_data = asyncdata_;
  1850. asyncdata_ = new_data;
  1851. asyncsize_ = count;
  1852. uv_async_send(&this->async);
  1853. uv_mutex_unlock(&this->async_lock);
  1854. delete[] old_data;
  1855. }
  1856. T *asyncdata_;
  1857. size_t asyncsize_;
  1858. };
  1859. // This ensures compatibility to the previous un-templated AsyncProgressWorker
  1860. // class definition.
  1861. typedef AsyncProgressWorkerBase<char> AsyncProgressWorker;
  1862. template<class T>
  1863. /* abstract */
  1864. class AsyncBareProgressQueueWorker : public AsyncBareProgressWorkerBase {
  1865. public:
  1866. explicit AsyncBareProgressQueueWorker(
  1867. Callback *callback_,
  1868. const char* resource_name = "nan:AsyncBareProgressQueueWorker")
  1869. : AsyncBareProgressWorkerBase(callback_, resource_name) {
  1870. }
  1871. virtual ~AsyncBareProgressQueueWorker() {
  1872. }
  1873. class ExecutionProgress {
  1874. friend class AsyncBareProgressQueueWorker;
  1875. public:
  1876. void Send(const T* data, size_t count) const {
  1877. that_->SendProgress_(data, count);
  1878. }
  1879. private:
  1880. explicit ExecutionProgress(AsyncBareProgressQueueWorker *that)
  1881. : that_(that) {}
  1882. NAN_DISALLOW_ASSIGN_COPY_MOVE(ExecutionProgress)
  1883. AsyncBareProgressQueueWorker* const that_;
  1884. };
  1885. virtual void Execute(const ExecutionProgress& progress) = 0;
  1886. virtual void HandleProgressCallback(const T *data, size_t size) = 0;
  1887. private:
  1888. void Execute() /*final override*/ {
  1889. ExecutionProgress progress(this);
  1890. Execute(progress);
  1891. }
  1892. virtual void SendProgress_(const T *data, size_t count) = 0;
  1893. };
  1894. template<class T>
  1895. /* abstract */
  1896. class AsyncProgressQueueWorker : public AsyncBareProgressQueueWorker<T> {
  1897. public:
  1898. explicit AsyncProgressQueueWorker(
  1899. Callback *callback_,
  1900. const char* resource_name = "nan:AsyncProgressQueueWorker")
  1901. : AsyncBareProgressQueueWorker<T>(callback_) {
  1902. uv_mutex_init(&async_lock);
  1903. }
  1904. virtual ~AsyncProgressQueueWorker() {
  1905. uv_mutex_lock(&async_lock);
  1906. while (!asyncdata_.empty()) {
  1907. std::pair<T*, size_t> &datapair = asyncdata_.front();
  1908. T *data = datapair.first;
  1909. asyncdata_.pop();
  1910. delete[] data;
  1911. }
  1912. uv_mutex_unlock(&async_lock);
  1913. uv_mutex_destroy(&async_lock);
  1914. }
  1915. void WorkComplete() {
  1916. WorkProgress();
  1917. AsyncWorker::WorkComplete();
  1918. }
  1919. void WorkProgress() {
  1920. uv_mutex_lock(&async_lock);
  1921. while (!asyncdata_.empty()) {
  1922. std::pair<T*, size_t> &datapair = asyncdata_.front();
  1923. T *data = datapair.first;
  1924. size_t size = datapair.second;
  1925. asyncdata_.pop();
  1926. uv_mutex_unlock(&async_lock);
  1927. // Don't send progress events after we've already completed.
  1928. if (this->callback) {
  1929. this->HandleProgressCallback(data, size);
  1930. }
  1931. delete[] data;
  1932. uv_mutex_lock(&async_lock);
  1933. }
  1934. uv_mutex_unlock(&async_lock);
  1935. }
  1936. private:
  1937. void SendProgress_(const T *data, size_t count) {
  1938. T *new_data = new T[count];
  1939. {
  1940. T *it = new_data;
  1941. std::copy(data, data + count, it);
  1942. }
  1943. uv_mutex_lock(&async_lock);
  1944. asyncdata_.push(std::pair<T*, size_t>(new_data, count));
  1945. uv_mutex_unlock(&async_lock);
  1946. uv_async_send(&this->async);
  1947. }
  1948. uv_mutex_t async_lock;
  1949. std::queue<std::pair<T*, size_t> > asyncdata_;
  1950. };
  1951. inline void AsyncExecute (uv_work_t* req) {
  1952. AsyncWorker *worker = static_cast<AsyncWorker*>(req->data);
  1953. worker->Execute();
  1954. }
  1955. inline void AsyncExecuteComplete (uv_work_t* req) {
  1956. AsyncWorker* worker = static_cast<AsyncWorker*>(req->data);
  1957. worker->WorkComplete();
  1958. worker->Destroy();
  1959. }
  1960. inline void AsyncQueueWorker (AsyncWorker* worker) {
  1961. uv_queue_work(
  1962. GetCurrentEventLoop()
  1963. , &worker->request
  1964. , AsyncExecute
  1965. , reinterpret_cast<uv_after_work_cb>(AsyncExecuteComplete)
  1966. );
  1967. }
  1968. namespace imp {
  1969. inline
  1970. ExternalOneByteStringResource const*
  1971. GetExternalResource(v8::Local<v8::String> str) {
  1972. #if NODE_MODULE_VERSION < ATOM_0_21_MODULE_VERSION
  1973. return str->GetExternalAsciiStringResource();
  1974. #else
  1975. return str->GetExternalOneByteStringResource();
  1976. #endif
  1977. }
  1978. inline
  1979. bool
  1980. IsExternal(v8::Local<v8::String> str) {
  1981. #if NODE_MODULE_VERSION < ATOM_0_21_MODULE_VERSION
  1982. return str->IsExternalAscii();
  1983. #else
  1984. return str->IsExternalOneByte();
  1985. #endif
  1986. }
  1987. } // end of namespace imp
  1988. enum Encoding {ASCII, UTF8, BASE64, UCS2, BINARY, HEX, BUFFER};
  1989. #if NODE_MODULE_VERSION < NODE_0_10_MODULE_VERSION
  1990. # include "nan_string_bytes.h" // NOLINT(build/include)
  1991. #endif
  1992. inline v8::Local<v8::Value> Encode(
  1993. const void *buf, size_t len, enum Encoding encoding = BINARY) {
  1994. #if (NODE_MODULE_VERSION >= ATOM_0_21_MODULE_VERSION)
  1995. v8::Isolate* isolate = v8::Isolate::GetCurrent();
  1996. node::encoding node_enc = static_cast<node::encoding>(encoding);
  1997. if (encoding == UCS2) {
  1998. return node::Encode(
  1999. isolate
  2000. , reinterpret_cast<const uint16_t *>(buf)
  2001. , len / 2);
  2002. } else {
  2003. return node::Encode(
  2004. isolate
  2005. , reinterpret_cast<const char *>(buf)
  2006. , len
  2007. , node_enc);
  2008. }
  2009. #elif (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION)
  2010. return node::Encode(
  2011. v8::Isolate::GetCurrent()
  2012. , buf, len
  2013. , static_cast<node::encoding>(encoding));
  2014. #else
  2015. # if NODE_MODULE_VERSION >= NODE_0_10_MODULE_VERSION
  2016. return node::Encode(buf, len, static_cast<node::encoding>(encoding));
  2017. # else
  2018. return imp::Encode(reinterpret_cast<const char*>(buf), len, encoding);
  2019. # endif
  2020. #endif
  2021. }
  2022. inline ssize_t DecodeBytes(
  2023. v8::Local<v8::Value> val, enum Encoding encoding = BINARY) {
  2024. #if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION)
  2025. return node::DecodeBytes(
  2026. v8::Isolate::GetCurrent()
  2027. , val
  2028. , static_cast<node::encoding>(encoding));
  2029. #else
  2030. # if (NODE_MODULE_VERSION < NODE_0_10_MODULE_VERSION)
  2031. if (encoding == BUFFER) {
  2032. return node::DecodeBytes(val, node::BINARY);
  2033. }
  2034. # endif
  2035. return node::DecodeBytes(val, static_cast<node::encoding>(encoding));
  2036. #endif
  2037. }
  2038. inline ssize_t DecodeWrite(
  2039. char *buf
  2040. , size_t len
  2041. , v8::Local<v8::Value> val
  2042. , enum Encoding encoding = BINARY) {
  2043. #if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION)
  2044. return node::DecodeWrite(
  2045. v8::Isolate::GetCurrent()
  2046. , buf
  2047. , len
  2048. , val
  2049. , static_cast<node::encoding>(encoding));
  2050. #else
  2051. # if (NODE_MODULE_VERSION < NODE_0_10_MODULE_VERSION)
  2052. if (encoding == BUFFER) {
  2053. return node::DecodeWrite(buf, len, val, node::BINARY);
  2054. }
  2055. # endif
  2056. return node::DecodeWrite(
  2057. buf
  2058. , len
  2059. , val
  2060. , static_cast<node::encoding>(encoding));
  2061. #endif
  2062. }
  2063. inline void SetPrototypeTemplate(
  2064. v8::Local<v8::FunctionTemplate> templ
  2065. , const char *name
  2066. , v8::Local<v8::Data> value
  2067. ) {
  2068. HandleScope scope;
  2069. SetTemplate(templ->PrototypeTemplate(), name, value);
  2070. }
  2071. inline void SetPrototypeTemplate(
  2072. v8::Local<v8::FunctionTemplate> templ
  2073. , v8::Local<v8::String> name
  2074. , v8::Local<v8::Data> value
  2075. , v8::PropertyAttribute attributes
  2076. ) {
  2077. HandleScope scope;
  2078. SetTemplate(templ->PrototypeTemplate(), name, value, attributes);
  2079. }
  2080. inline void SetInstanceTemplate(
  2081. v8::Local<v8::FunctionTemplate> templ
  2082. , const char *name
  2083. , v8::Local<v8::Data> value
  2084. ) {
  2085. HandleScope scope;
  2086. SetTemplate(templ->InstanceTemplate(), name, value);
  2087. }
  2088. inline void SetInstanceTemplate(
  2089. v8::Local<v8::FunctionTemplate> templ
  2090. , v8::Local<v8::String> name
  2091. , v8::Local<v8::Data> value
  2092. , v8::PropertyAttribute attributes
  2093. ) {
  2094. HandleScope scope;
  2095. SetTemplate(templ->InstanceTemplate(), name, value, attributes);
  2096. }
  2097. namespace imp {
  2098. // Note(@agnat): Helper to distinguish different receiver types. The first
  2099. // version deals with receivers derived from v8::Template. The second version
  2100. // handles everything else. The final argument only serves as discriminator and
  2101. // is unused.
  2102. template <typename T>
  2103. inline
  2104. void
  2105. SetMethodAux(T recv,
  2106. v8::Local<v8::String> name,
  2107. v8::Local<v8::FunctionTemplate> tpl,
  2108. v8::Template *) {
  2109. recv->Set(name, tpl);
  2110. }
  2111. template <typename T>
  2112. inline
  2113. void
  2114. SetMethodAux(T recv,
  2115. v8::Local<v8::String> name,
  2116. v8::Local<v8::FunctionTemplate> tpl,
  2117. ...) {
  2118. Set(recv, name, GetFunction(tpl).ToLocalChecked());
  2119. }
  2120. } // end of namespace imp
  2121. template <typename T, template <typename> class HandleType>
  2122. inline void SetMethod(
  2123. HandleType<T> recv
  2124. , const char *name
  2125. , FunctionCallback callback) {
  2126. HandleScope scope;
  2127. v8::Local<v8::FunctionTemplate> t = New<v8::FunctionTemplate>(callback);
  2128. v8::Local<v8::String> fn_name = New(name).ToLocalChecked();
  2129. t->SetClassName(fn_name);
  2130. // Note(@agnat): Pass an empty T* as discriminator. See note on
  2131. // SetMethodAux(...) above
  2132. imp::SetMethodAux(recv, fn_name, t, static_cast<T*>(0));
  2133. }
  2134. inline void SetPrototypeMethod(
  2135. v8::Local<v8::FunctionTemplate> recv
  2136. , const char* name, FunctionCallback callback) {
  2137. HandleScope scope;
  2138. v8::Local<v8::FunctionTemplate> t = New<v8::FunctionTemplate>(
  2139. callback
  2140. , v8::Local<v8::Value>()
  2141. , New<v8::Signature>(recv));
  2142. v8::Local<v8::String> fn_name = New(name).ToLocalChecked();
  2143. recv->PrototypeTemplate()->Set(fn_name, t);
  2144. t->SetClassName(fn_name);
  2145. }
  2146. //=== Accessors and Such =======================================================
  2147. inline void SetAccessor(
  2148. v8::Local<v8::ObjectTemplate> tpl
  2149. , v8::Local<v8::String> name
  2150. , GetterCallback getter
  2151. , SetterCallback setter = 0
  2152. , v8::Local<v8::Value> data = v8::Local<v8::Value>()
  2153. , v8::AccessControl settings = v8::DEFAULT
  2154. , v8::PropertyAttribute attribute = v8::None
  2155. , imp::Sig signature = imp::Sig()) {
  2156. HandleScope scope;
  2157. imp::NativeGetter getter_ =
  2158. imp::GetterCallbackWrapper;
  2159. imp::NativeSetter setter_ =
  2160. setter ? imp::SetterCallbackWrapper : 0;
  2161. v8::Local<v8::ObjectTemplate> otpl = New<v8::ObjectTemplate>();
  2162. otpl->SetInternalFieldCount(imp::kAccessorFieldCount);
  2163. v8::Local<v8::Object> obj = NewInstance(otpl).ToLocalChecked();
  2164. obj->SetInternalField(
  2165. imp::kGetterIndex
  2166. , New<v8::External>(reinterpret_cast<void *>(getter)));
  2167. if (setter != 0) {
  2168. obj->SetInternalField(
  2169. imp::kSetterIndex
  2170. , New<v8::External>(reinterpret_cast<void *>(setter)));
  2171. }
  2172. if (!data.IsEmpty()) {
  2173. obj->SetInternalField(imp::kDataIndex, data);
  2174. }
  2175. tpl->SetAccessor(
  2176. name
  2177. , getter_
  2178. , setter_
  2179. , obj
  2180. , settings
  2181. , attribute
  2182. , signature);
  2183. }
  2184. inline bool SetAccessor(
  2185. v8::Local<v8::Object> obj
  2186. , v8::Local<v8::String> name
  2187. , GetterCallback getter
  2188. , SetterCallback setter = 0
  2189. , v8::Local<v8::Value> data = v8::Local<v8::Value>()
  2190. , v8::AccessControl settings = v8::DEFAULT
  2191. , v8::PropertyAttribute attribute = v8::None) {
  2192. HandleScope scope;
  2193. imp::NativeGetter getter_ =
  2194. imp::GetterCallbackWrapper;
  2195. imp::NativeSetter setter_ =
  2196. setter ? imp::SetterCallbackWrapper : 0;
  2197. v8::Local<v8::ObjectTemplate> otpl = New<v8::ObjectTemplate>();
  2198. otpl->SetInternalFieldCount(imp::kAccessorFieldCount);
  2199. v8::Local<v8::Object> dataobj = NewInstance(otpl).ToLocalChecked();
  2200. dataobj->SetInternalField(
  2201. imp::kGetterIndex
  2202. , New<v8::External>(reinterpret_cast<void *>(getter)));
  2203. if (!data.IsEmpty()) {
  2204. dataobj->SetInternalField(imp::kDataIndex, data);
  2205. }
  2206. if (setter) {
  2207. dataobj->SetInternalField(
  2208. imp::kSetterIndex
  2209. , New<v8::External>(reinterpret_cast<void *>(setter)));
  2210. }
  2211. #if (NODE_MODULE_VERSION >= NODE_6_0_MODULE_VERSION)
  2212. return obj->SetAccessor(
  2213. GetCurrentContext()
  2214. , name
  2215. , getter_
  2216. , setter_
  2217. , dataobj
  2218. , settings
  2219. , attribute).FromMaybe(false);
  2220. #else
  2221. return obj->SetAccessor(
  2222. name
  2223. , getter_
  2224. , setter_
  2225. , dataobj
  2226. , settings
  2227. , attribute);
  2228. #endif
  2229. }
  2230. inline void SetNamedPropertyHandler(
  2231. v8::Local<v8::ObjectTemplate> tpl
  2232. , PropertyGetterCallback getter
  2233. , PropertySetterCallback setter = 0
  2234. , PropertyQueryCallback query = 0
  2235. , PropertyDeleterCallback deleter = 0
  2236. , PropertyEnumeratorCallback enumerator = 0
  2237. , v8::Local<v8::Value> data = v8::Local<v8::Value>()) {
  2238. HandleScope scope;
  2239. imp::NativePropertyGetter getter_ =
  2240. imp::PropertyGetterCallbackWrapper;
  2241. imp::NativePropertySetter setter_ =
  2242. setter ? imp::PropertySetterCallbackWrapper : 0;
  2243. imp::NativePropertyQuery query_ =
  2244. query ? imp::PropertyQueryCallbackWrapper : 0;
  2245. imp::NativePropertyDeleter *deleter_ =
  2246. deleter ? imp::PropertyDeleterCallbackWrapper : 0;
  2247. imp::NativePropertyEnumerator enumerator_ =
  2248. enumerator ? imp::PropertyEnumeratorCallbackWrapper : 0;
  2249. v8::Local<v8::ObjectTemplate> otpl = New<v8::ObjectTemplate>();
  2250. otpl->SetInternalFieldCount(imp::kPropertyFieldCount);
  2251. v8::Local<v8::Object> obj = NewInstance(otpl).ToLocalChecked();
  2252. obj->SetInternalField(
  2253. imp::kPropertyGetterIndex
  2254. , New<v8::External>(reinterpret_cast<void *>(getter)));
  2255. if (setter) {
  2256. obj->SetInternalField(
  2257. imp::kPropertySetterIndex
  2258. , New<v8::External>(reinterpret_cast<void *>(setter)));
  2259. }
  2260. if (query) {
  2261. obj->SetInternalField(
  2262. imp::kPropertyQueryIndex
  2263. , New<v8::External>(reinterpret_cast<void *>(query)));
  2264. }
  2265. if (deleter) {
  2266. obj->SetInternalField(
  2267. imp::kPropertyDeleterIndex
  2268. , New<v8::External>(reinterpret_cast<void *>(deleter)));
  2269. }
  2270. if (enumerator) {
  2271. obj->SetInternalField(
  2272. imp::kPropertyEnumeratorIndex
  2273. , New<v8::External>(reinterpret_cast<void *>(enumerator)));
  2274. }
  2275. if (!data.IsEmpty()) {
  2276. obj->SetInternalField(imp::kDataIndex, data);
  2277. }
  2278. #if NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION
  2279. tpl->SetHandler(v8::NamedPropertyHandlerConfiguration(
  2280. getter_, setter_, query_, deleter_, enumerator_, obj));
  2281. #else
  2282. tpl->SetNamedPropertyHandler(
  2283. getter_
  2284. , setter_
  2285. , query_
  2286. , deleter_
  2287. , enumerator_
  2288. , obj);
  2289. #endif
  2290. }
  2291. inline void SetIndexedPropertyHandler(
  2292. v8::Local<v8::ObjectTemplate> tpl
  2293. , IndexGetterCallback getter
  2294. , IndexSetterCallback setter = 0
  2295. , IndexQueryCallback query = 0
  2296. , IndexDeleterCallback deleter = 0
  2297. , IndexEnumeratorCallback enumerator = 0
  2298. , v8::Local<v8::Value> data = v8::Local<v8::Value>()) {
  2299. HandleScope scope;
  2300. imp::NativeIndexGetter getter_ =
  2301. imp::IndexGetterCallbackWrapper;
  2302. imp::NativeIndexSetter setter_ =
  2303. setter ? imp::IndexSetterCallbackWrapper : 0;
  2304. imp::NativeIndexQuery query_ =
  2305. query ? imp::IndexQueryCallbackWrapper : 0;
  2306. imp::NativeIndexDeleter deleter_ =
  2307. deleter ? imp::IndexDeleterCallbackWrapper : 0;
  2308. imp::NativeIndexEnumerator enumerator_ =
  2309. enumerator ? imp::IndexEnumeratorCallbackWrapper : 0;
  2310. v8::Local<v8::ObjectTemplate> otpl = New<v8::ObjectTemplate>();
  2311. otpl->SetInternalFieldCount(imp::kIndexPropertyFieldCount);
  2312. v8::Local<v8::Object> obj = NewInstance(otpl).ToLocalChecked();
  2313. obj->SetInternalField(
  2314. imp::kIndexPropertyGetterIndex
  2315. , New<v8::External>(reinterpret_cast<void *>(getter)));
  2316. if (setter) {
  2317. obj->SetInternalField(
  2318. imp::kIndexPropertySetterIndex
  2319. , New<v8::External>(reinterpret_cast<void *>(setter)));
  2320. }
  2321. if (query) {
  2322. obj->SetInternalField(
  2323. imp::kIndexPropertyQueryIndex
  2324. , New<v8::External>(reinterpret_cast<void *>(query)));
  2325. }
  2326. if (deleter) {
  2327. obj->SetInternalField(
  2328. imp::kIndexPropertyDeleterIndex
  2329. , New<v8::External>(reinterpret_cast<void *>(deleter)));
  2330. }
  2331. if (enumerator) {
  2332. obj->SetInternalField(
  2333. imp::kIndexPropertyEnumeratorIndex
  2334. , New<v8::External>(reinterpret_cast<void *>(enumerator)));
  2335. }
  2336. if (!data.IsEmpty()) {
  2337. obj->SetInternalField(imp::kDataIndex, data);
  2338. }
  2339. #if NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION
  2340. tpl->SetHandler(v8::IndexedPropertyHandlerConfiguration(
  2341. getter_, setter_, query_, deleter_, enumerator_, obj));
  2342. #else
  2343. tpl->SetIndexedPropertyHandler(
  2344. getter_
  2345. , setter_
  2346. , query_
  2347. , deleter_
  2348. , enumerator_
  2349. , obj);
  2350. #endif
  2351. }
  2352. inline void SetCallHandler(
  2353. v8::Local<v8::FunctionTemplate> tpl
  2354. , FunctionCallback callback
  2355. , v8::Local<v8::Value> data = v8::Local<v8::Value>()) {
  2356. HandleScope scope;
  2357. v8::Local<v8::ObjectTemplate> otpl = New<v8::ObjectTemplate>();
  2358. otpl->SetInternalFieldCount(imp::kFunctionFieldCount);
  2359. v8::Local<v8::Object> obj = NewInstance(otpl).ToLocalChecked();
  2360. obj->SetInternalField(
  2361. imp::kFunctionIndex
  2362. , New<v8::External>(reinterpret_cast<void *>(callback)));
  2363. if (!data.IsEmpty()) {
  2364. obj->SetInternalField(imp::kDataIndex, data);
  2365. }
  2366. tpl->SetCallHandler(imp::FunctionCallbackWrapper, obj);
  2367. }
  2368. inline void SetCallAsFunctionHandler(
  2369. v8::Local<v8::ObjectTemplate> tpl,
  2370. FunctionCallback callback,
  2371. v8::Local<v8::Value> data = v8::Local<v8::Value>()) {
  2372. HandleScope scope;
  2373. v8::Local<v8::ObjectTemplate> otpl = New<v8::ObjectTemplate>();
  2374. otpl->SetInternalFieldCount(imp::kFunctionFieldCount);
  2375. v8::Local<v8::Object> obj = NewInstance(otpl).ToLocalChecked();
  2376. obj->SetInternalField(
  2377. imp::kFunctionIndex
  2378. , New<v8::External>(reinterpret_cast<void *>(callback)));
  2379. if (!data.IsEmpty()) {
  2380. obj->SetInternalField(imp::kDataIndex, data);
  2381. }
  2382. tpl->SetCallAsFunctionHandler(imp::FunctionCallbackWrapper, obj);
  2383. }
  2384. //=== Weak Persistent Handling =================================================
  2385. #include "nan_weak.h" // NOLINT(build/include)
  2386. //=== ObjectWrap ===============================================================
  2387. #include "nan_object_wrap.h" // NOLINT(build/include)
  2388. //=== HiddenValue/Private ======================================================
  2389. #include "nan_private.h" // NOLINT(build/include)
  2390. //=== Export ==================================================================
  2391. inline
  2392. void
  2393. Export(ADDON_REGISTER_FUNCTION_ARGS_TYPE target, const char *name,
  2394. FunctionCallback f) {
  2395. HandleScope scope;
  2396. Set(target, New<v8::String>(name).ToLocalChecked(),
  2397. GetFunction(New<v8::FunctionTemplate>(f)).ToLocalChecked());
  2398. }
  2399. //=== Tap Reverse Binding =====================================================
  2400. struct Tap {
  2401. explicit Tap(v8::Local<v8::Value> t) : t_() {
  2402. HandleScope scope;
  2403. t_.Reset(To<v8::Object>(t).ToLocalChecked());
  2404. }
  2405. ~Tap() { t_.Reset(); } // not sure if neccessary
  2406. inline void plan(int i) {
  2407. HandleScope scope;
  2408. v8::Local<v8::Value> arg = New(i);
  2409. Call("plan", New(t_), 1, &arg);
  2410. }
  2411. inline void ok(bool isOk, const char *msg = NULL) {
  2412. HandleScope scope;
  2413. v8::Local<v8::Value> args[2];
  2414. args[0] = New(isOk);
  2415. if (msg) args[1] = New(msg).ToLocalChecked();
  2416. Call("ok", New(t_), msg ? 2 : 1, args);
  2417. }
  2418. inline void pass(const char * msg = NULL) {
  2419. HandleScope scope;
  2420. v8::Local<v8::Value> hmsg;
  2421. if (msg) hmsg = New(msg).ToLocalChecked();
  2422. Call("pass", New(t_), msg ? 1 : 0, &hmsg);
  2423. }
  2424. inline void end() {
  2425. HandleScope scope;
  2426. Call("end", New(t_), 0, NULL);
  2427. }
  2428. private:
  2429. Persistent<v8::Object> t_;
  2430. };
  2431. #define NAN_STRINGIZE2(x) #x
  2432. #define NAN_STRINGIZE(x) NAN_STRINGIZE2(x)
  2433. #define NAN_TEST_EXPRESSION(expression) \
  2434. ( expression ), __FILE__ ":" NAN_STRINGIZE(__LINE__) ": " #expression
  2435. #define NAN_EXPORT(target, function) Export(target, #function, function)
  2436. #undef TYPE_CHECK
  2437. //=== Generic Maybefication ===================================================
  2438. namespace imp {
  2439. template <typename T> struct Maybefier;
  2440. template <typename T> struct Maybefier<v8::Local<T> > {
  2441. inline static MaybeLocal<T> convert(v8::Local<T> v) {
  2442. return v;
  2443. }
  2444. };
  2445. template <typename T> struct Maybefier<MaybeLocal<T> > {
  2446. inline static MaybeLocal<T> convert(MaybeLocal<T> v) {
  2447. return v;
  2448. }
  2449. };
  2450. } // end of namespace imp
  2451. template <typename T, template <typename> class MaybeMaybe>
  2452. inline MaybeLocal<T>
  2453. MakeMaybe(MaybeMaybe<T> v) {
  2454. return imp::Maybefier<MaybeMaybe<T> >::convert(v);
  2455. }
  2456. //=== TypedArrayContents =======================================================
  2457. #include "nan_typedarray_contents.h" // NOLINT(build/include)
  2458. //=== JSON =====================================================================
  2459. #include "nan_json.h" // NOLINT(build/include)
  2460. } // end of namespace Nan
  2461. #endif // NAN_H_