Debian Codegraph @

rhino/src/org/mozilla/javascript/JavaAdapter.java

raw symbols SCIP
1 /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2 *
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 package org.mozilla.javascript;
8
9 import org.mozilla.classfile.*;
10 import java.lang.reflect.*;
11 import java.io.*;
12 import java.security.*;
13 import java.util.*;
14
15 public final class JavaAdapter implements IdFunctionCall
16 {
17 /**
18 * Provides a key with which to distinguish previously generated
19 * adapter classes stored in a hash table.
20 */
21 static class JavaAdapterSignature
22 {
23 Class<?> superClass;
24 Class<?>[] interfaces;
25 ObjToIntMap names;
26
27 JavaAdapterSignature(Class<?> superClass, Class<?>[] interfaces,
28 ObjToIntMap names)
29 {
30 this.superClass = superClass;
31 this.interfaces = interfaces;
32 this.names = names;
33 }
34
35 @Override
36 public boolean equals(Object obj)
37 {
38 if (!(obj instanceof JavaAdapterSignature))
39 return false;
40 JavaAdapterSignature sig = (JavaAdapterSignature) obj;
41 if (superClass != sig.superClass)
42 return false;
43 if (interfaces != sig.interfaces) {
44 if (interfaces.length != sig.interfaces.length)
45 return false;
46 for (int i=0; i < interfaces.length; i++)
47 if (interfaces[i] != sig.interfaces[i])
48 return false;
49 }
50 if (names.size() != sig.names.size())
51 return false;
52 ObjToIntMap.Iterator iter = new ObjToIntMap.Iterator(names);
53 for (iter.start(); !iter.done(); iter.next()) {
54 String name = (String)iter.getKey();
55 int arity = iter.getValue();
56 if (arity != sig.names.get(name, arity + 1))
57 return false;
58 }
59 return true;
60 }
61
62 @Override
63 public int hashCode()
64 {
65 return (superClass.hashCode() + Arrays.hashCode(interfaces)) ^ names.size();
66 }
67 }
68
69 public static void init(Context cx, Scriptable scope, boolean sealed)
70 {
71 JavaAdapter obj = new JavaAdapter();
72 IdFunctionObject ctor = new IdFunctionObject(obj, FTAG, Id_JavaAdapter,
73 "JavaAdapter", 1, scope);
74 ctor.markAsConstructor(null);
75 if (sealed) {
76 ctor.sealObject();
77 }
78 ctor.exportAsScopeProperty();
79 }
80
81 public Object execIdCall(IdFunctionObject f, Context cx, Scriptable scope,
82 Scriptable thisObj, Object[] args)
83 {
84 if (f.hasTag(FTAG)) {
85 if (f.methodId() == Id_JavaAdapter) {
86 return js_createAdapter(cx, scope, args);
87 }
88 }
89 throw f.unknown();
90 }
91
92 public static Object convertResult(Object result, Class<?> c)
93 {
94 if (result == Undefined.instance &&
95 (c != ScriptRuntime.ObjectClass &&
96 c != ScriptRuntime.StringClass))
97 {
98 // Avoid an error for an undefined value; return null instead.
99 return null;
100 }
101 return Context.jsToJava(result, c);
102 }
103
104 public static Scriptable createAdapterWrapper(Scriptable obj, Object adapter)
105 {
106 Scriptable scope = ScriptableObject.getTopLevelScope(obj);
107 NativeJavaObject res = new NativeJavaObject(scope, adapter, null, true);
108 res.setPrototype(obj);
109 return res;
110 }
111
112 public static Object getAdapterSelf(Class<?> adapterClass, Object adapter)
113 throws NoSuchFieldException, IllegalAccessException
114 {
115 Field self = adapterClass.getDeclaredField("self");
116 return self.get(adapter);
117 }
118
119 static Object js_createAdapter(Context cx, Scriptable scope, Object[] args)
120 {
121 int N = args.length;
122 if (N == 0) {
123 throw ScriptRuntime.typeError0("msg.adapter.zero.args");
124 }
125
126 // Expected arguments:
127 // Any number of NativeJavaClass objects representing the super-class
128 // and/or interfaces to implement, followed by one NativeObject providing
129 // the implementation, followed by any number of arguments to pass on
130 // to the (super-class) constructor.
131
132 int classCount;
133 for (classCount = 0; classCount < N - 1; classCount++) {
134 Object arg = args[classCount];
135 // We explicitly test for NativeObject here since checking for
136 // instanceof ScriptableObject or !(instanceof NativeJavaClass)
137 // would fail for a Java class that isn't found in the class path
138 // as NativeJavaPackage extends ScriptableObject.
139 if (arg instanceof NativeObject) {
140 break;
141 }
142 if (!(arg instanceof NativeJavaClass)) {
143 throw ScriptRuntime.typeError2("msg.not.java.class.arg",
144 String.valueOf(classCount),
145 ScriptRuntime.toString(arg));
146 }
147 }
148 Class<?> superClass = null;
149 Class<?>[] intfs = new Class[classCount];
150 int interfaceCount = 0;
151 for (int i = 0; i < classCount; ++i) {
152 Class<?> c = ((NativeJavaClass) args[i]).getClassObject();
153 if (!c.isInterface()) {
154 if (superClass != null) {
155 throw ScriptRuntime.typeError2("msg.only.one.super",
156 superClass.getName(), c.getName());
157 }
158 superClass = c;
159 } else {
160 intfs[interfaceCount++] = c;
161 }
162 }
163
164 if (superClass == null) {
165 superClass = ScriptRuntime.ObjectClass;
166 }
167
168 Class<?>[] interfaces = new Class[interfaceCount];
169 System.arraycopy(intfs, 0, interfaces, 0, interfaceCount);
170 // next argument is implementation, must be scriptable
171 Scriptable obj = ScriptableObject.ensureScriptable(args[classCount]);
172
173 Class<?> adapterClass = getAdapterClass(scope, superClass, interfaces, obj);
174 Object adapter;
175
176 int argsCount = N - classCount - 1;
177 try {
178 if (argsCount > 0) {
179 // Arguments contain parameters for super-class constructor.
180 // We use the generic Java method lookup logic to find and
181 // invoke the right constructor.
182 Object[] ctorArgs = new Object[argsCount + 2];
183 ctorArgs[0] = obj;
184 ctorArgs[1] = cx.getFactory();
185 System.arraycopy(args, classCount + 1, ctorArgs, 2, argsCount);
186 // TODO: cache class wrapper?
187 NativeJavaClass classWrapper = new NativeJavaClass(scope,
188 adapterClass, true);
189 NativeJavaMethod ctors = classWrapper.members.ctors;
190 int index = ctors.findCachedFunction(cx, ctorArgs);
191 if (index < 0) {
192 String sig = NativeJavaMethod.scriptSignature(args);
193 throw Context.reportRuntimeError2(
194 "msg.no.java.ctor", adapterClass.getName(), sig);
195 }
196
197 // Found the constructor, so try invoking it.
198 adapter = NativeJavaClass.constructInternal(ctorArgs, ctors.methods[index]);
199 } else {
200 Class<?>[] ctorParms = {
201 ScriptRuntime.ScriptableClass,
202 ScriptRuntime.ContextFactoryClass
203 };
204 Object[] ctorArgs = { obj, cx.getFactory() };
205 adapter = adapterClass.getConstructor(ctorParms).newInstance(ctorArgs);
206 }
207
208 Object self = getAdapterSelf(adapterClass, adapter);
209 // Return unwrapped JavaAdapter if it implements Scriptable
210 if (self instanceof Wrapper) {
211 Object unwrapped = ((Wrapper) self).unwrap();
212 if (unwrapped instanceof Scriptable) {
213 if (unwrapped instanceof ScriptableObject) {
214 ScriptRuntime.setObjectProtoAndParent(
215 (ScriptableObject)unwrapped, scope);
216 }
217 return unwrapped;
218 }
219 }
220 return self;
221 } catch (Exception ex) {
222 throw Context.throwAsScriptRuntimeEx(ex);
223 }
224 }
225
226 // Needed by NativeJavaObject serializer
227 public static void writeAdapterObject(Object javaObject,
228 ObjectOutputStream out)
229 throws IOException
230 {
231 Class<?> cl = javaObject.getClass();
232 out.writeObject(cl.getSuperclass().getName());
233
234 Class<?>[] interfaces = cl.getInterfaces();
235 String[] interfaceNames = new String[interfaces.length];
236
237 for (int i=0; i < interfaces.length; i++)
238 interfaceNames[i] = interfaces[i].getName();
239
240 out.writeObject(interfaceNames);
241
242 try {
243 Object delegee = cl.getField("delegee").get(javaObject);
244 out.writeObject(delegee);
245 return;
246 } catch (IllegalAccessException e) {
247 } catch (NoSuchFieldException e) {
248 }
249 throw new IOException();
250 }
251
252 // Needed by NativeJavaObject de-serializer
253 public static Object readAdapterObject(Scriptable self,
254 ObjectInputStream in)
255 throws IOException, ClassNotFoundException
256 {
257 ContextFactory factory;
258 Context cx = Context.getCurrentContext();
259 if (cx != null) {
260 factory = cx.getFactory();
261 } else {
262 factory = null;
263 }
264
265 Class<?> superClass = Class.forName((String)in.readObject());
266
267 String[] interfaceNames = (String[])in.readObject();
268 Class<?>[] interfaces = new Class[interfaceNames.length];
269
270 for (int i=0; i < interfaceNames.length; i++)
271 interfaces[i] = Class.forName(interfaceNames[i]);
272
273 Scriptable delegee = (Scriptable)in.readObject();
274
275 Class<?> adapterClass = getAdapterClass(self, superClass, interfaces,
276 delegee);
277
278 Class<?>[] ctorParms = {
279 ScriptRuntime.ContextFactoryClass,
280 ScriptRuntime.ScriptableClass,
281 ScriptRuntime.ScriptableClass
282 };
283 Object[] ctorArgs = { factory, delegee, self };
284 try {
285 return adapterClass.getConstructor(ctorParms).newInstance(ctorArgs);
286 } catch(InstantiationException e) {
287 } catch(IllegalAccessException e) {
288 } catch(InvocationTargetException e) {
289 } catch(NoSuchMethodException e) {
290 }
291
292 throw new ClassNotFoundException("adapter");
293 }
294
295 private static ObjToIntMap getObjectFunctionNames(Scriptable obj)
296 {
297 Object[] ids = ScriptableObject.getPropertyIds(obj);
298 ObjToIntMap map = new ObjToIntMap(ids.length);
299 for (int i = 0; i != ids.length; ++i) {
300 if (!(ids[i] instanceof String))
301 continue;
302 String id = (String) ids[i];
303 Object value = ScriptableObject.getProperty(obj, id);
304 if (value instanceof Function) {
305 Function f = (Function)value;
306 int length = ScriptRuntime.toInt32(
307 ScriptableObject.getProperty(f, "length"));
308 if (length < 0) {
309 length = 0;
310 }
311 map.put(id, length);
312 }
313 }
314 return map;
315 }
316
317 private static Class<?> getAdapterClass(Scriptable scope, Class<?> superClass,
318 Class<?>[] interfaces, Scriptable obj)
319 {
320 ClassCache cache = ClassCache.get(scope);
321 Map<JavaAdapterSignature,Class<?>> generated
322 = cache.getInterfaceAdapterCacheMap();
323
324 ObjToIntMap names = getObjectFunctionNames(obj);
325 JavaAdapterSignature sig;
326 sig = new JavaAdapterSignature(superClass, interfaces, names);
327 Class<?> adapterClass = generated.get(sig);
328 if (adapterClass == null) {
329 String adapterName = "adapter" + cache.newClassSerialNumber();
330 byte[] code = createAdapterCode(names, adapterName,
331 superClass, interfaces, null);
332
333 adapterClass = loadAdapterClass(adapterName, code);
334 if (cache.isCachingEnabled()) {
335 generated.put(sig, adapterClass);
336 }
337 }
338 return adapterClass;
339 }
340
341 public static byte[] createAdapterCode(ObjToIntMap functionNames,
342 String adapterName,
343 Class<?> superClass,
344 Class<?>[] interfaces,
345 String scriptClassName)
346 {
347 ClassFileWriter cfw = new ClassFileWriter(adapterName,
348 superClass.getName(),
349 "<adapter>");
350 cfw.addField("factory", "Lorg/mozilla/javascript/ContextFactory;",
351 (short) (ClassFileWriter.ACC_PUBLIC |
352 ClassFileWriter.ACC_FINAL));
353 cfw.addField("delegee", "Lorg/mozilla/javascript/Scriptable;",
354 (short) (ClassFileWriter.ACC_PUBLIC |
355 ClassFileWriter.ACC_FINAL));
356 cfw.addField("self", "Lorg/mozilla/javascript/Scriptable;",
357 (short) (ClassFileWriter.ACC_PUBLIC |
358 ClassFileWriter.ACC_FINAL));
359 int interfacesCount = interfaces == null ? 0 : interfaces.length;
360 for (int i=0; i < interfacesCount; i++) {
361 if (interfaces[i] != null)
362 cfw.addInterface(interfaces[i].getName());
363 }
364
365 String superName = superClass.getName().replace('.', '/');
366 Constructor<?>[] ctors = superClass.getDeclaredConstructors();
367 for (Constructor<?> ctor : ctors) {
368 int mod = ctor.getModifiers();
369 if (Modifier.isPublic(mod) || Modifier.isProtected(mod)) {
370 generateCtor(cfw, adapterName, superName, ctor);
371 }
372 }
373 generateSerialCtor(cfw, adapterName, superName);
374 if (scriptClassName != null) {
375 generateEmptyCtor(cfw, adapterName, superName, scriptClassName);
376 }
377
378 ObjToIntMap generatedOverrides = new ObjToIntMap();
379 ObjToIntMap generatedMethods = new ObjToIntMap();
380
381 // generate methods to satisfy all specified interfaces.
382 for (int i = 0; i < interfacesCount; i++) {
383 Method[] methods = interfaces[i].getMethods();
384 for (int j = 0; j < methods.length; j++) {
385 Method method = methods[j];
386 int mods = method.getModifiers();
387 if (Modifier.isStatic(mods) || Modifier.isFinal(mods)) {
388 continue;
389 }
390 String methodName = method.getName();
391 Class<?>[] argTypes = method.getParameterTypes();
392 if (!functionNames.has(methodName)) {
393 try {
394 superClass.getMethod(methodName, argTypes);
395 // The class we're extending implements this method and
396 // the JavaScript object doesn't have an override. See
397 // bug 61226.
398 continue;
399 } catch (NoSuchMethodException e) {
400 // Not implemented by superclass; fall through
401 }
402 }
403 // make sure to generate only one instance of a particular
404 // method/signature.
405 String methodSignature = getMethodSignature(method, argTypes);
406 String methodKey = methodName + methodSignature;
407 if (! generatedOverrides.has(methodKey)) {
408 generateMethod(cfw, adapterName, methodName, argTypes,
409 method.getReturnType(), true);
410 generatedOverrides.put(methodKey, 0);
411 generatedMethods.put(methodName, 0);
412 }
413 }
414 }
415
416 // Now, go through the superclass's methods, checking for abstract
417 // methods or additional methods to override.
418
419 // generate any additional overrides that the object might contain.
420 Method[] methods = getOverridableMethods(superClass);
421 for (int j = 0; j < methods.length; j++) {
422 Method method = methods[j];
423 int mods = method.getModifiers();
424 // if a method is marked abstract, must implement it or the
425 // resulting class won't be instantiable. otherwise, if the object
426 // has a property of the same name, then an override is intended.
427 boolean isAbstractMethod = Modifier.isAbstract(mods);
428 String methodName = method.getName();
429 if (isAbstractMethod || functionNames.has(methodName)) {
430 // make sure to generate only one instance of a particular
431 // method/signature.
432 Class<?>[] argTypes = method.getParameterTypes();
433 String methodSignature = getMethodSignature(method, argTypes);
434 String methodKey = methodName + methodSignature;
435 if (! generatedOverrides.has(methodKey)) {
436 generateMethod(cfw, adapterName, methodName, argTypes,
437 method.getReturnType(), true);
438 generatedOverrides.put(methodKey, 0);
439 generatedMethods.put(methodName, 0);
440
441 // if a method was overridden, generate a "super$method"
442 // which lets the delegate call the superclass' version.
443 if (!isAbstractMethod) {
444 generateSuper(cfw, adapterName, superName,
445 methodName, methodSignature,
446 argTypes, method.getReturnType());
447 }
448 }
449 }
450 }
451
452 // Generate Java methods for remaining properties that are not
453 // overrides.
454 ObjToIntMap.Iterator iter = new ObjToIntMap.Iterator(functionNames);
455 for (iter.start(); !iter.done(); iter.next()) {
456 String functionName = (String)iter.getKey();
457 if (generatedMethods.has(functionName))
458 continue;
459 int length = iter.getValue();
460 Class<?>[] parms = new Class[length];
461 for (int k=0; k < length; k++)
462 parms[k] = ScriptRuntime.ObjectClass;
463 generateMethod(cfw, adapterName, functionName, parms,
464 ScriptRuntime.ObjectClass, false);
465 }
466 return cfw.toByteArray();
467 }
468
469 static Method[] getOverridableMethods(Class<?> clazz)
470 {
471 ArrayList<Method> list = new ArrayList<Method>();
472 HashSet<String> skip = new HashSet<String>();
473 // Check superclasses before interfaces so we always choose
474 // implemented methods over abstract ones, even if a subclass
475 // re-implements an interface already implemented in a superclass
476 // (e.g. java.util.ArrayList)
477 for (Class<?> c = clazz; c != null; c = c.getSuperclass()) {
478 appendOverridableMethods(c, list, skip);
479 }
480 for (Class<?> c = clazz; c != null; c = c.getSuperclass()) {
481 for (Class<?> intf: c.getInterfaces())
482 appendOverridableMethods(intf, list, skip);
483 }
484 return list.toArray(new Method[list.size()]);
485 }
486
487 private static void appendOverridableMethods(Class<?> c,
488 ArrayList<Method> list, HashSet<String> skip)
489 {
490 Method[] methods = c.getDeclaredMethods();
491 for (int i = 0; i < methods.length; i++) {
492 String methodKey = methods[i].getName() +
493 getMethodSignature(methods[i],
494 methods[i].getParameterTypes());
495 if (skip.contains(methodKey))
496 continue; // skip this method
497 int mods = methods[i].getModifiers();
498 if (Modifier.isStatic(mods))
499 continue;
500 if (Modifier.isFinal(mods)) {
501 // Make sure we don't add a final method to the list
502 // of overridable methods.
503 skip.add(methodKey);
504 continue;
505 }
506 if (Modifier.isPublic(mods) || Modifier.isProtected(mods)) {
507 list.add(methods[i]);
508 skip.add(methodKey);
509 }
510 }
511 }
512
513 static Class<?> loadAdapterClass(String className, byte[] classBytes)
514 {
515 Object staticDomain;
516 Class<?> domainClass = SecurityController.getStaticSecurityDomainClass();
517 if(domainClass == CodeSource.class || domainClass == ProtectionDomain.class) {
518 // use the calling script's security domain if available
519 ProtectionDomain protectionDomain = SecurityUtilities.getScriptProtectionDomain();
520 if (protectionDomain == null) {
521 protectionDomain = JavaAdapter.class.getProtectionDomain();
522 }
523 if(domainClass == CodeSource.class) {
524 staticDomain = protectionDomain == null ? null : protectionDomain.getCodeSource();
525 }
526 else {
527 staticDomain = protectionDomain;
528 }
529 }
530 else {
531 staticDomain = null;
532 }
533 GeneratedClassLoader loader = SecurityController.createLoader(null,
534 staticDomain);
535 Class<?> result = loader.defineClass(className, classBytes);
536 loader.linkClass(result);
537 return result;
538 }
539
540 public static Function getFunction(Scriptable obj, String functionName)
541 {
542 Object x = ScriptableObject.getProperty(obj, functionName);
543 if (x == Scriptable.NOT_FOUND) {
544 // This method used to swallow the exception from calling
545 // an undefined method. People have come to depend on this
546 // somewhat dubious behavior. It allows people to avoid
547 // implementing listener methods that they don't care about,
548 // for instance.
549 return null;
550 }
551 if (!(x instanceof Function))
552 throw ScriptRuntime.notFunctionError(x, functionName);
553
554 return (Function)x;
555 }
556
557 /**
558 * Utility method which dynamically binds a Context to the current thread,
559 * if none already exists.
560 */
561 public static Object callMethod(ContextFactory factory,
562 final Scriptable thisObj,
563 final Function f, final Object[] args,
564 final long argsToWrap)
565 {
566 if (f == null) {
567 // See comments in getFunction
568 return null;
569 }
570 if (factory == null) {
571 factory = ContextFactory.getGlobal();
572 }
573
574 final Scriptable scope = f.getParentScope();
575 if (argsToWrap == 0) {
576 return Context.call(factory, f, scope, thisObj, args);
577 }
578
579 Context cx = Context.getCurrentContext();
580 if (cx != null) {
581 return doCall(cx, scope, thisObj, f, args, argsToWrap);
582 } else {
583 return factory.call(new ContextAction() {
584 public Object run(Context cx)
585 {
586 return doCall(cx, scope, thisObj, f, args, argsToWrap);
587 }
588 });
589 }
590 }
591
592 private static Object doCall(Context cx, Scriptable scope,
593 Scriptable thisObj, Function f,
594 Object[] args, long argsToWrap)
595 {
596 // Wrap the rest of objects
597 for (int i = 0; i != args.length; ++i) {
598 if (0 != (argsToWrap & (1 << i))) {
599 Object arg = args[i];
600 if (!(arg instanceof Scriptable)) {
601 args[i] = cx.getWrapFactory().wrap(cx, scope, arg,
602 null);
603 }
604 }
605 }
606 return f.call(cx, scope, thisObj, args);
607 }
608
609 public static Scriptable runScript(final Script script)
610 {
611 return (Scriptable)ContextFactory.getGlobal().call(
612 new ContextAction() {
613 public Object run(Context cx)
614 {
615 ScriptableObject global = ScriptRuntime.getGlobal(cx);
616 script.exec(cx, global);
617 return global;
618 }
619 });
620 }
621
622 private static void generateCtor(ClassFileWriter cfw, String adapterName,
623 String superName, Constructor<?> superCtor)
624 {
625 short locals = 3; // this + factory + delegee
626 Class<?>[] parameters = superCtor.getParameterTypes();
627
628 // Note that we swapped arguments in app-facing constructors to avoid
629 // conflicting signatures with serial constructor defined below.
630 if (parameters.length == 0) {
631 cfw.startMethod("<init>",
632 "(Lorg/mozilla/javascript/Scriptable;"
633 +"Lorg/mozilla/javascript/ContextFactory;)V",
634 ClassFileWriter.ACC_PUBLIC);
635
636 // Invoke base class constructor
637 cfw.add(ByteCode.ALOAD_0); // this
638 cfw.addInvoke(ByteCode.INVOKESPECIAL, superName, "<init>", "()V");
639 } else {
640 StringBuilder sig = new StringBuilder(
641 "(Lorg/mozilla/javascript/Scriptable;"
642 +"Lorg/mozilla/javascript/ContextFactory;");
643 int marker = sig.length(); // lets us reuse buffer for super signature
644 for (Class<?> c : parameters) {
645 appendTypeString(sig, c);
646 }
647 sig.append(")V");
648 cfw.startMethod("<init>", sig.toString(), ClassFileWriter.ACC_PUBLIC);
649
650 // Invoke base class constructor
651 cfw.add(ByteCode.ALOAD_0); // this
652 short paramOffset = 3;
653 for (Class<?> parameter : parameters) {
654 paramOffset += generatePushParam(cfw, paramOffset, parameter);
655 }
656 locals = paramOffset;
657 sig.delete(1, marker);
658 cfw.addInvoke(ByteCode.INVOKESPECIAL, superName, "<init>", sig.toString());
659 }
660
661 // Save parameter in instance variable "delegee"
662 cfw.add(ByteCode.ALOAD_0); // this
663 cfw.add(ByteCode.ALOAD_1); // first arg: Scriptable delegee
664 cfw.add(ByteCode.PUTFIELD, adapterName, "delegee",
665 "Lorg/mozilla/javascript/Scriptable;");
666
667 // Save parameter in instance variable "factory"
668 cfw.add(ByteCode.ALOAD_0); // this
669 cfw.add(ByteCode.ALOAD_2); // second arg: ContextFactory instance
670 cfw.add(ByteCode.PUTFIELD, adapterName, "factory",
671 "Lorg/mozilla/javascript/ContextFactory;");
672
673 cfw.add(ByteCode.ALOAD_0); // this for the following PUTFIELD for self
674 // create a wrapper object to be used as "this" in method calls
675 cfw.add(ByteCode.ALOAD_1); // the Scriptable delegee
676 cfw.add(ByteCode.ALOAD_0); // this
677 cfw.addInvoke(ByteCode.INVOKESTATIC,
678 "org/mozilla/javascript/JavaAdapter",
679 "createAdapterWrapper",
680 "(Lorg/mozilla/javascript/Scriptable;"
681 +"Ljava/lang/Object;"
682 +")Lorg/mozilla/javascript/Scriptable;");
683 cfw.add(ByteCode.PUTFIELD, adapterName, "self",
684 "Lorg/mozilla/javascript/Scriptable;");
685
686 cfw.add(ByteCode.RETURN);
687 cfw.stopMethod(locals);
688 }
689
690 private static void generateSerialCtor(ClassFileWriter cfw,
691 String adapterName,
692 String superName)
693 {
694 cfw.startMethod("<init>",
695 "(Lorg/mozilla/javascript/ContextFactory;"
696 +"Lorg/mozilla/javascript/Scriptable;"
697 +"Lorg/mozilla/javascript/Scriptable;"
698 +")V",
699 ClassFileWriter.ACC_PUBLIC);
700
701 // Invoke base class constructor
702 cfw.add(ByteCode.ALOAD_0); // this
703 cfw.addInvoke(ByteCode.INVOKESPECIAL, superName, "<init>", "()V");
704
705 // Save parameter in instance variable "factory"
706 cfw.add(ByteCode.ALOAD_0); // this
707 cfw.add(ByteCode.ALOAD_1); // first arg: ContextFactory instance
708 cfw.add(ByteCode.PUTFIELD, adapterName, "factory",
709 "Lorg/mozilla/javascript/ContextFactory;");
710
711 // Save parameter in instance variable "delegee"
712 cfw.add(ByteCode.ALOAD_0); // this
713 cfw.add(ByteCode.ALOAD_2); // second arg: Scriptable delegee
714 cfw.add(ByteCode.PUTFIELD, adapterName, "delegee",
715 "Lorg/mozilla/javascript/Scriptable;");
716 // save self
717 cfw.add(ByteCode.ALOAD_0); // this
718 cfw.add(ByteCode.ALOAD_3); // third arg: Scriptable self
719 cfw.add(ByteCode.PUTFIELD, adapterName, "self",
720 "Lorg/mozilla/javascript/Scriptable;");
721
722 cfw.add(ByteCode.RETURN);
723 cfw.stopMethod((short)4); // 4: this + factory + delegee + self
724 }
725
726 private static void generateEmptyCtor(ClassFileWriter cfw,
727 String adapterName,
728 String superName,
729 String scriptClassName)
730 {
731 cfw.startMethod("<init>", "()V", ClassFileWriter.ACC_PUBLIC);
732
733 // Invoke base class constructor
734 cfw.add(ByteCode.ALOAD_0); // this
735 cfw.addInvoke(ByteCode.INVOKESPECIAL, superName, "<init>", "()V");
736
737 // Set factory to null to use current global when necessary
738 cfw.add(ByteCode.ALOAD_0);
739 cfw.add(ByteCode.ACONST_NULL);
740 cfw.add(ByteCode.PUTFIELD, adapterName, "factory",
741 "Lorg/mozilla/javascript/ContextFactory;");
742
743 // Load script class
744 cfw.add(ByteCode.NEW, scriptClassName);
745 cfw.add(ByteCode.DUP);
746 cfw.addInvoke(ByteCode.INVOKESPECIAL, scriptClassName, "<init>", "()V");
747
748 // Run script and save resulting scope
749 cfw.addInvoke(ByteCode.INVOKESTATIC,
750 "org/mozilla/javascript/JavaAdapter",
751 "runScript",
752 "(Lorg/mozilla/javascript/Script;"
753 +")Lorg/mozilla/javascript/Scriptable;");
754 cfw.add(ByteCode.ASTORE_1);
755
756 // Save the Scriptable in instance variable "delegee"
757 cfw.add(ByteCode.ALOAD_0); // this
758 cfw.add(ByteCode.ALOAD_1); // the Scriptable
759 cfw.add(ByteCode.PUTFIELD, adapterName, "delegee",
760 "Lorg/mozilla/javascript/Scriptable;");
761
762 cfw.add(ByteCode.ALOAD_0); // this for the following PUTFIELD for self
763 // create a wrapper object to be used as "this" in method calls
764 cfw.add(ByteCode.ALOAD_1); // the Scriptable
765 cfw.add(ByteCode.ALOAD_0); // this
766 cfw.addInvoke(ByteCode.INVOKESTATIC,
767 "org/mozilla/javascript/JavaAdapter",
768 "createAdapterWrapper",
769 "(Lorg/mozilla/javascript/Scriptable;"
770 +"Ljava/lang/Object;"
771 +")Lorg/mozilla/javascript/Scriptable;");
772 cfw.add(ByteCode.PUTFIELD, adapterName, "self",
773 "Lorg/mozilla/javascript/Scriptable;");
774
775 cfw.add(ByteCode.RETURN);
776 cfw.stopMethod((short)2); // this + delegee
777 }
778
779 /**
780 * Generates code to wrap Java arguments into Object[].
781 * Non-primitive Java types are left as-is pending conversion
782 * in the helper method. Leaves the array object on the top of the stack.
783 */
784 static void generatePushWrappedArgs(ClassFileWriter cfw,
785 Class<?>[] argTypes,
786 int arrayLength)
787 {
788 // push arguments
789 cfw.addPush(arrayLength);
790 cfw.add(ByteCode.ANEWARRAY, "java/lang/Object");
791 int paramOffset = 1;
792 for (int i = 0; i != argTypes.length; ++i) {
793 cfw.add(ByteCode.DUP); // duplicate array reference
794 cfw.addPush(i);
795 paramOffset += generateWrapArg(cfw, paramOffset, argTypes[i]);
796 cfw.add(ByteCode.AASTORE);
797 }
798 }
799
800 /**
801 * Generates code to wrap Java argument into Object.
802 * Non-primitive Java types are left unconverted pending conversion
803 * in the helper method. Leaves the wrapper object on the top of the stack.
804 */
805 private static int generateWrapArg(ClassFileWriter cfw, int paramOffset,
806 Class<?> argType)
807 {
808 int size = 1;
809 if (!argType.isPrimitive()) {
810 cfw.add(ByteCode.ALOAD, paramOffset);
811
812 } else if (argType == Boolean.TYPE) {
813 // wrap boolean values with java.lang.Boolean.
814 cfw.add(ByteCode.NEW, "java/lang/Boolean");
815 cfw.add(ByteCode.DUP);
816 cfw.add(ByteCode.ILOAD, paramOffset);
817 cfw.addInvoke(ByteCode.INVOKESPECIAL, "java/lang/Boolean",
818 "<init>", "(Z)V");
819
820 } else if (argType == Character.TYPE) {
821 // Create a string of length 1 using the character parameter.
822 cfw.add(ByteCode.ILOAD, paramOffset);
823 cfw.addInvoke(ByteCode.INVOKESTATIC, "java/lang/String",
824 "valueOf", "(C)Ljava/lang/String;");
825
826 } else {
827 // convert all numeric values to java.lang.Double.
828 cfw.add(ByteCode.NEW, "java/lang/Double");
829 cfw.add(ByteCode.DUP);
830 String typeName = argType.getName();
831 switch (typeName.charAt(0)) {
832 case 'b':
833 case 's':
834 case 'i':
835 // load an int value, convert to double.
836 cfw.add(ByteCode.ILOAD, paramOffset);
837 cfw.add(ByteCode.I2D);
838 break;
839 case 'l':
840 // load a long, convert to double.
841 cfw.add(ByteCode.LLOAD, paramOffset);
842 cfw.add(ByteCode.L2D);
843 size = 2;
844 break;
845 case 'f':
846 // load a float, convert to double.
847 cfw.add(ByteCode.FLOAD, paramOffset);
848 cfw.add(ByteCode.F2D);
849 break;
850 case 'd':
851 cfw.add(ByteCode.DLOAD, paramOffset);
852 size = 2;
853 break;
854 }
855 cfw.addInvoke(ByteCode.INVOKESPECIAL, "java/lang/Double",
856 "<init>", "(D)V");
857 }
858 return size;
859 }
860
861 /**
862 * Generates code to convert a wrapped value type to a primitive type.
863 * Handles unwrapping java.lang.Boolean, and java.lang.Number types.
864 * Generates the appropriate RETURN bytecode.
865 */
866 static void generateReturnResult(ClassFileWriter cfw, Class<?> retType,
867 boolean callConvertResult)
868 {
869 // wrap boolean values with java.lang.Boolean, convert all other
870 // primitive values to java.lang.Double.
871 if (retType == Void.TYPE) {
872 cfw.add(ByteCode.POP);
873 cfw.add(ByteCode.RETURN);
874
875 } else if (retType == Boolean.TYPE) {
876 cfw.addInvoke(ByteCode.INVOKESTATIC,
877 "org/mozilla/javascript/Context",
878 "toBoolean", "(Ljava/lang/Object;)Z");
879 cfw.add(ByteCode.IRETURN);
880
881 } else if (retType == Character.TYPE) {
882 // characters are represented as strings in JavaScript.
883 // return the first character.
884 // first convert the value to a string if possible.
885 cfw.addInvoke(ByteCode.INVOKESTATIC,
886 "org/mozilla/javascript/Context",
887 "toString",
888 "(Ljava/lang/Object;)Ljava/lang/String;");
889 cfw.add(ByteCode.ICONST_0);
890 cfw.addInvoke(ByteCode.INVOKEVIRTUAL, "java/lang/String",
891 "charAt", "(I)C");
892 cfw.add(ByteCode.IRETURN);
893
894 } else if (retType.isPrimitive()) {
895 cfw.addInvoke(ByteCode.INVOKESTATIC,
896 "org/mozilla/javascript/Context",
897 "toNumber", "(Ljava/lang/Object;)D");
898 String typeName = retType.getName();
899 switch (typeName.charAt(0)) {
900 case 'b':
901 case 's':
902 case 'i':
903 cfw.add(ByteCode.D2I);
904 cfw.add(ByteCode.IRETURN);
905 break;
906 case 'l':
907 cfw.add(ByteCode.D2L);
908 cfw.add(ByteCode.LRETURN);
909 break;
910 case 'f':
911 cfw.add(ByteCode.D2F);
912 cfw.add(ByteCode.FRETURN);
913 break;
914 case 'd':
915 cfw.add(ByteCode.DRETURN);
916 break;
917 default:
918 throw new RuntimeException("Unexpected return type " +
919 retType.toString());
920 }
921
922 } else {
923 String retTypeStr = retType.getName();
924 if (callConvertResult) {
925 cfw.addLoadConstant(retTypeStr);
926 cfw.addInvoke(ByteCode.INVOKESTATIC,
927 "java/lang/Class",
928 "forName",
929 "(Ljava/lang/String;)Ljava/lang/Class;");
930
931 cfw.addInvoke(ByteCode.INVOKESTATIC,
932 "org/mozilla/javascript/JavaAdapter",
933 "convertResult",
934 "(Ljava/lang/Object;"
935 +"Ljava/lang/Class;"
936 +")Ljava/lang/Object;");
937 }
938 // Now cast to return type
939 cfw.add(ByteCode.CHECKCAST, retTypeStr);
940 cfw.add(ByteCode.ARETURN);
941 }
942 }
943
944 private static void generateMethod(ClassFileWriter cfw, String genName,
945 String methodName, Class<?>[] parms,
946 Class<?> returnType, boolean convertResult)
947 {
948 StringBuilder sb = new StringBuilder();
949 int paramsEnd = appendMethodSignature(parms, returnType, sb);
950 String methodSignature = sb.toString();
951 cfw.startMethod(methodName, methodSignature,
952 ClassFileWriter.ACC_PUBLIC);
953
954 // Prepare stack to call method
955
956 // push factory
957 cfw.add(ByteCode.ALOAD_0);
958 cfw.add(ByteCode.GETFIELD, genName, "factory",
959 "Lorg/mozilla/javascript/ContextFactory;");
960
961 // push self
962 cfw.add(ByteCode.ALOAD_0);
963 cfw.add(ByteCode.GETFIELD, genName, "self",
964 "Lorg/mozilla/javascript/Scriptable;");
965
966 // push function
967 cfw.add(ByteCode.ALOAD_0);
968 cfw.add(ByteCode.GETFIELD, genName, "delegee",
969 "Lorg/mozilla/javascript/Scriptable;");
970 cfw.addPush(methodName);
971 cfw.addInvoke(ByteCode.INVOKESTATIC,
972 "org/mozilla/javascript/JavaAdapter",
973 "getFunction",
974 "(Lorg/mozilla/javascript/Scriptable;"
975 +"Ljava/lang/String;"
976 +")Lorg/mozilla/javascript/Function;");
977
978 // push arguments
979 generatePushWrappedArgs(cfw, parms, parms.length);
980
981 // push bits to indicate which parameters should be wrapped
982 if (parms.length > 64) {
983 // If it will be an issue, then passing a static boolean array
984 // can be an option, but for now using simple bitmask
985 throw Context.reportRuntimeError0(
986 "JavaAdapter can not subclass methods with more then"
987 +" 64 arguments.");
988 }
989 long convertionMask = 0;
990 for (int i = 0; i != parms.length; ++i) {
991 if (!parms[i].isPrimitive()) {
992 convertionMask |= (1 << i);
993 }
994 }
995 cfw.addPush(convertionMask);
996
997 // go through utility method, which creates a Context to run the
998 // method in.
999 cfw.addInvoke(ByteCode.INVOKESTATIC,
1000 "org/mozilla/javascript/JavaAdapter",
1001 "callMethod",
1002 "(Lorg/mozilla/javascript/ContextFactory;"
1003 +"Lorg/mozilla/javascript/Scriptable;"
1004 +"Lorg/mozilla/javascript/Function;"
1005 +"[Ljava/lang/Object;"
1006 +"J"
1007 +")Ljava/lang/Object;");
1008
1009 generateReturnResult(cfw, returnType, convertResult);
1010
1011 cfw.stopMethod((short)paramsEnd);
1012 }
1013
1014 /**
1015 * Generates code to push typed parameters onto the operand stack
1016 * prior to a direct Java method call.
1017 */
1018 private static int generatePushParam(ClassFileWriter cfw, int paramOffset,
1019 Class<?> paramType)
1020 {
1021 if (!paramType.isPrimitive()) {
1022 cfw.addALoad(paramOffset);
1023 return 1;
1024 }
1025 String typeName = paramType.getName();
1026 switch (typeName.charAt(0)) {
1027 case 'z':
1028 case 'b':
1029 case 'c':
1030 case 's':
1031 case 'i':
1032 // load an int value, convert to double.
1033 cfw.addILoad(paramOffset);
1034 return 1;
1035 case 'l':
1036 // load a long, convert to double.
1037 cfw.addLLoad(paramOffset);
1038 return 2;
1039 case 'f':
1040 // load a float, convert to double.
1041 cfw.addFLoad(paramOffset);
1042 return 1;
1043 case 'd':
1044 cfw.addDLoad(paramOffset);
1045 return 2;
1046 }
1047 throw Kit.codeBug();
1048 }
1049
1050 /**
1051 * Generates code to return a Java type, after calling a Java method
1052 * that returns the same type.
1053 * Generates the appropriate RETURN bytecode.
1054 */
1055 private static void generatePopResult(ClassFileWriter cfw,
1056 Class<?> retType)
1057 {
1058 if (retType.isPrimitive()) {
1059 String typeName = retType.getName();
1060 switch (typeName.charAt(0)) {
1061 case 'b':
1062 case 'c':
1063 case 's':
1064 case 'i':
1065 case 'z':
1066 cfw.add(ByteCode.IRETURN);
1067 break;
1068 case 'l':
1069 cfw.add(ByteCode.LRETURN);
1070 break;
1071 case 'f':
1072 cfw.add(ByteCode.FRETURN);
1073 break;
1074 case 'd':
1075 cfw.add(ByteCode.DRETURN);
1076 break;
1077 }
1078 } else {
1079 cfw.add(ByteCode.ARETURN);
1080 }
1081 }
1082
1083 /**
1084 * Generates a method called "super$methodName()" which can be called
1085 * from JavaScript that is equivalent to calling "super.methodName()"
1086 * from Java. Eventually, this may be supported directly in JavaScript.
1087 */
1088 private static void generateSuper(ClassFileWriter cfw,
1089 String genName, String superName,
1090 String methodName, String methodSignature,
1091 Class<?>[] parms, Class<?> returnType)
1092 {
1093 cfw.startMethod("super$" + methodName, methodSignature,
1094 ClassFileWriter.ACC_PUBLIC);
1095
1096 // push "this"
1097 cfw.add(ByteCode.ALOAD, 0);
1098
1099 // push the rest of the parameters.
1100 int paramOffset = 1;
1101 for (Class<?> parm : parms) {
1102 paramOffset += generatePushParam(cfw, paramOffset, parm);
1103 }
1104
1105 // call the superclass implementation of the method.
1106 cfw.addInvoke(ByteCode.INVOKESPECIAL,
1107 superName,
1108 methodName,
1109 methodSignature);
1110
1111 // now, handle the return type appropriately.
1112 Class<?> retType = returnType;
1113 if (!retType.equals(Void.TYPE)) {
1114 generatePopResult(cfw, retType);
1115 } else {
1116 cfw.add(ByteCode.RETURN);
1117 }
1118 cfw.stopMethod((short)(paramOffset + 1));
1119 }
1120
1121 /**
1122 * Returns a fully qualified method name concatenated with its signature.
1123 */
1124 private static String getMethodSignature(Method method, Class<?>[] argTypes)
1125 {
1126 StringBuilder sb = new StringBuilder();
1127 appendMethodSignature(argTypes, method.getReturnType(), sb);
1128 return sb.toString();
1129 }
1130
1131 static int appendMethodSignature(Class<?>[] argTypes,
1132 Class<?> returnType,
1133 StringBuilder sb)
1134 {
1135 sb.append('(');
1136 int firstLocal = 1 + argTypes.length; // includes this.
1137 for (Class<?> type : argTypes) {
1138 appendTypeString(sb, type);
1139 if (type == Long.TYPE || type == Double.TYPE) {
1140 // adjust for double slot
1141 ++firstLocal;
1142 }
1143 }
1144 sb.append(')');
1145 appendTypeString(sb, returnType);
1146 return firstLocal;
1147 }
1148
1149 private static StringBuilder appendTypeString(StringBuilder sb, Class<?> type)
1150 {
1151 while (type.isArray()) {
1152 sb.append('[');
1153 type = type.getComponentType();
1154 }
1155 if (type.isPrimitive()) {
1156 char typeLetter;
1157 if (type == Boolean.TYPE) {
1158 typeLetter = 'Z';
1159 } else if (type == Long.TYPE) {
1160 typeLetter = 'J';
1161 } else {
1162 String typeName = type.getName();
1163 typeLetter = Character.toUpperCase(typeName.charAt(0));
1164 }
1165 sb.append(typeLetter);
1166 } else {
1167 sb.append('L');
1168 sb.append(type.getName().replace('.', '/'));
1169 sb.append(';');
1170 }
1171 return sb;
1172 }
1173
1174 static int[] getArgsToConvert(Class<?>[] argTypes)
1175 {
1176 int count = 0;
1177 for (int i = 0; i != argTypes.length; ++i) {
1178 if (!argTypes[i].isPrimitive())
1179 ++count;
1180 }
1181 if (count == 0)
1182 return null;
1183 int[] array = new int[count];
1184 count = 0;
1185 for (int i = 0; i != argTypes.length; ++i) {
1186 if (!argTypes[i].isPrimitive())
1187 array[count++] = i;
1188 }
1189 return array;
1190 }
1191
1192 private static final Object FTAG = "JavaAdapter";
1193 private static final int Id_JavaAdapter = 1;
1194 }