<commit_before>/*
 * *
 *    Copyright 2014 <NAME> & <NAME>
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 *
 */

package ch.eiafr.cojac;

import static ch.eiafr.cojac.models.FloatReplacerClasses.*;
import static ch.eiafr.cojac.FloatReplacerMethodVisitor.DN_NAME;
import static ch.eiafr.cojac.FloatReplacerMethodVisitor.FN_NAME;
import static ch.eiafr.cojac.instrumenters.InvokableMethod.*;
import static ch.eiafr.cojac.instrumenters.ReplaceFloatsMethods.FL_DESCR;
import static ch.eiafr.cojac.instrumenters.ReplaceFloatsMethods.DL_DESCR;

import java.util.HashMap;
import java.util.Map;

import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;

import static org.objectweb.asm.Opcodes.*;

import org.objectweb.asm.Type;

public class FloatProxyMethod {
    private static final Type JWRAPPER_FLOAT_TYPE  = Type.getType(Float.class);
    private static final Type JWRAPPER_DOUBLE_TYPE = Type.getType(Double.class);
    private static final Type OBJ_ARRAY_TYPE=Type.getType("[Ljava/lang/Object;");
    private static final Type   OBJ_TYPE = Type.getType(Object.class);
    private static final String OBJ_DESC = OBJ_TYPE.getDescriptor();
    
	private static final String COJAC_TYPE_CONVERT_NAME = "COJAC_TYPE_CONVERT";
    
    private final CojacClassVisitor ccv;
    private final String crtClassName;
    
    public FloatProxyMethod(CojacClassVisitor ccv, String classPath){
        this.ccv = ccv;
        this.crtClassName = classPath;
    }
    
    public void nativeCall(MethodVisitor mv, int access, String owner, String name, String desc){
        boolean isStatic = (access & ACC_STATIC) > 0;
		String newDesc = replaceFloatMethodDescription(desc);
		MethodVisitor newMv = ccv.addProxyMethod(access & ~ACC_NATIVE, name, newDesc, null, null);
		int varIndex = 0;
		int opcode = INVOKESTATIC;
		if(!isStatic){
			newMv.visitVarInsn(ALOAD, 0);
			varIndex = 1;
			opcode = INVOKEVIRTUAL;
		}
        ConversionContext cc=new ConversionContext(opcode, owner, name, desc);
		Type args[] = Type.getArgumentTypes(newDesc);
		for (Type type : args) {
			newMv.visitVarInsn(getLoadOpcode(type), varIndex);
			varIndex += type.getSize();
		}
        convertArgumentsToReal(mv, cc);           
        // stack >> [target] allParamsArr [target] allParamsArr
        maybeConvertTarget(mv, cc.opcode, cc.owner);
        // stack >> [target] allParamsArr [newTarget] allParamsArr
        explodeOnStack(mv, cc, true); 
        // stack >> [target] allParamsArr [newTarget] nprm0 nprm1 nprm2...
		newMv.visitMethodInsn(opcode, owner, name, desc, false);       
        // stack >> [target] allParamsArr [possibleResult]
		checkArraysAfterCall(newMv, cc.convertedArrays, desc);		
        // stack >> [target] [possibleResult]
		convertReturnType(newMv, desc);		
        // stack >> [target] [newPossibleResult]
		newMv.visitInsn(afterFloatReplacement(Type.getReturnType(desc)).getOpcode(IRETURN));
        // stack >> [target]       // left on the stack... not a problem!
        newMv.visitMaxs(0, 0);
    }
    
    public void proxyCall(MethodVisitor mv, int opcode, String owner, String name, String desc){
        ConversionContext cc=new ConversionContext(opcode, owner, name, desc);
        // stack >> allParamsArr [target] nprm0 nprm1 nprm2...
        convertArgumentsToReal(mv, cc);           
        // stack >> [target] allParamsArr [target] allParamsArr
        maybeConvertTarget(mv, cc.opcode, cc.owner);
        // stack >> [target] allParamsArr [newTarget] allParamsArr
        explodeOnStack(mv, cc, true); 
        // stack >> [target] allParamsArr [newTarget] nprm0 nprm1 nprm2...
        mv.visitMethodInsn(opcode, owner, name, desc, (opcode == INVOKEINTERFACE));
        // stack >> [target] allParamsArr [possibleResult]
        checkArraysAfterCall(mv, cc.convertedArrays, desc);
        // stack >> [target] [possibleResult]
        int resultWidth=Type.getReturnType(desc).getSize();
        if(hasTarget(opcode)) {
            if(resultWidth==0) {
                mv.visitInsn(POP);
            } else if (resultWidth==1) {
                mv.visitInsn(SWAP);
                mv.visitInsn(POP);
            } else { // resultWidth==2) 
                mv.visitInsn(DUP2_X1);
                // stack >> possibleResult target possibleResult
                mv.visitInsn(POP2);
                // stack >> possibleResult target
                mv.visitInsn(POP);
                // stack >> possibleResult
            }
        }
        // stack >> [possibleResult]
        convertReturnType(mv, desc);
        // stack >> [newPossibleResult]
    }
    
