forked from sanyaade-mobiledev/chromium.src
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathnp_v8_bridge.cc
1578 lines (1361 loc) · 53.8 KB
/
np_v8_bridge.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2009, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Code relating to interoperation of V8 JavaScript engine with NPAPI.
// Tests are in o3d/tests/selenium/tests/v8.html. They can be run
// by opening the web page in a browser or as part of the selenium tests.
#include <npapi.h>
#include <sstream>
#include <vector>
#include "base/scoped_ptr.h"
#include "plugin/cross/np_v8_bridge.h"
using v8::AccessorInfo;
using v8::Arguments;
using v8::Array;
using v8::Context;
using v8::DontDelete;
using v8::DontEnum;
using v8::External;
using v8::Function;
using v8::FunctionTemplate;
using v8::HandleScope;
using v8::Int32;
using v8::Integer;
using v8::Local;
using v8::Message;
using v8::Null;
using v8::Number;
using v8::Object;
using v8::ObjectTemplate;
using v8::Persistent;
using v8::PropertyAttribute;
using v8::ReadOnly;
using v8::Script;
using v8::TryCatch;
using v8::Undefined;
using v8::Value;
namespace o3d {
// Only used during debugging. Type "o3d::DebugV8String(a.val_)" in the
// watch window to get the string representation of a V8 object.
const char* DebugV8String(Value* value) {
static char buffer[4096];
if (value == NULL) {
::base::snprintf(buffer, sizeof(buffer), "<null>");
} else {
value->ToString()->WriteUtf8(buffer);
}
return buffer;
}
namespace {
// The indices of the internal fields of a V8 proxy for an NPObject.
enum {
// Pointer to the bridge that created the proxy.
V8_NP_OBJECT_BRIDGE,
// Pointer to the wrapped NPObject.
V8_NP_OBJECT_WRAPPED,
V8_NP_OBJECT_NUM_INTERNAL_FIELDS
};
// The name of the "hidden" property in a V8 non-proxy object that contains
// an External that points to the NPObject proxy for it. The property does
// not exist if there is no associated NPObject proxy.
const char* const kInternalProperty = "internal_property_";
// Convert an NPIdentifier (NULL, string or integer) to a V8 value.
Local<Value> NPToV8Identifier(NPIdentifier np_identifier) {
if (np_identifier == NULL) {
return Local<Value>();
} else if (NPN_IdentifierIsString(np_identifier)) {
NPUTF8* utf8_name = NPN_UTF8FromIdentifier(np_identifier);
Local<v8::String> v8_identifier = v8::String::New(utf8_name);
NPN_MemFree(utf8_name);
return v8_identifier;
} else {
return Integer::New(NPN_IntFromIdentifier(np_identifier));
}
}
// Convert a V8 value (empty, string or integer) into an NPIdentifier.
NPIdentifier V8ToNPIdentifier(v8::Handle<Value> v8_identifier) {
if (v8_identifier.IsEmpty()) {
return NULL;
} else if (v8_identifier->IsNumber()) {
return NPN_GetIntIdentifier(v8_identifier->Int32Value());
} else if (v8_identifier->IsString()) {
return NPN_GetStringIdentifier(
*v8::String::Utf8Value(v8_identifier->ToString()));
} else {
return NULL;
}
}
} // namespace anonymous
// The class of NPObject proxies that wrap V8 objects. These field the NPAPI
// functions and translate them into V8 calls.
class NPV8Object : public NPObject {
public:
static NPObjectPtr<NPV8Object> Create(NPV8Bridge* bridge,
Local<Object> v8_object) {
NPObjectPtr<NPV8Object> np_object =
NPObjectPtr<NPV8Object>::AttachToReturned(
static_cast<NPV8Object*>(NPN_CreateObject(bridge->npp(),
&np_class_)));
np_object->v8_object_ = Persistent<Object>::New(v8_object);
np_object->bridge_ = bridge;
return np_object;
}
v8::Handle<Object> v8_object() const {
return v8_object_;
}
// Drop references between NPObject and V8 object. Must be called before the
// NPObject is destroyed so V8 can garbage collect the associated V8 object.
void UnlinkFromV8() {
HandleScope handle_scope;
if (!v8_object_.IsEmpty()) {
v8_object_->DeleteHiddenValue(v8::String::NewSymbol(kInternalProperty));
v8_object_.Dispose();
v8_object_.Clear();
}
}
static NPClass np_class_;
private:
NPV8Object() : bridge_(NULL) {
}
static NPObject* Allocate(NPP npp, NPClass* np_class) {
v8::Locker locker;
NPV8Object* np_v8_object = new NPV8Object();
np_v8_object->bridge_ = NULL;
return np_v8_object;
}
static void Deallocate(NPObject* np_object) {
v8::Locker locker;
NPV8Object* np_v8_object = static_cast<NPV8Object*> (np_object);
// Uncomment this line to see objects with a non-zero reference
// count being deallocated. For example, Firefox does this when unloading
// the plugin.
// DCHECK_EQ(0, np_v8_object_map->referenceCount);
np_v8_object->UnlinkFromV8();
delete np_v8_object;
}
static void Invalidate(NPObject* np_object) {
v8::Locker locker;
NPV8Object* np_v8_object = static_cast<NPV8Object*> (np_object);
np_v8_object->bridge_ = NULL;
np_v8_object->UnlinkFromV8();
}
static bool HasMethod(NPObject* np_object, NPIdentifier np_name) {
v8::Locker locker;
NPV8Object* np_v8_object = static_cast<NPV8Object*> (np_object);
NPV8Bridge* bridge = np_v8_object->bridge_;
if (bridge == NULL)
return false;
HandleScope handle_scope;
Context::Scope scope(bridge->script_context());
TryCatch tryCatch;
v8::Handle<Object> v8_object = np_v8_object->v8_object_;
if (v8_object.IsEmpty())
return false;
Local<Value> v8_name = NPToV8Identifier(np_name);
Local<Value> value = v8_object->Get(v8_name);
if (tryCatch.HasCaught()) {
bridge->ReportV8Exception(tryCatch);
return false;
}
// Returns true iff the object has a property with the given name and
// the object assigned to the property is a function. This works for V8
// functions and assigned browser JavaScript functions (because their
// proxies are created from FunctionTemplates so V8 considers them to be
// functions).
return !value.IsEmpty() && value->IsFunction();
}
// Called when a method is invoked through "obj.m(...)".
static bool Invoke(NPObject* np_object, NPIdentifier np_name,
const NPVariant* np_args, uint32_t numArgs,
NPVariant* result) {
v8::Locker locker;
// This works around a bug in Chrome:
// http://code.google.com/p/chromium/issues/detail?id=5110
// NPN_InvokeDefault is transformed into a call to Invoke on the plugin with
// a null method name identifier.
if (np_name == NULL) {
return InvokeDefault(np_object, np_args, numArgs, result);
}
NPV8Object* np_v8_object = static_cast<NPV8Object*> (np_object);
NPV8Bridge* bridge = np_v8_object->bridge_;
if (bridge == NULL)
return false;
HandleScope handle_scope;
Context::Scope scope(bridge->script_context());
TryCatch tryCatch;
v8::Handle<Object> v8_object = np_v8_object->v8_object_;
if (v8_object.IsEmpty())
return false;
Local<Value> v8_name = NPToV8Identifier(np_name);
Local<Value> value = v8_object->Get(v8_name);
if (value.IsEmpty() || !value->IsFunction())
return false;
Local<Function> function = Local<Function>::Cast(value);
std::vector<v8::Handle<Value> > v8_args(numArgs);
for (uint32_t i = 0; i != numArgs; ++i) {
v8_args[i] = bridge->NPToV8Variant(np_args[i]);
}
*result = bridge->V8ToNPVariant(
function->Call(v8_object, numArgs,
numArgs == 0 ? NULL : &v8_args.front()));
if (tryCatch.HasCaught()) {
bridge->ReportV8Exception(tryCatch);
return false;
}
return true;
}
// Called when an object is called as a function "f(...)".
static bool InvokeDefault(NPObject* np_object, const NPVariant* np_args,
uint32_t numArgs, NPVariant* result) {
v8::Locker locker;
NPV8Object* np_v8_object = static_cast<NPV8Object*> (np_object);
NPV8Bridge* bridge = np_v8_object->bridge_;
if (bridge == NULL)
return false;
HandleScope handle_scope;
Context::Scope scope(bridge->script_context());
TryCatch tryCatch;
v8::Handle<Object> v8_object = np_v8_object->v8_object_;
if (v8_object.IsEmpty())
return false;
if (!v8_object->IsFunction())
return false;
v8::Handle<Function> function = v8::Handle<Function>::Cast(v8_object);
std::vector<v8::Handle<Value> > v8_args(numArgs);
for (uint32_t i = 0; i != numArgs; ++i) {
v8_args[i] = bridge->NPToV8Variant(np_args[i]);
}
*result = bridge->V8ToNPVariant(
function->Call(v8_object, numArgs,
numArgs == 0 ? NULL : &v8_args.front()));
if (tryCatch.HasCaught()) {
bridge->ReportV8Exception(tryCatch);
return false;
}
return true;
}
// Called when an object is called as a constructor "new C(...)".
static bool Construct(NPObject* np_object, const NPVariant* np_args,
uint32_t numArgs, NPVariant* result) {
v8::Locker locker;
NPV8Object* np_v8_object = static_cast<NPV8Object*> (np_object);
NPV8Bridge* bridge = np_v8_object->bridge_;
if (bridge == NULL)
return false;
HandleScope handle_scope;
Context::Scope scope(bridge->script_context());
TryCatch tryCatch;
v8::Handle<Object> v8_object = np_v8_object->v8_object_;
if (v8_object.IsEmpty())
return false;
if (!v8_object->IsFunction())
return false;
v8::Handle<Function> function = v8::Handle<Function>::Cast(v8_object);
std::vector<v8::Handle<Value> > v8_args(numArgs);
for (uint32_t i = 0; i != numArgs; ++i) {
v8_args[i] = bridge->NPToV8Variant(np_args[i]);
}
Local<Object> v8_result = function->NewInstance(
numArgs, numArgs == 0 ? NULL : &v8_args.front());
if (v8_result.IsEmpty())
return false;
*result = bridge->V8ToNPVariant(v8_result);
if (tryCatch.HasCaught()) {
bridge->ReportV8Exception(tryCatch);
return false;
}
return true;
}
static bool HasProperty(NPObject* np_object, NPIdentifier np_name) {
v8::Locker locker;
NPV8Object* np_v8_object = static_cast<NPV8Object*> (np_object);
NPV8Bridge* bridge = np_v8_object->bridge_;
if (bridge == NULL)
return false;
HandleScope handle_scope;
Context::Scope scope(bridge->script_context());
v8::Handle<Object> v8_object = np_v8_object->v8_object_;
if (v8_object.IsEmpty())
return false;
// This is a better approach than the one below. It allows functions
// to be retreived as first class objects. Unfortunately we can't
// support this yet because of a Chrome bug:
// http://code.google.com/p/chromium/issues/detail?id=5742
// if (NPN_IdentifierIsString(np_name)) {
// Local<v8::String> v8_name = Local<v8::String>::Cast(
// NPToV8Identifier(np_name));
// return v8_object->Has(v8_name);
// } else {
// return v8_object->Has(NPN_IntFromIdentifier(np_name));
// }
// Instead hide properties with function type. This ensures that Chrome
// will invoke them with Invoke rather than InvokeDefault. The problem
// with InvokeDefault is it doesn't tell us what "this" should be
// bound to, whereas Invoke does.
Local<Value> v8_name = NPToV8Identifier(np_name);
if (NPN_IdentifierIsString(np_name)) {
if (!v8_object->Has(v8_name->ToString())) {
return false;
}
} else {
if (!v8_object->Has(NPN_IntFromIdentifier(np_name))) {
return false;
}
}
Local<Value> v8_property_value = v8_object->Get(v8_name);
if (v8_property_value->IsFunction()) {
return false;
}
return true;
}
static bool GetProperty(NPObject* np_object, NPIdentifier np_name,
NPVariant* result) {
v8::Locker locker;
NPV8Object* np_v8_object = static_cast<NPV8Object*> (np_object);
NPV8Bridge* bridge = np_v8_object->bridge_;
if (bridge == NULL)
return false;
HandleScope handle_scope;
Context::Scope scope(bridge->script_context());
TryCatch tryCatch;
v8::Handle<Object> v8_object = np_v8_object->v8_object_;
if (v8_object.IsEmpty())
return false;
Local<Value> v8_name = NPToV8Identifier(np_name);
Local<Value> v8_property_value = v8_object->Get(v8_name);
if (tryCatch.HasCaught()) {
bridge->ReportV8Exception(tryCatch);
return false;
}
// See comment in HasProperty. Do not return properties that are
// functions. It will prevent Chrome from invoking them as methods.
if (v8_property_value.IsEmpty() || v8_property_value->IsFunction())
return false;
*result = bridge->V8ToNPVariant(v8_property_value);
return true;
}
static bool SetProperty(NPObject* np_object, NPIdentifier np_name,
const NPVariant* np_value) {
v8::Locker locker;
NPV8Object* np_v8_object = static_cast<NPV8Object*> (np_object);
NPV8Bridge* bridge = np_v8_object->bridge_;
if (bridge == NULL)
return false;
HandleScope handle_scope;
Context::Scope scope(bridge->script_context());
TryCatch tryCatch;
v8::Handle<Object> v8_object = np_v8_object->v8_object_;
if (v8_object.IsEmpty())
return false;
Local<Value> v8_name = NPToV8Identifier(np_name);
bool success = v8_object->Set(v8_name, bridge->NPToV8Variant(*np_value));
if (tryCatch.HasCaught()) {
bridge->ReportV8Exception(tryCatch);
return false;
}
return success;
}
static bool RemoveProperty(NPObject* np_object, NPIdentifier np_name) {
v8::Locker locker;
NPV8Object* np_v8_object = static_cast<NPV8Object*> (np_object);
NPV8Bridge* bridge = np_v8_object->bridge_;
if (bridge == NULL)
return false;
HandleScope handle_scope;
Context::Scope scope(bridge->script_context());
TryCatch tryCatch;
v8::Handle<Object> v8_object = np_v8_object->v8_object_;
if (v8_object.IsEmpty())
return false;
bool success;
if (NPN_IdentifierIsString(np_name)) {
NPUTF8* utf8_name = NPN_UTF8FromIdentifier(np_name);
Local<v8::String> v8_name = v8::String::New(utf8_name);
NPN_MemFree(utf8_name);
success = v8_object->Delete(v8_name);
} else {
success = v8_object->Delete(NPN_IntFromIdentifier(np_name));
}
if (tryCatch.HasCaught()) {
bridge->ReportV8Exception(tryCatch);
return false;
}
return success;
}
static bool Enumerate(NPObject* np_object, NPIdentifier** np_names,
uint32_t* numNames) {
v8::Locker locker;
NPV8Object* np_v8_object = static_cast<NPV8Object*> (np_object);
NPV8Bridge* bridge = np_v8_object->bridge_;
if (bridge == NULL)
return false;
HandleScope handle_scope;
Context::Scope scope(bridge->script_context());
v8::Handle<Object> v8_object = np_v8_object->v8_object_;
if (v8_object.IsEmpty())
return false;
Local<Array> v8_names = v8_object->GetPropertyNames();
// Due to a bug in Chrome, need to filter out any properties that
// are functions. See comment in HasProperty.
int num_non_function_properties = 0;
int length = v8_names->Length();
for (int i = 0; i < length; ++i) {
Local<Value> v8_property_value =
v8_object->Get(v8_names->Get(Int32::New(i)));
if (!v8_property_value->IsFunction()) {
++num_non_function_properties;
}
}
*numNames = num_non_function_properties;
*np_names = static_cast<NPIdentifier*> (
NPN_MemAlloc(num_non_function_properties * sizeof(NPIdentifier)));
int j = 0;
for (uint32_t i = 0; i != v8_names->Length(); ++i) {
Local<Value> v8_name = v8_names->Get(Int32::New(i));
Local<Value> v8_property_value = v8_object->Get(v8_name);
if (!v8_property_value->IsFunction()) {
(*np_names)[j++] = V8ToNPIdentifier(v8_name);
}
}
return true;
}
NPV8Bridge* bridge_;
AutoV8Persistent<Object> v8_object_;
DISALLOW_COPY_AND_ASSIGN(NPV8Object);
};
NPClass NPV8Object::np_class_ = {
NP_CLASS_STRUCT_VERSION,
Allocate,
Deallocate,
Invalidate,
HasMethod,
Invoke,
InvokeDefault,
HasProperty,
GetProperty,
SetProperty,
RemoveProperty,
Enumerate,
Construct
};
NPV8Bridge::NPV8Bridge(ServiceLocator* service_locator, NPP npp)
: service_locator_(service_locator),
error_status_(service_locator),
npp_(npp) {
np_name_identifier_ = NPN_GetStringIdentifier("name");
np_call_identifier_ = NPN_GetStringIdentifier("call");
np_length_identifier_ = NPN_GetStringIdentifier("length");
np_proxy_identifier_ = NPN_GetStringIdentifier("npv8_proxy_");
}
NPV8Bridge::~NPV8Bridge() {
v8::Locker locker;
// Do not call weak reference callback after the bridge is destroyed
// because the callbacks assume it exists. The only purpose of the callback
// is to remove the corresponding object entry from the NP-V8 object map
// and its about to get cleared anyway.
for (NPV8ObjectMap::iterator it = np_v8_object_map_.begin();
it != np_v8_object_map_.end(); ++it) {
it->second.ClearWeak();
}
}
NPObjectPtr<NPObject> NPV8Bridge::NPEvaluateObject(const char* script) {
NPString np_script = { script, strlen(script) };
NPVariant np_variant;
NPObjectPtr<NPObject> np_result;
if (NPN_Evaluate(npp_, global_np_object_.Get(), &np_script, &np_variant)) {
if (NPVARIANT_IS_OBJECT(np_variant)) {
np_result = NPObjectPtr<NPObject>(NPVARIANT_TO_OBJECT(np_variant));
}
NPN_ReleaseVariantValue(&np_variant);
}
return np_result;
}
namespace {
// Create code that looks like this:
// (function(func, protoArray) {
// return function() {
// switch (arguments.length) {
// case 0:
// return func.call(this);
// case 1:
// return func.call(this,
// arguments[0]);
// case 2:
// return func.call(this,
// arguments[0],
// arguments[1]);
// ...
// default:
// var args = protoArray.slice();
// for (var i = 0; i < arguments.length; ++i) {
// args[i] = arguments[i];
// }
// return func.apply(this, args);
// }
// };
// })
String MakeWrapFunctionScript() {
std::ostringstream code;
code << "(function(func, protoArray) {";
code << " return function() {";
code << " switch (arguments.length) {";
for (int i = 0; i <= 10; ++i) {
code << " case " << i << ": return func.call(this";
for (int j = 0; j < i; ++j) {
code << ", arguments[" << j << "]";
}
code << ");";
}
code << " default:";
code << " var args = protoArray.slice();";
code << " for (var i = 0; i < arguments.length; ++i) {";
code << " args.push(arguments[i]);";
code << " }";
code << " return func.apply(this, args);";
code << " }";
code << " };";
code << "})";
return code.str();
}
} // namespace anonymous
void NPV8Bridge::Initialize(const NPObjectPtr<NPObject>& global_np_object) {
v8::Locker locker;
HandleScope handle_scope;
global_np_object_ = global_np_object;
// This template is used for V8 proxies of NPObjects.
v8_np_constructor_template_ = Persistent<FunctionTemplate>::New(
FunctionTemplate::New());
InitializeV8ObjectTemplate(v8_np_constructor_template_->InstanceTemplate());
// This template is used for the global V8 object.
Local<FunctionTemplate> v8_global_template = FunctionTemplate::New();
InitializeV8ObjectTemplate(v8_global_template->PrototypeTemplate());
script_context_ = Context::New(NULL, v8_global_template->InstanceTemplate());
Context::Scope scope(script_context_);
// Give the global object a prototype that allows V8 to access global
// variables in another JavaScript environemnt over NPAPI.
Local<Object> v8_global_prototype =
Local<Object>::Cast(script_context_->Global()->GetPrototype());
Local<Object> v8_global_prototype2 =
Local<Object>::Cast(v8_global_prototype->GetPrototype());
global_prototype_ = Persistent<Object>::New(v8_global_prototype2);
NPToV8Object(v8_global_prototype2, global_np_object);
function_map_ = Persistent<Object>::New(Object::New());
// Create a browser JavaScript function that can later be called to get the
// type of an object (as the browser sees it). This is useful for determining
// whether an object received over NPAPI is a function (which means its
// proxy must be created from a FunctionTemplate rather than an
// ObjectTemplate).
static const char kIsFunctionScript[] =
"(function(obj) { return obj instanceof Function; })";
np_is_function_function_ = NPEvaluateObject(kIsFunctionScript);
// Create a browser JavaScript function that can later be used to enumerate
// the properties of an object. This is used as a fallback if NPN_Evaluate
// is not implemented by the browser (like Firefox 2) and the enumerate
// callback is not implemented by the NPObject.
static const char kEnumerateScript[] =
"(function(object) {"
" var properties = [];"
" for (var property in object) {"
" if (object.hasOwnProperty(property)) {"
" properties[properties.length++] = property;"
" }"
" }"
" return properties;"
"})";
np_enumerate_function_ = NPEvaluateObject(kEnumerateScript);
// Create a browser JavaScript function that can later be used to create
// a wrapper around an V8 function proxy, making it appear to be a real
// browser function.
np_wrap_function_function_ = NPEvaluateObject(
MakeWrapFunctionScript().c_str());
// Create an NPObject proxy for a V8 array. This is for the browser to use as
// a prototype for creating new V8 arrays with slice().
np_empty_array_ = V8ToNPObject(v8::Array::New(0));
}
void NPV8Bridge::ReleaseNPObjects() {
v8::Locker locker;
np_v8_object_map_.clear();
np_construct_functions_.clear();
global_np_object_.Clear();
np_is_function_function_.Clear();
np_enumerate_function_.Clear();
np_wrap_function_function_.Clear();
np_empty_array_.Clear();
}
v8::Handle<Context> NPV8Bridge::script_context() {
return script_context_;
}
bool NPV8Bridge::Evaluate(const NPVariant* np_args, int numArgs,
NPVariant* np_result) {
v8::Locker locker;
HandleScope handle_scope;
Context::Scope scope(script_context_);
Local<Value> v8_code;
if (numArgs == 1) {
v8_code = NPToV8Variant(np_args[0]);
} else {
return false;
}
if (v8_code.IsEmpty() || !v8_code->IsString())
return false;
TryCatch tryCatch;
Local<v8::String> v8_code_string = v8_code->ToString();
Local<Script> v8_script = v8::Script::Compile(v8_code_string);
if (tryCatch.HasCaught()) {
// Newer version of v8 doesn't like eval('function () { ... }') but wants
// instead eval('(function () { ... })'). Old js code may still try to pass
// that in, so add a pair of ( ) around the given string, and try again.
tryCatch.Reset();
int length = v8_code_string->Utf8Length();
// Note: this string is not 0-terminated.
scoped_array<char> paren_string(new char[length + 2]);
v8_code_string->WriteUtf8(paren_string.get() + 1, length);
paren_string[0] = '(';
paren_string[length + 1] = ')';
v8_code_string = v8::String::New(paren_string.get(), length + 2);
v8_script = v8::Script::Compile(v8_code_string);
if (tryCatch.HasCaught()) {
ReportV8Exception(tryCatch);
return false;
}
}
if (v8_script.IsEmpty())
return false;
Local<Value> v8_result = v8_script->Run();
if (tryCatch.HasCaught()) {
ReportV8Exception(tryCatch);
return false;
}
if (v8_result.IsEmpty())
return false;
*np_result = V8ToNPVariant(v8_result);
return true;
}
void NPV8Bridge::SetGlobalProperty(const String& name,
NPObjectPtr<NPObject>& np_object) {
v8::Locker locker;
HandleScope handle_scope;
Context::Scope scope(script_context_);
script_context_->Global()->Set(v8::String::New(name.c_str()),
NPToV8Object(np_object));
}
NPVariant NPV8Bridge::V8ToNPVariant(Local<Value> value) {
NPVariant np_variant;
if (value.IsEmpty() || value->IsUndefined()) {
VOID_TO_NPVARIANT(np_variant);
} else if (value->IsNull()) {
NULL_TO_NPVARIANT(np_variant);
} else if (value->IsBoolean()) {
BOOLEAN_TO_NPVARIANT(value->BooleanValue(), np_variant);
} else if (value->IsInt32()) {
INT32_TO_NPVARIANT(value->Int32Value(), np_variant);
} else if (value->IsNumber()) {
DOUBLE_TO_NPVARIANT(value->NumberValue(), np_variant);
} else if (value->IsString()) {
Local<v8::String> v8_string = value->ToString();
int utf8_length = v8_string->Length();
NPUTF8* utf8_chars = static_cast<NPUTF8*>(NPN_MemAlloc(utf8_length + 1));
v8_string->WriteUtf8(utf8_chars);
STRINGN_TO_NPVARIANT(utf8_chars, utf8_length, np_variant);
} else if (value->IsObject()) {
Local<Object> v8_object = value->ToObject();
NPObjectPtr<NPObject> np_object = V8ToNPObject(v8_object);
OBJECT_TO_NPVARIANT(np_object.Disown(), np_variant);
}
return np_variant;
}
Local<Value> NPV8Bridge::NPToV8Variant(const NPVariant& np_variant) {
Local<Value> v8_result;
switch (np_variant.type) {
case NPVariantType_Void:
v8_result = Local<Value>::New(Undefined());
break;
case NPVariantType_Null:
v8_result = Local<Value>::New(Null());
break;
case NPVariantType_Bool:
v8_result = Local<Value>::New(
v8::Boolean::New(NPVARIANT_TO_BOOLEAN(np_variant)));
break;
case NPVariantType_Int32:
v8_result = Local<Value>::New(
Int32::New(NPVARIANT_TO_INT32(np_variant)));
break;
case NPVariantType_Double:
v8_result = Local<Value>::New(
Number::New(NPVARIANT_TO_DOUBLE(np_variant)));
break;
case NPVariantType_String:
{
NPString np_string = NPVARIANT_TO_STRING(np_variant);
v8_result = Local<Value>::New(
v8::String::New(np_string.UTF8Characters, np_string.UTF8Length));
break;
}
case NPVariantType_Object:
v8_result = NPToV8Object(
NPObjectPtr<NPObject>(NPVARIANT_TO_OBJECT(np_variant)));
break;
default:
v8_result = Local<Value>();
break;
}
return v8_result;
}
NPObjectPtr<NPObject> NPV8Bridge::V8ToNPObject(Local<Value> v8_value) {
NPObjectPtr<NPObject> np_object;
if (!v8_value.IsEmpty() && v8_value->IsObject()) {
Local<Object> v8_object = Local<Object>::Cast(v8_value);
if (v8_object->InternalFieldCount() == 0) {
// It is must be a V8 created JavaScript object (or function), a V8
// function proxy for an NP function or a V8 function proxy for a named
// native method. If it is already associated with an NP object then that
// will be stored in the "internal property". Return that if it's there,
// otherwise create a new NP proxy.
Local<v8::String> internal_name = v8::String::NewSymbol(
kInternalProperty);
Local<Value> v8_internal = v8_object->GetHiddenValue(internal_name);
if (v8_internal.IsEmpty() || v8_internal->IsUndefined()) {
// No existing NP object so create a proxy and store it in the "internal
// property".
np_object = NPV8Object::Create(this, v8_object);
v8_internal = External::New(np_object.Get());
v8_object->SetHiddenValue(internal_name, v8_internal);
} else {
np_object = NPObjectPtr<NPObject>(
static_cast<NPObject*>(
Local<External>::Cast(v8_internal)->Value()));
}
// If it is a V8 function then wrap it in a browser function so that its
// typeof will be reported as 'function' in the browser and it can be
// used in cases where a real function is required (rather than an
// object that just happens to be invocable.
if (v8_value->IsFunction() &&
np_object->_class == &NPV8Object::np_class_) {
np_object = WrapV8Function(np_object);
}
} else {
// This is a V8 object proxy. The NP object is referenced from an internal
// field.
Local<Value> internal = v8_object->GetInternalField(
V8_NP_OBJECT_WRAPPED);
np_object = NPObjectPtr<NPObject>(
static_cast<NPObject*>(Local<External>::Cast(internal)->Value()));
}
}
return np_object;
}
// Wrap NPV8Object proxying a V8 function in a browser function so that its
// typeof will be reported as 'function' in the browser and it can be
// used in cases where a real function is required (rather than an
// object that just happens to be invocable.
// A new wrapper function is created whenever a V8 function crosses into the
// browser. So === won't do the right thing in the browser.
NPObjectPtr<NPObject> NPV8Bridge::WrapV8Function(
const NPObjectPtr<NPObject>& np_object) {
NPObjectPtr<NPObject> np_result = np_object;
NPVariant np_args[2];
OBJECT_TO_NPVARIANT(np_object.Get(), np_args[0]);
OBJECT_TO_NPVARIANT(np_empty_array_.Get(), np_args[1]);
NPVariant np_variant;
if (NPN_InvokeDefault(npp_, np_wrap_function_function_.Get(),
np_args, 2, &np_variant)) {
if (NPVARIANT_IS_OBJECT(np_variant)) {
NPObjectPtr<NPObject> np_wrapper(NPVARIANT_TO_OBJECT(np_variant));
// Add a reference back to the NPV8Object so we can find it again.
if (NPN_SetProperty(npp_, np_wrapper.Get(), np_proxy_identifier_,
&np_args[0])) {
np_result = np_wrapper;
}
}
NPN_ReleaseVariantValue(&np_variant);
}
return np_result;
}
Local<Value> NPV8Bridge::NPToV8Object(const NPObjectPtr<NPObject>& np_object) {
if (np_object.IsNull())
return Local<Value>::New(Null());
// This might be a wrapper for a function. Find the actual proxy in that
// case.
NPObjectPtr<NPObject> np_real_object = np_object;
{
// NPN_GetProperty might cause an O3D NPObject to set an error if the
// property does not exist. Prevent that. It would be better to simply
// test whether the property exists by calling NPN_HasProperty but that
// is not supported in Mac Safari.
ErrorSuppressor error_suppressor(service_locator_);
NPVariant np_variant;
if (NPN_GetProperty(npp_, np_real_object.Get(), np_proxy_identifier_,
&np_variant)) {
if (NPVARIANT_IS_OBJECT(np_variant)) {
np_real_object = NPVARIANT_TO_OBJECT(np_variant);
}
NPN_ReleaseVariantValue(&np_variant);
}
}
if (np_real_object->_class == &NPV8Object::np_class_) {
NPV8Object* np_v8_object = static_cast<NPV8Object*>(np_real_object.Get());
return Local<Object>::New(np_v8_object->v8_object());
} else {
NPV8ObjectMap::const_iterator it = np_v8_object_map_.find(np_real_object);
if (it != np_v8_object_map_.end())
return Local<Object>::New(it->second);
if (IsNPFunction(np_real_object)) {
return NPToV8Function(np_real_object);
} else {
Local<Function> v8_function = v8_np_constructor_template_->GetFunction();
Local<Object> v8_object = v8_function->NewInstance();
if (!v8_object.IsEmpty()) {
// NewInstance sets a JavaScript exception if it fails. Eventually
// it'll be caught when control flow hits a TryCatch. Just make sure
// not to dereference it before then.
NPToV8Object(v8_object, np_real_object);
}
return v8_object;
}
}
}
void NPV8Bridge::NPToV8Object(v8::Local<Object> v8_target,
const NPObjectPtr<NPObject>& np_object) {
v8_target->SetInternalField(V8_NP_OBJECT_BRIDGE, External::New(this));
v8_target->SetInternalField(V8_NP_OBJECT_WRAPPED,
External::New(np_object.Get()));
RegisterV8Object(v8_target, np_object);
}
bool NPV8Bridge::IsNPFunction(const NPObjectPtr<NPObject>& np_object) {
// Before invoking the potentially expensive instanceof function (it has to
// go through the browser) check whether the object has a call
// property. If it doesn't have one then it isn't a JavaScript
// function.
if (!NPN_HasProperty(npp_, np_object.Get(), np_call_identifier_)) {
return false;
}
// If it looks like it might be a function then call the instanceof function
// in the browser to confirm.
bool is_function = false;
NPVariant np_object_variant;
OBJECT_TO_NPVARIANT(np_object.Get(), np_object_variant);