vendredi 10 septembre 2021

imagejpeg non present in extension functions

If I try to do (new ReflectionExtension('gd'))->getFunctions() I get a list of functions, but imagejpeg is not among the results, even if the function is documented and works fine in my code.

Do you have any idea why it is not in the output of my call?





Command handler receives wrong arguments when it's a let binding but works as lambda

I'm trying to use F# and System.CommandLine to make a little CLI tool. A command can have a handler callback that is called when the command is used. Usually one can define several flags for a command and the name of the flag is used to bind to an argument of the handler function with the same name.

Example

myApp foo --a

will call the handler for the foo command

let handler (a: bool) (b: bool) = // a should be true, b should be false
   ...

However this doesn't work and both a and b are false when I bind the handler that is a let binding:

let fooCommand = Command ...
fooCommand.Handler <- CommandHandler.Create handler
// will call handler false false

But, when I use a lambda directly it works fine and the function arguments have the correct values

let fooCommand = Command ...
fooCommand.Handler <- CommandHandler.Create (fun (a: bool) (b: bool) -> handler a b)
// will call handler true false

Why is that? Why does the handler work as a lambda but not as a let binding?

Here is a MRE

#r "nuget: System.CommandLine, 2.0.0-beta1.21308.1"

open System.CommandLine
open System.CommandLine.Invocation
open System.CommandLine.Parsing

let opts = [Option<bool>([|"--a"|]); Option<bool>([|"--b"|])]

let fooCmd = Command("foo", "")
List.iter fooCmd.AddOption opts

let barCmd = Command("bar", "")
List.iter barCmd.AddOption opts

let handler (a: bool) (b: bool) = 
    printfn "%A" {| a = a; b = b|}

fooCmd.Handler <- CommandHandler.Create handler

barCmd.Handler <- CommandHandler.Create (fun (a: bool) (b: bool) -> handler a b)

let root = RootCommand("")
root.Add fooCmd
root.Add barCmd

printfn "foo --a: "
root.Invoke("foo --a")

printfn "bar --a: "
root.Invoke("bar --a")

which prints

foo --a: 
{ a = false
  b = false }
bar --a: 
{ a = true
  b = false }




jeudi 9 septembre 2021

Android create Toast using class reflection?

I am creating a hook using AndHook to test some functions getting called. I need to show a Toast inside a method without being able to get the context object (I can't directly import MainActivity because I am injecting the script without having the corresponding package when compiling so I can't use MainActivity.this). Here's the code sample:

import andhook.lib.HookHelper;

import android.widget.Toast;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap;

public class AndHookConfig {
    @HookHelper.Hook(clazz = BitmapFactory.class)
    private static Bitmap decodeFile(BitmapFactory thiz, String path) {
        Toast.makeText(Class.forName("com.example.activity.MainActivity").this, "Bitmap.decodeFile("+path+")", Toast.LENGTH_LONG).show();
        return (Bitmap)(HookHelper.invokeObjectOrigin(thiz, path));
    }
}

I think the only way to do this is using reflection but the code sample doesn't compile and results in an error. Do you have any solutions ?

Thanks in advance.





JDK11 to JDK12 Migration java.lang.NoSuchFieldException: modifiers

Below function Hacks the "HttpURLConnection#methods" static field (through Java Reflection). I am using reflection to unit test my code functionality. I found out we can not change the static final fields in JDK12. I found one solution to use unsafe but I am not sure how can I get this function working in JDK12 using unsafe.

protected static void allowMethods(String... methods) {
    try {
        Field methodsField = HttpURLConnection.class.getDeclaredField("methods");

        Field modifiersField = Unsafe.class.getDeclaredField("modifiers");
        modifiersField.setAccessible(true);
        modifiersField.setInt(methodsField, methodsField.getModifiers() & ~Modifier.FINAL);

        methodsField.setAccessible(true);

        String[] oldMethods = (String[]) methodsField.get(null);
        Set<String> methodsSet = new LinkedHashSet<>(Arrays.asList(oldMethods));
        methodsSet.addAll(Arrays.asList(methods));
        String[] newMethods = methodsSet.toArray(new String[0]);

        methodsField.set(null/*static field*/, newMethods);
    } catch (NoSuchFieldException | IllegalAccessException e) {
        throw new IllegalStateException(e);
    }
}  

