vendredi 30 décembre 2022

NoSuchMethodException is throwing when trying to access getActivePasswordQuality() method of LockPatternUtils class

I want to get access to com.android.internal.widget.LockPatternUtils class object using reflection and want to know the Lock method user has set in Android device.

I am using below code for that :

    private fun getAuthenticationMethodType() : Int {
    var lockType = 0
    try {
        val lockPatternUtilsClass = Class.forName("com.android.internal.widget.LockPatternUtils")
        val lockPatternUtils =
            lockPatternUtilsClass.getConstructor(Context::class.java).newInstance(this)


        val method: Method = lockPatternUtilsClass.getMethod("getActivePasswordQuality")
        // === The above Line throws an exception NoSuchMethodException === //

        val method2: Method = lockPatternUtilsClass.getDeclaredMethod("getActivePasswordQuality",
                            Class.forName("android.os.UserHandle"))
       // === Tried above line too, but this Line also throws an exception NoSuchMethodException === //

        val userHandleClass = Class.forName("android.os.UserHandle")
        val myUserIdMethod = userHandleClass.getMethod("myUserId")
        val userId = myUserIdMethod.invoke(userHandleClass)

        lockType = method.invoke(lockPatternUtils, userId) as Int
    } catch (e: java.lang.Exception) {
        e.printStackTrace()
        Log.d("TAG","exception : " + e.printStackTrace())
    }
     return lockType
}

I know the above code works fine until Android 6. I am trying on Android 12.

I checked on Android Documentation Non-SDK API lists and found that getActivePasswordQuality and getKeyguardStoredPasswordQuality methods are marked as greyList. As per documentation of greyList, it says :

Unsupported (greylist) : Non-SDK interfaces that are currently unrestricted and your app can use. Note however, that these interfaces are unsupported and subject to change without notice. Expect these interfaces to be conditionally blocked in future Android versions in a max-target-x list.

But, these both methods are not accessible. My understanding is that the methods marked with greyList can be accessible. Is it correct?

Is there any mistake in my code?

How to know lock password type that user has set like PIN/Password/Pattern/Biometric, just categorisation is needed





mercredi 28 décembre 2022

How to find all sub classes of java.lang.Throwable in the JVM?

I want to find all sub classes of java.lang.Throwable in the JVM. The classes may or may not have been already loaded in the JVM.

I have read the similar question How do you find all subclasses of a given class in Java?, and I think org.reflections can solve my question.

I tried the following code:

public static void main(String[] args) {
    Reflections reflections = new Reflections( "org" ) ;
    Set<Class<? extends Throwable>> set = reflections.getSubTypesOf( Throwable.class ) ;
    for (Class<? extends Throwable> t : set) {
        System.out.println( t ) ;
    }
}

But the result is not what I expected:

class java.lang.Exception
class java.lang.RuntimeException
class org.reflections.ReflectionsException

I have two doubts:

  1. Why are java.lang.Exception and java.lang.RuntimeException in the result? I used the prefix "org".
  2. Why is java.lang.NullPointerException not in the result? It is in the package "java.lang" too.




Why does Assembly.GetType not get the type that exists in the target Assembly?

Assembly UnityEditorAssembly = Assembly.Load("UnityEditor");
Type[] allType = UnityEditorAssembly.GetTypes();
for (int i = 0; i < allType.Length; i++)
{
    if (allType[i].Name== "SceneAsset")
    Debug.LogError(allType[i].Name);
}
Type targetType = UnityEditorAssembly.GetType("SceneAsset",false,false);
Debug.LogError(targetType);

When I tried to get the SceneAsset type in UnityEditor by reflection, I could not get the target by Assembly.GetType, but by traversing to prove that the type existed at runtime. I wondered why





lundi 26 décembre 2022

Can I invoke a Kotlin coroutine from Java reflectively and wrap it in CompletableFuture?