    public void proxyCallBetter(MethodVisitor mv, int opcode, String owner, String name, String desc){
        ConversionContext cc=new ConversionContext(opcode, owner, name, desc);
        // stack >> allParamsArr [target] nprm0 nprm1 nprm2...
        convertArgumentsToReal(mv, cc);           
        // stack >> [target] allParamsArr [target] allParamsArr
        maybeConvertTarget(mv, cc.opcode, cc.owner);
        // stack >> [target] allParamsArr [newTarget] allParamsArr
        explodeOnStack(mv, cc, true); 
        Label lBeginTry = new Label();
        Label lEndTry = new Label();
        Label lBeginHandler = new Label();
        mv.visitTryCatchBlock(lBeginTry, lEndTry, lBeginHandler, "java/lang/NoSuchMethodError");
        mv.visitTryCatchBlock(lBeginTry, lEndTry, lBeginHandler, "java/lang/AbstractMethodError");
        mv.visitLabel(lBeginTry);
        String descAfter=replaceFloatMethodDescription(desc);
        mv.visitMethodInsn(opcode, owner, name, descAfter, (opcode == INVOKEINTERFACE));
        // stack >> [target] allParamsArr [possibleResult]

        // stack >> [target] allParamsArr [newTarget] nprm0 nprm1 nprm2...
        mv.visitMethodInsn(opcode, owner, name, desc, (opcode == INVOKEINTERFACE));
        // stack >> [target] allParamsArr [possibleResult]
        checkArraysAfterCall(mv, cc.convertedArrays, desc);
        // stack >> [target] [possibleResult]
        int resultWidth=Type.getReturnType(desc).getSize();
        if(hasTarget(opcode)) {
            if(resultWidth==0) {
                mv.visitInsn(POP);
            } else if (resultWidth==1) {
                mv.visitInsn(SWAP);
                mv.visitInsn(POP);
            } else { // resultWidth==2) 
                mv.visitInsn(DUP2_X1);
                // stack >> possibleResult target possibleResult
                mv.visitInsn(POP2);
                // stack >> possibleResult target
                mv.visitInsn(POP);
                // stack >> possibleResult
            }
        }
        // stack >> [possibleResult]
        convertReturnType(mv, desc);
        // stack >> [newPossibleResult]
        mv.visitLabel(lEndTry);
        mv.visitLabel(lBeginHandler);

    }

    
    public boolean needsConversion(String owner, String name, String desc) {
        if(owner.equals(JWRAPPER_FLOAT_TYPE .getInternalName())) return true;
        if(owner.equals(JWRAPPER_DOUBLE_TYPE.getInternalName())) return true;
        if(name.equals("clone") && desc.equals("()Ljava/lang/Object;")) return true;
        for (Type t:Type.getArgumentTypes(desc))
            if (needsConversion(t)) return true;
        return needsConversion(Type.getReturnType(desc));
    }
    
    private static boolean needsConversion(Type t) {
        return ! afterFloatReplacement(t).equals(t);
    }
	
    private static Type[] typesAfterReplacement(Type[] javArgs, Map<Integer, Type> conv) {
        Type cojArgs[] = new Type[javArgs.length];
        for (int i = 0; i < javArgs.length; i++) {
            cojArgs[i] = afterFloatReplacement(javArgs[i]);
            if(cojArgs[i].equals(javArgs[i]) == false){
                conv.put(i, javArgs[i]);
            }
        }
        return cojArgs;
    }
    
