nan.h 84 KB

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