This is the stacktrace for the above code:

Caused by: java.lang.IllegalStateException: java.lang.NoSuchFieldException: modifiers
at pii.rest.call.RestUtils.allowMethods(RestUtils.java:75)
at pii.rest.call.JobAbort.<clinit>(JobAbort.java:39)
Caused by: java.lang.NoSuchFieldException: modifiers
at java.base/java.lang.Class.getDeclaredField(Class.java:2549)
at pii.rest.call.RestUtils.allowMethods(RestUtils.java:62)

Can anybody help me convert this function to use Unsafe so therefore it works with JDK12+. I have tried this until now:

final Field ourField = HttpURLConnection.class.getDeclaredField("methods");
final Field unsafeField = Unsafe.class.getDeclaredField("theUnsafe");
unsafeField.setAccessible(true);
final Unsafe unsafe = (Unsafe) unsafeField.get(null);
final Object staticFieldBase = unsafe.staticFieldBase(ourField);
final long staticFieldOffset = unsafe.staticFieldOffset(ourField);
unsafe.putObject(staticFieldBase, staticFieldOffset, "it works");




Simulation of reflected Brownian Motion with two boundaries

I want to run a simulation of a reflected Brownian motion (RBM) with two boundaries. I have found MATLAB code for the one-sided case with drift from a textbook by Kroese et al (see also Wikipedia “RBM”). Does someone know how to write the code for the RBM with two boundaries?





Get actual interface parameter for class

I have interface like this:

public interface Converter<R extends Data> {
    CustomData convert(R source);
}

and few implementations. For example:

public class ShopConverter implements Converter<ShopData> {
    public CustomData convert(ShopData source) {}
}

Of course ShopData extends Data.

In the handler I receive my converters by DI and store their in List<Converter<? extends Data>> converters.

I want to fetch actual Data sub-class implementation. For this case it should be ShopData but I've receive only Data by code:

Class<? extends Converter> converterClass = converters.get(0).getClass();
Type interfaceType = converterClass.getGenericInterfaces()[0];
ParameterizedType parameterizedType = (ParameterizedType)interfaceType
Type actualTypeArgument = parameterizedType.getActualTypeArguments()[0]; //will be Data but I want to receive ShopData

Is it possible to fetch actual sub-class Type (or better Class) instead of super-class?





protobuf DynamicMessage reflection AddMessage pure virtual method called?

I'm parsing message by runtime proto-file. I constructed "prototye message", and tried to get reflection infos of each fields. when it comes to nested message, I need to AddMessage to get the inside fields.

// proto-file

message A {
   int32  a1 = 1;
   string a2 = 2;
};
message B {
   repeated A b1 = 1;
   int64      b2 = 2;
};
Class ProtoType {
Message* msg;
BizX* biz_x;
void Init(const std::string& proto_file_path) {
    // parse from file to get msgDesc
    auto* factory = new google::protobuf::DynamicMessageFactory();
    factory->SetDelegateToGeneratedFactory(true);                                                                 
    msg= mFactory->GetPrototype(msgDesc);         
}
void InitRefl() {
    biz_x = new BizX();
    biz_x->Init(*(msg->New()));
}
};
class BizX {
BizY* biz_y;
Reflection* refl;
Descriptor* desc;
void Init(const Message& msg) {
    refl = msg.GetReflection();
    desc = msg.GetDescriptor();

    const auto* field_desc = desc->FindFieldByName("b1");
    auto* p = msg.New();
    auto* tmp = refl->AddMessage(p, field_desc);

    biz_y = new BizY();
    biz_y->Init(msg);
} 
};
class BizY {
Reflection* refl;
Descriptor* desc;
void Init(const Message& msg) {
    refl = msg.GetReflection();
    desc = msg.GetDescriptor();

    const auto* field_desc = desc->FindFieldByName("b1");
    auto* p = msg.New();
    auto* tmp = refl->AddMessage(p, field_desc); // crash!!!:pure virtual method called
}
};
int main() {
    ProtoType* p = new ProtoType();
    p->Init("proto-file")
    p->InitRefl();
    return 0;
}

I thought BizY::Init should have the same result as BizX::Init, but it crashed, why?