    private void convertArgumentsToReal(MethodVisitor mv, ConversionContext cc){        <commit_msg>prepare tryUnproxied (wip)<commit_after>/*
 * *
 *    Copyright 2014 <NAME> & <NAME>
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 *
 */

package ch.eiafr.cojac;

import static ch.eiafr.cojac.models.FloatReplacerClasses.*;
import static ch.eiafr.cojac.FloatReplacerMethodVisitor.DN_NAME;
import static ch.eiafr.cojac.FloatReplacerMethodVisitor.FN_NAME;
import static ch.eiafr.cojac.instrumenters.InvokableMethod.*;
import static ch.eiafr.cojac.instrumenters.ReplaceFloatsMethods.FL_DESCR;
import static ch.eiafr.cojac.instrumenters.ReplaceFloatsMethods.DL_DESCR;

import java.util.HashMap;
import java.util.Map;

import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;

import static org.objectweb.asm.Opcodes.*;

import org.objectweb.asm.Type;

public class FloatProxyMethod {
    private static final Type JWRAPPER_FLOAT_TYPE  = Type.getType(Float.class);
    private static final Type JWRAPPER_DOUBLE_TYPE = Type.getType(Double.class);
    private static final Type OBJ_ARRAY_TYPE=Type.getType("[Ljava/lang/Object;");
    private static final Type   OBJ_TYPE = Type.getType(Object.class);
    private static final String OBJ_DESC = OBJ_TYPE.getDescriptor();
    
	private static final String COJAC_TYPE_CONVERT_NAME = "COJAC_TYPE_CONVERT";
    
    private final CojacClassVisitor ccv;
    private final String crtClassName;
    
    public FloatProxyMethod(CojacClassVisitor ccv, String classPath){
        this.ccv = ccv;
        this.crtClassName = classPath;
    }
    
    public void nativeCall(MethodVisitor mv, int access, String owner, String name, String desc){
        boolean isStatic = (access & ACC_STATIC) > 0;
		String newDesc = replaceFloatMethodDescription(desc);
		MethodVisitor newMv = ccv.addProxyMethod(access & ~ACC_NATIVE, name, newDesc, null, null);
		int varIndex = 0;
		int opcode = INVOKESTATIC;
		if(!isStatic){
			newMv.visitVarInsn(ALOAD, 0);
			varIndex = 1;
			opcode = INVOKEVIRTUAL;
		}
        ConversionContext cc=new ConversionContext(opcode, owner, name, desc);
		Type args[] = Type.getArgumentTypes(newDesc);
		for (Type type : args) {
			newMv.visitVarInsn(getLoadOpcode(type), varIndex);
			varIndex += type.getSize();
		}
        convertArgumentsToReal(mv, cc);           
        // stack >> [target] allParamsArr [target] allParamsArr
        maybeConvertTarget(mv, cc.opcode, cc.owner);
        // stack >> [target] allParamsArr [newTarget] allParamsArr
        explodeOnStack(mv, cc, true); 
        // stack >> [target] allParamsArr [newTarget] nprm0 nprm1 nprm2...
		newMv.visitMethodInsn(opcode, owner, name, desc, false);       
        // stack >> [target] allParamsArr [possibleResult]
		checkArraysAfterCall(newMv, cc.convertedArrays, desc);		
        // stack >> [target] [possibleResult]
		convertReturnType(newMv, desc);		
        // stack >> [target] [newPossibleResult]
		newMv.visitInsn(afterFloatReplacement(Type.getReturnType(desc)).getOpcode(IRETURN));
        // stack >> [target]       // left on the stack... not a problem!
        newMv.visitMaxs(0, 0);
    }
    
    public void proxyCall(MethodVisitor mv, int opcode, String owner, String name, String desc){
        ConversionContext cc=new ConversionContext(opcode, owner, name, desc);
        // stack >> allParamsArr [target] nprm0 nprm1 nprm2...
        convertArgumentsToReal(mv, cc);           
        // stack >> [target] allParamsArr [target] allParamsArr
        maybeConvertTarget(mv, cc.opcode, cc.owner);
        // stack >> [target] allParamsArr [newTarget] allParamsArr
        explodeOnStack(mv, cc, true); 
        // stack >> [target] allParamsArr [newTarget] nprm0 nprm1 nprm2...
        mv.visitMethodInsn(opcode, owner, name, desc, (opcode == INVOKEINTERFACE));
        // stack >> [target] allParamsArr [possibleResult]
        checkArraysAfterCall(mv, cc.convertedArrays, desc);
        // stack >> [target] [possibleResult]
        int resultWidth=Type.getReturnType(desc).getSize();
        if(hasTarget(opcode)) {
            if(resultWidth==0) {
                mv.visitInsn(POP);
            } else if (resultWidth==1) {
                mv.visitInsn(SWAP);
                mv.visitInsn(POP);
            } else { // resultWidth==2) 
                mv.visitInsn(DUP2_X1);
                // stack >> possibleResult target possibleResult
                mv.visitInsn(POP2);
                // stack >> possibleResult target
                mv.visitInsn(POP);
                // stack >> possibleResult
            }
        }
        // stack >> [possibleResult]
        convertReturnType(mv, desc);
        // stack >> [newPossibleResult]
    }
    
    public void proxyCallBetter(MethodVisitor mv, int opcode, String owner, String name, String desc){
        Label lBeginTry = new Label(), lEndTry = new Label(); 
        Label lBeginHandler = new Label(), lEndHandler = new Label();
        String descAfter=replaceFloatMethodDescription(desc);
        ConversionContext cc=new ConversionContext(opcode, owner, name, desc);
        // stack >> allParamsArr [target] nprm0 nprm1 nprm2...
        convertArgumentsToReal(mv, cc);           
        // stack >> [target] allParamsArr [target] allParamsArr
        // try to call as if that method was indeed instrumented...
        mv.visitTryCatchBlock(lBeginTry, lEndTry, lBeginHandler, "java/lang/NoSuchMethodError");
        mv.visitTryCatchBlock(lBeginTry, lEndTry, lBeginHandler, "java/lang/AbstractMethodError");
        mv.visitLabel(lBeginTry);
        mv.visitMethodInsn(opcode, owner, name, descAfter, (opcode == INVOKEINTERFACE));
        // stack >> [target] allParamsArr [possibleResult]
        int resultWidth=Type.getReturnType(descAfter).getSize();
        if (resultWidth==0) {
            mv.visitInsn(POP);
            if(hasTarget(opcode)) {
                mv.visitInsn(POP);
            }
        } else if (resultWidth==1) {
            mv.visitInsn(DUP2_X1);
            mv.visitInsn(POP);
            if(hasTarget(opcode)) {
                mv.visitInsn(SWAP);
                mv.visitInsn(POP);
            }
        } else { // resultWidth==2)
            mv.visitInsn(DUP2_X1);
            mv.visitInsn(POP2);
            mv.visitInsn(POP);
            if(hasTarget(opcode)) {
                mv.visitInsn(DUP2_X1);
                mv.visitInsn(POP2);
                mv.visitInsn(POP);
            }
        }
        // stack >> [possibleResult]
        mv.visitJumpInsn(GOTO, lEndHandler);  // and we're done !
        mv.visitLabel(lEndTry);
        
        mv.visitLabel(lBeginHandler);
        // stack >> [target] allParamsArr exception
        mv.visitInsn(POP); // we don't need the exception object
        // stack >> [target] allParamsArr
        maybeConvertTarget(mv, cc.opcode, cc.owner);
        // stack >> [newTarget] allParamsArr
        if (hasTarget(opcode)) {
            mv.visitInsn(DUP_X1);
        } else {
            mv.visitInsn(DUP);
        }
        // stack >> allParamsArr [newTarget] allParamsArr
        explodeOnStack(mv, cc, true); 
        // stack >> allParamsArr [newTarget] nprm0 nprm1 nprm2...
        mv.visitMethodInsn(opcode, owner, name, desc, (opcode == INVOKEINTERFACE));
        // stack >> allParamsArr [possibleResult]
        checkArraysAfterCall(mv, cc.convertedArrays, desc);
        // stack >> [possibleResult]
        convertReturnType(mv, desc);
        // stack >> [newPossibleResult]
        mv.visitLabel(lEndHandler);

    }

    
    public boolean needsConversion(String owner, String name, String desc) {
        if(owner.equals(JWRAPPER_FLOAT_TYPE .getInternalName())) return true;
        if(owner.equals(JWRAPPER_DOUBLE_TYPE.getInternalName())) return true;
        if(name.equals("clone") && desc.equals("()Ljava/lang/Object;")) return true;
        for (Type t:Type.getArgumentTypes(desc))
            if (needsConversion(t)) return true;
        return needsConversion(Type.getReturnType(desc));
    }
    
    private static boolean needsConversion(Type t) {
        return ! afterFloatReplacement(t).equals(t);
    }
	
    private static Type[] typesAfterReplacement(Type[] javArgs, Map<Integer, Type> conv) {
        Type cojArgs[] = new Type[javArgs.length];
        for (int i = 0; i < javArgs.length; i++) {
            cojArgs[i] = afterFloatReplacement(javArgs[i]);
            if(cojArgs[i].equals(javArgs[i]) == false){
                conv.put(i, javArgs[i]);
            }
        }
        return cojArgs;
    }
    
    private void convertArgumentsToReal(MethodVisitor mv, ConversionContext cc){        
{'fraction_non_alphanumeric': 0.11156128737731112, 'fraction_numerical': 0.0051358137411549876, 'mean_word_length': 2.664018398494669, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 131, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2135451', 'n_tokens_mistral': 5412, 'n_tokens_neox': 5263, 'n_words': 1196}