I'm reflectively accessing a Kotlin class and trying to invoke a coroutine, wrapping it in a CompletableFuture. Looking at an example from Spring, they manage to wrap such a reflective call in a Mono using kotlinx-coroutines-reactor:

Mono<Object> mono = MonoKt.mono(Dispatchers.getUnconfined(), (scope, continuation) ->
                        KCallables.callSuspend(function, getSuspendedFunctionArgs(target, args), continuation));

I could easily just call Mono#toFuture() but I'm trying to avoid dragging in a dependency to Reactor. Can I achieve the same without going through Mono?

Looking at kotlinx-coroutines-jdk8, there seems to exist something similar to the above, but I can't figure out how to use it. Perhaps:

CompletableFuture<Object> future = FutureKt.future(
         GlobalScope.INSTANCE, Dispatchers.getUnconfined(), CoroutineStart.DEFAULT, (scope, continuation) ->
                KCallables.callSuspend(function, getSuspendedFunctionArgs(target, args), continuation));

But this is just a blind guess, as I have next to 0 Kotlin knowledge. Are CoroutineStart.DEFAULT or GlobalScope.INSTANCE even ok here?

Btw, how is Spring getting away with passing a CoroutineDispatcher (Dispatchers.getUnconfined()) where a CoroutineContext is expected?





What draws the line between reflective programming & non-reflective programming like simple softcoding?

Not sure if this is the right place to bring up this kind of discussion but, Im reading https://en.wikipedia.org/wiki/Reflective_programming and feel I need a bit further clarification for where the line between "reflective" & non-reflective programming really goes. Theres a series of examples of reflective v non-reflective code towards the end of the wikipedia page where all the "reflective" examples seem to access data with string identifiers - but what would actually differentiate this from say putting a bunch of objects in a collection/array of some sort and accessing them by an index - say compared to accessing them by an array of string identifiers that you can use to fetch the desired object?

In some languages you can clearly see the difference & benefit, like in Python & JS they have the eval method that lets them insert all sorts of code at runtime that can be pretty much endlessly complex and completely change the code flow of an application - and no longer limited to accessing mere special type objects. But in the examples listed on the wiki page you can also find examples where the "reflection" seems limited only to accessing specially declared objects by there name (at which point Im questioning if you can really argue that the program really can be considered to be "modifying" itself at all, at least on a high level in conceptual point of view).

Does the way that the underlying machinery producd by the compiler (or the way that the interpreter reads your code) affect whats considered to be reflective?

Is the ability of redefining the contents of existing objects or declaring new objects without a "base class"/preexisting structure created at compile time that differentiates reflective & non-reflective code? If so, how would this play with the examples at the wikipedia page that doesnt seem to showcase this ability?

Can the meaning of "reflective programming" vary slightly depending on the scenario?

Any thoughts appreciated <3





.NET Reflection: Type is resolved from Assembly, but not from Module

I have the following code which loads an assembly via LoadFile and tries to get a generic type from it (.NET 6):

using System.Reflection;

var assemblyPath = "D:\\jb_lifetimes\\JetBrains.Lifetimes.dll";
var typeName = "JetBrains.Util.Util.StaticsForType`1[[JetBrains.Threading.ByteBufferAsyncProcessor," +
               " JetBrains.Lifetimes, Version=777.0.0.0, Culture=neutral, PublicKeyToken=3c74c1a6a8683340]]";
var moduleName = "D:\\jb_lifetimes\\JetBrains.Lifetimes.dll";

var assembly = Assembly.LoadFile(assemblyPath);
var fromAssembly = assembly.GetType(typeName);

Console.WriteLine($"Module count: {assembly.Modules.Count()}");

var module = assembly.GetModules().First(m => m.FullyQualifiedName == moduleName);
Console.WriteLine($"Resolved module: {module}");

Console.WriteLine($"Types count in module: {module.GetTypes().Length}");
Console.WriteLine($"Types count in assembly: {assembly.GetTypes().Length}");

