1/*
2 * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.  Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26package java.lang.invoke;
27
28import static java.lang.invoke.MethodHandleStatics.UNSAFE;
29
30final class VarHandles {
31
32    static VarHandle makeFieldHandle(MemberName f, Class<?> refc, Class<?> type, boolean isWriteAllowedOnFinalFields) {
33        if (!f.isStatic()) {
34            long foffset = MethodHandleNatives.objectFieldOffset(f);
35            if (!type.isPrimitive()) {
36                return f.isFinal() && !isWriteAllowedOnFinalFields
37                       ? new VarHandleObjects.FieldInstanceReadOnly(refc, foffset, type)
38                       : new VarHandleObjects.FieldInstanceReadWrite(refc, foffset, type);
39            }
40            else if (type == boolean.class) {
41                return f.isFinal() && !isWriteAllowedOnFinalFields
42                       ? new VarHandleBooleans.FieldInstanceReadOnly(refc, foffset)
43                       : new VarHandleBooleans.FieldInstanceReadWrite(refc, foffset);
44            }
45            else if (type == byte.class) {
46                return f.isFinal() && !isWriteAllowedOnFinalFields
47                       ? new VarHandleBytes.FieldInstanceReadOnly(refc, foffset)
48                       : new VarHandleBytes.FieldInstanceReadWrite(refc, foffset);
49            }
50            else if (type == short.class) {
51                return f.isFinal() && !isWriteAllowedOnFinalFields
52                       ? new VarHandleShorts.FieldInstanceReadOnly(refc, foffset)
53                       : new VarHandleShorts.FieldInstanceReadWrite(refc, foffset);
54            }
55            else if (type == char.class) {
56                return f.isFinal() && !isWriteAllowedOnFinalFields
57                       ? new VarHandleChars.FieldInstanceReadOnly(refc, foffset)
58                       : new VarHandleChars.FieldInstanceReadWrite(refc, foffset);
59            }
60            else if (type == int.class) {
61                return f.isFinal() && !isWriteAllowedOnFinalFields
62                       ? new VarHandleInts.FieldInstanceReadOnly(refc, foffset)
63                       : new VarHandleInts.FieldInstanceReadWrite(refc, foffset);
64            }
65            else if (type == long.class) {
66                return f.isFinal() && !isWriteAllowedOnFinalFields
67                       ? new VarHandleLongs.FieldInstanceReadOnly(refc, foffset)
68                       : new VarHandleLongs.FieldInstanceReadWrite(refc, foffset);
69            }
70            else if (type == float.class) {
71                return f.isFinal() && !isWriteAllowedOnFinalFields
72                       ? new VarHandleFloats.FieldInstanceReadOnly(refc, foffset)
73                       : new VarHandleFloats.FieldInstanceReadWrite(refc, foffset);
74            }
75            else if (type == double.class) {
76                return f.isFinal() && !isWriteAllowedOnFinalFields
77                       ? new VarHandleDoubles.FieldInstanceReadOnly(refc, foffset)
78                       : new VarHandleDoubles.FieldInstanceReadWrite(refc, foffset);
79            }
80            else {
81                throw new UnsupportedOperationException();
82            }
83        }
84        else {
85            // TODO This is not lazy on first invocation
86            // and might cause some circular initialization issues
87
88            // Replace with something similar to direct method handles
89            // where a barrier is used then elided after use
90
91            if (UNSAFE.shouldBeInitialized(refc))
92                UNSAFE.ensureClassInitialized(refc);
93
94            Object base = MethodHandleNatives.staticFieldBase(f);
95            long foffset = MethodHandleNatives.staticFieldOffset(f);
96            if (!type.isPrimitive()) {
97                return f.isFinal() && !isWriteAllowedOnFinalFields
98                       ? new VarHandleObjects.FieldStaticReadOnly(base, foffset, type)
99                       : new VarHandleObjects.FieldStaticReadWrite(base, foffset, type);
100            }
101            else if (type == boolean.class) {
102                return f.isFinal() && !isWriteAllowedOnFinalFields
103                       ? new VarHandleBooleans.FieldStaticReadOnly(base, foffset)
104                       : new VarHandleBooleans.FieldStaticReadWrite(base, foffset);
105            }
106            else if (type == byte.class) {
107                return f.isFinal() && !isWriteAllowedOnFinalFields
108                       ? new VarHandleBytes.FieldStaticReadOnly(base, foffset)
109                       : new VarHandleBytes.FieldStaticReadWrite(base, foffset);
110            }
111            else if (type == short.class) {
112                return f.isFinal() && !isWriteAllowedOnFinalFields
113                       ? new VarHandleShorts.FieldStaticReadOnly(base, foffset)
114                       : new VarHandleShorts.FieldStaticReadWrite(base, foffset);
115            }
116            else if (type == char.class) {
117                return f.isFinal() && !isWriteAllowedOnFinalFields
118                       ? new VarHandleChars.FieldStaticReadOnly(base, foffset)
119                       : new VarHandleChars.FieldStaticReadWrite(base, foffset);
120            }
121            else if (type == int.class) {
122                return f.isFinal() && !isWriteAllowedOnFinalFields
123                       ? new VarHandleInts.FieldStaticReadOnly(base, foffset)
124                       : new VarHandleInts.FieldStaticReadWrite(base, foffset);
125            }
126            else if (type == long.class) {
127                return f.isFinal() && !isWriteAllowedOnFinalFields
128                       ? new VarHandleLongs.FieldStaticReadOnly(base, foffset)
129                       : new VarHandleLongs.FieldStaticReadWrite(base, foffset);
130            }
131            else if (type == float.class) {
132                return f.isFinal() && !isWriteAllowedOnFinalFields
133                       ? new VarHandleFloats.FieldStaticReadOnly(base, foffset)
134                       : new VarHandleFloats.FieldStaticReadWrite(base, foffset);
135            }
136            else if (type == double.class) {
137                return f.isFinal() && !isWriteAllowedOnFinalFields
138                       ? new VarHandleDoubles.FieldStaticReadOnly(base, foffset)
139                       : new VarHandleDoubles.FieldStaticReadWrite(base, foffset);
140            }
141            else {
142                throw new UnsupportedOperationException();
143            }
144        }
145    }
146
147    static VarHandle makeArrayElementHandle(Class<?> arrayClass) {
148        if (!arrayClass.isArray())
149            throw new IllegalArgumentException("not an array: " + arrayClass);
150
151        Class<?> componentType = arrayClass.getComponentType();
152
153        int aoffset = UNSAFE.arrayBaseOffset(arrayClass);
154        int ascale = UNSAFE.arrayIndexScale(arrayClass);
155        int ashift = 31 - Integer.numberOfLeadingZeros(ascale);
156
157        if (!componentType.isPrimitive()) {
158            return new VarHandleObjects.Array(aoffset, ashift, arrayClass);
159        }
160        else if (componentType == boolean.class) {
161            return new VarHandleBooleans.Array(aoffset, ashift);
162        }
163        else if (componentType == byte.class) {
164            return new VarHandleBytes.Array(aoffset, ashift);
165        }
166        else if (componentType == short.class) {
167            return new VarHandleShorts.Array(aoffset, ashift);
168        }
169        else if (componentType == char.class) {
170            return new VarHandleChars.Array(aoffset, ashift);
171        }
172        else if (componentType == int.class) {
173            return new VarHandleInts.Array(aoffset, ashift);
174        }
175        else if (componentType == long.class) {
176            return new VarHandleLongs.Array(aoffset, ashift);
177        }
178        else if (componentType == float.class) {
179            return new VarHandleFloats.Array(aoffset, ashift);
180        }
181        else if (componentType == double.class) {
182            return new VarHandleDoubles.Array(aoffset, ashift);
183        }
184        else {
185            throw new UnsupportedOperationException();
186        }
187    }
188
189    static VarHandle byteArrayViewHandle(Class<?> viewArrayClass,
190                                         boolean be) {
191        if (!viewArrayClass.isArray())
192            throw new IllegalArgumentException("not an array: " + viewArrayClass);
193
194        Class<?> viewComponentType = viewArrayClass.getComponentType();
195
196        if (viewComponentType == long.class) {
197            return new VarHandleByteArrayAsLongs.ArrayHandle(be);
198        }
199        else if (viewComponentType == int.class) {
200            return new VarHandleByteArrayAsInts.ArrayHandle(be);
201        }
202        else if (viewComponentType == short.class) {
203            return new VarHandleByteArrayAsShorts.ArrayHandle(be);
204        }
205        else if (viewComponentType == char.class) {
206            return new VarHandleByteArrayAsChars.ArrayHandle(be);
207        }
208        else if (viewComponentType == double.class) {
209            return new VarHandleByteArrayAsDoubles.ArrayHandle(be);
210        }
211        else if (viewComponentType == float.class) {
212            return new VarHandleByteArrayAsFloats.ArrayHandle(be);
213        }
214
215        throw new UnsupportedOperationException();
216    }
217
218    static VarHandle makeByteBufferViewHandle(Class<?> viewArrayClass,
219                                              boolean be) {
220        if (!viewArrayClass.isArray())
221            throw new IllegalArgumentException("not an array: " + viewArrayClass);
222
223        Class<?> viewComponentType = viewArrayClass.getComponentType();
224
225        if (viewComponentType == long.class) {
226            return new VarHandleByteArrayAsLongs.ByteBufferHandle(be);
227        }
228        else if (viewComponentType == int.class) {
229            return new VarHandleByteArrayAsInts.ByteBufferHandle(be);
230        }
231        else if (viewComponentType == short.class) {
232            return new VarHandleByteArrayAsShorts.ByteBufferHandle(be);
233        }
234        else if (viewComponentType == char.class) {
235            return new VarHandleByteArrayAsChars.ByteBufferHandle(be);
236        }
237        else if (viewComponentType == double.class) {
238            return new VarHandleByteArrayAsDoubles.ByteBufferHandle(be);
239        }
240        else if (viewComponentType == float.class) {
241            return new VarHandleByteArrayAsFloats.ByteBufferHandle(be);
242        }
243
244        throw new UnsupportedOperationException();
245    }
246
247//    /**
248//     * A helper program to generate the VarHandleGuards class with a set of
249//     * static guard methods each of which corresponds to a particular shape and
250//     * performs a type check of the symbolic type descriptor with the VarHandle
251//     * type descriptor before linking/invoking to the underlying operation as
252//     * characterized by the operation member name on the VarForm of the
253//     * VarHandle.
254//     * <p>
255//     * The generated class essentially encapsulates pre-compiled LambdaForms,
256//     * one for each method, for the most set of common method signatures.
257//     * This reduces static initialization costs, footprint costs, and circular
258//     * dependencies that may arise if a class is generated per LambdaForm.
259//     * <p>
260//     * A maximum of L*T*S methods will be generated where L is the number of
261//     * access modes kinds (or unique operation signatures) and T is the number
262//     * of variable types and S is the number of shapes (such as instance field,
263//     * static field, or array access).
264//     * If there are 4 unique operation signatures, 5 basic types (Object, int,
265//     * long, float, double), and 3 shapes then a maximum of 60 methods will be
266//     * generated.  However, the number is likely to be less since there
267//     * be duplicate signatures.
268//     * <p>
269//     * Each method is annotated with @LambdaForm.Compiled to inform the runtime
270//     * that such methods should be treated as if a method of a class that is the
271//     * result of compiling a LambdaForm.  Annotation of such methods is
272//     * important for correct evaluation of certain assertions and method return
273//     * type profiling in HotSpot.
274//     */
275//    public static class GuardMethodGenerator {
276//
277//        static final String GUARD_METHOD_SIG_TEMPLATE = "<RETURN> <NAME>_<SIGNATURE>(<PARAMS>)";
278//
279//        static final String GUARD_METHOD_TEMPLATE =
280//                "@ForceInline\n" +
281//                "@LambdaForm.Compiled\n" +
282//                "final static <METHOD> throws Throwable {\n" +
283//                "    if (handle.vform.methodType_table[ad.type] == ad.symbolicMethodType) {\n" +
284//                "        <RESULT_ERASED>MethodHandle.linkToStatic(<LINK_TO_STATIC_ARGS>);<RETURN_ERASED>\n" +
285//                "    }\n" +
286//                "    else {\n" +
287//                "        MethodHandle mh = handle.getMethodHandle(ad.mode);\n" +
288//                "        <RETURN>mh.asType(ad.symbolicMethodTypeInvoker).invokeBasic(<LINK_TO_INVOKER_ARGS>);\n" +
289//                "    }\n" +
290//                "}";
291//
292//        static final String GUARD_METHOD_TEMPLATE_V =
293//                "@ForceInline\n" +
294//                "@LambdaForm.Compiled\n" +
295//                "final static <METHOD> throws Throwable {\n" +
296//                "    if (handle.vform.methodType_table[ad.type] == ad.symbolicMethodType) {\n" +
297//                "        MethodHandle.linkToStatic(<LINK_TO_STATIC_ARGS>);\n" +
298//                "    }\n" +
299//                "    else if (handle.vform.getMethodType_V(ad.type) == ad.symbolicMethodType) {\n" +
300//                "        MethodHandle.linkToStatic(<LINK_TO_STATIC_ARGS>);\n" +
301//                "    }\n" +
302//                "    else {\n" +
303//                "        MethodHandle mh = handle.getMethodHandle(ad.mode);\n" +
304//                "        mh.asType(ad.symbolicMethodTypeInvoker).invokeBasic(<LINK_TO_INVOKER_ARGS>);\n" +
305//                "    }\n" +
306//                "}";
307//
308//        // A template for deriving the operations
309//        // could be supported by annotating VarHandle directly with the
310//        // operation kind and shape
311//        interface VarHandleTemplate {
312//            Object get();
313//
314//            void set(Object value);
315//
316//            boolean compareAndSwap(Object actualValue, Object expectedValue);
317//
318//            Object compareAndExchange(Object actualValue, Object expectedValue);
319//
320//            Object getAndUpdate(Object value);
321//        }
322//
323//        static class HandleType {
324//            final Class<?> receiver;
325//            final Class<?>[] intermediates;
326//            final Class<?> value;
327//
328//            HandleType(Class<?> receiver, Class<?> value, Class<?>... intermediates) {
329//                this.receiver = receiver;
330//                this.intermediates = intermediates;
331//                this.value = value;
332//            }
333//        }
334//
335//        /**
336//         * @param args parameters
337//         */
338//        public static void main(String[] args) {
339//            System.out.println("package java.lang.invoke;");
340//            System.out.println();
341//            System.out.println("import jdk.internal.vm.annotation.ForceInline;");
342//            System.out.println();
343//            System.out.println("// This class is auto-generated by " +
344//                               GuardMethodGenerator.class.getName() +
345//                               ". Do not edit.");
346//            System.out.println("final class VarHandleGuards {");
347//
348//            System.out.println();
349//
350//            // Declare the stream of shapes
351//            Stream<HandleType> hts = Stream.of(
352//                    // Object->Object
353//                    new HandleType(Object.class, Object.class),
354//                    // Object->int
355//                    new HandleType(Object.class, int.class),
356//                    // Object->long
357//                    new HandleType(Object.class, long.class),
358//                    // Object->float
359//                    new HandleType(Object.class, float.class),
360//                    // Object->double
361//                    new HandleType(Object.class, double.class),
362//
363//                    // <static>->Object
364//                    new HandleType(null, Object.class),
365//                    // <static>->int
366//                    new HandleType(null, int.class),
367//                    // <static>->long
368//                    new HandleType(null, long.class),
369//                    // <static>->float
370//                    new HandleType(null, float.class),
371//                    // <static>->double
372//                    new HandleType(null, double.class),
373//
374//                    // Array[int]->Object
375//                    new HandleType(Object.class, Object.class, int.class),
376//                    // Array[int]->int
377//                    new HandleType(Object.class, int.class, int.class),
378//                    // Array[int]->long
379//                    new HandleType(Object.class, long.class, int.class),
380//                    // Array[int]->float
381//                    new HandleType(Object.class, float.class, int.class),
382//                    // Array[int]->double
383//                    new HandleType(Object.class, double.class, int.class),
384//
385//                    // Array[long]->int
386//                    new HandleType(Object.class, int.class, long.class),
387//                    // Array[long]->long
388//                    new HandleType(Object.class, long.class, long.class)
389//            );
390//
391//            hts.flatMap(ht -> Stream.of(VarHandleTemplate.class.getMethods()).
392//                    map(m -> generateMethodType(m, ht.receiver, ht.value, ht.intermediates))).
393//                    distinct().
394//                    map(mt -> generateMethod(mt)).
395//                    forEach(s -> {
396//                        System.out.println(s);
397//                        System.out.println();
398//                    });
399//
400//            System.out.println("}");
401//        }
402//
403//        static MethodType generateMethodType(Method m, Class<?> receiver, Class<?> value, Class<?>... intermediates) {
404//            Class<?> returnType = m.getReturnType() == Object.class
405//                                  ? value : m.getReturnType();
406//
407//            List<Class<?>> params = new ArrayList<>();
408//            if (receiver != null)
409//                params.add(receiver);
410//            for (int i = 0; i < intermediates.length; i++) {
411//                params.add(intermediates[i]);
412//            }
413//            for (Parameter p : m.getParameters()) {
414//                params.add(value);
415//            }
416//            return MethodType.methodType(returnType, params);
417//        }
418//
419//        static String generateMethod(MethodType mt) {
420//            Class<?> returnType = mt.returnType();
421//
422//            LinkedHashMap<String, Class<?>> params = new LinkedHashMap<>();
423//            params.put("handle", VarHandle.class);
424//            for (int i = 0; i < mt.parameterCount(); i++) {
425//                params.put("arg" + i, mt.parameterType(i));
426//            }
427//            params.put("ad", VarHandle.AccessDescriptor.class);
428//
429//            // Generate method signature line
430//            String RETURN = className(returnType);
431//            String NAME = "guard";
432//            String SIGNATURE = getSignature(mt);
433//            String PARAMS = params.entrySet().stream().
434//                    map(e -> className(e.getValue()) + " " + e.getKey()).
435//                    collect(joining(", "));
436//            String METHOD = GUARD_METHOD_SIG_TEMPLATE.
437//                    replace("<RETURN>", RETURN).
438//                    replace("<NAME>", NAME).
439//                    replace("<SIGNATURE>", SIGNATURE).
440//                    replace("<PARAMS>", PARAMS);
441//
442//            // Generate method
443//            params.remove("ad");
444//
445//            List<String> LINK_TO_STATIC_ARGS = params.keySet().stream().
446//                    collect(toList());
447//            LINK_TO_STATIC_ARGS.add("handle.vform.getMemberName(ad.mode)");
448//            List<String> LINK_TO_STATIC_ARGS_V = params.keySet().stream().
449//                    collect(toList());
450//            LINK_TO_STATIC_ARGS_V.add("handle.vform.getMemberName_V(ad.mode)");
451//
452//            List<String> LINK_TO_INVOKER_ARGS = params.keySet().stream().
453//                    collect(toList());
454//
455//            RETURN = returnType == void.class
456//                     ? ""
457//                     : returnType == Object.class
458//                       ? "return "
459//                       : "return (" + returnType.getName() + ") ";
460//
461//            String RESULT_ERASED = returnType == void.class
462//                                   ? ""
463//                                   : returnType != Object.class
464//                                     ? "return (" + returnType.getName() + ") "
465//                                     : "Object r = ";
466//
467//            String RETURN_ERASED = returnType != Object.class
468//                                   ? ""
469//                                   : " return ad.returnType.cast(r);";
470//
471//            String template = returnType == void.class
472//                              ? GUARD_METHOD_TEMPLATE_V
473//                              : GUARD_METHOD_TEMPLATE;
474//            return template.
475//                    replace("<METHOD>", METHOD).
476//                    replace("<NAME>", NAME).
477//                    replaceAll("<RETURN>", RETURN).
478//                    replace("<RESULT_ERASED>", RESULT_ERASED).
479//                    replace("<RETURN_ERASED>", RETURN_ERASED).
480//                    replaceAll("<LINK_TO_STATIC_ARGS>", LINK_TO_STATIC_ARGS.stream().
481//                            collect(joining(", "))).
482//                    replaceAll("<LINK_TO_STATIC_ARGS_V>", LINK_TO_STATIC_ARGS_V.stream().
483//                            collect(joining(", "))).
484//                    replace("<LINK_TO_INVOKER_ARGS>", LINK_TO_INVOKER_ARGS.stream().
485//                            collect(joining(", ")))
486//                    ;
487//        }
488//
489//        static String className(Class<?> c) {
490//            String n = c.getName();
491//            if (n.startsWith("java.lang.")) {
492//                n = n.replace("java.lang.", "");
493//                if (n.startsWith("invoke.")) {
494//                    n = n.replace("invoke.", "");
495//                }
496//            }
497//            return n.replace('$', '.');
498//        }
499//
500//        static String getSignature(MethodType m) {
501//            StringBuilder sb = new StringBuilder(m.parameterCount() + 1);
502//
503//            for (int i = 0; i < m.parameterCount(); i++) {
504//                Class<?> pt = m.parameterType(i);
505//                sb.append(getCharType(pt));
506//            }
507//
508//            sb.append('_').append(getCharType(m.returnType()));
509//
510//            return sb.toString();
511//        }
512//
513//        static char getCharType(Class<?> pt) {
514//            if (pt == void.class) {
515//                return 'V';
516//            }
517//            else if (!pt.isPrimitive()) {
518//                return 'L';
519//            }
520//            else if (pt == boolean.class) {
521//                return 'Z';
522//            }
523//            else if (pt == int.class) {
524//                return 'I';
525//            }
526//            else if (pt == long.class) {
527//                return 'J';
528//            }
529//            else if (pt == float.class) {
530//                return 'F';
531//            }
532//            else if (pt == double.class) {
533//                return 'D';
534//            }
535//            else {
536//                throw new IllegalStateException(pt.getName());
537//            }
538//        }
539//    }
540}
541