var fromModule = module.GetType(typeName);

Console.WriteLine($"From assembly: {fromAssembly}");
Console.WriteLine($"From module: {fromModule}");

And get the following output:

Module count: 1
Resolved module: JetBrains.Lifetimes.dll
Types count in module: 316
Types count in assembly: 316
From assembly: JetBrains.Util.Util.StaticsForType`1[JetBrains.Threading.ByteBufferAsyncProcessor]
From module:

Type is resolved when it is acquired from Assembly.GetType, but Module.GetType returns null, however there is only one module in this assembly, and it is successfully resolved.

I don't understand why the type cannot be resolved from the only module of the assembly when it is successfully resolved from the assembly itself.

Some other observations:

  • If I replace LoadFile with LoadFrom, type is resolved from module as well. I know about different load contexts, but can't understand how they can affect the observed behavior
  • If I replace type name with JetBrains.Util.Util.StaticsForType1[JetBrains.Threading.ByteBufferAsyncProcessor], it is also resolved from module even with LoadFile




vendredi 23 décembre 2022

CreateDelegate: "ArgumentException: Cannot bind to the target method because its signature is not compatible with that of the delegate type."

I am writing a GUI program using AvaloniaUI. The part I'm stuck on right now is that I'm trying to add some code to the ViewModel's constructor that binds some methods to events defined in the VM using Reflection. This is what I have right now:

namespace Program
{
    [AttributeUsage(AttributeTargets.Method)]
    [MeansImplicitUse]
    internal sealed class AttachToEventInViewModelAttribute : Attribute
    {
        internal string EventName;

        public AttachToEventInViewModelAttribute(string EventName) =>
            this.EventName = EventName;
    }
}

namespace Program.Models
{
    public static class ExtractFiles
    {
        [AttachToEventInViewModel("onStartExtraction")]
        internal static void Extract()
        {
        }
    }
}

namespace Program.Views
{
    public partial class MainWindow : Window
    {
        private readonly Window instance;

        public MainWindow()
        {
            instance = this;
            InitializeComponent();
        }

        [AttachToEventInViewModel("onGetWindow")]
        public Window GetInstance() =>
            instance;
    }
}

namespace Program.ViewModels
{
    public sealed class MainWindowViewModel : ViewModelBase
    {
        // ==== Constructor ====
        public MainWindowViewModel()
        {
            <snip code for finding the GetInstance() and Extract() methods, which is working>
            
            MethodInfo method = allMethodsInType[j];
            object[] allAttributesOnMethod = method.GetCustomAttributes(typeof(AttachToEventInViewModelAttribute), false);

            AttachToEventInViewModelAttribute methodAttribute = (AttachToEventInViewModelAttribute) allAttributesOnMethod[0];
            BindingFlags bindingFlags = BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.NonPublic;

            EventInfo? methodEventInfo = this.GetType().GetEvent(methodAttribute.EventName, bindingFlags);
            if (methodEventInfo == null)
                continue;

            Type? methodEventType = methodEventInfo.EventHandlerType;
            if (methodEventType == null)
                continue;

            Delegate methodEventHandler = Delegate.CreateDelegate(methodEventType, this, method);
            methodEventInfo.AddEventHandler(this, methodEventHandler);
        }


        // ==== Events ====
        private event Action onStartExtraction;

        private event Func<Window> onGetWindow;
    }
}

However, when I try run this code, the CreateDelegate method triggers the Exception in the title. The strange part is that if I add the following lines to the MainWindowViewModel constructor, the compiler has no problem with them, implying that the signatures are actually compatible:

            onGetWindow += new MainWindow().GetInstance;
            onStartExtraction += ExtractFilesFromBsaRecords.Extract;

I searched the site and found other questions with this problem, but none of them helped. For the most part, the problem in those was that the asker used the CreateDelegate overload for static events.