How to find the real class name from obfuscated ProGuard classname in my source code? - proguard

I got an email from Google about unsafe implementation of TrustManager
with the only clue that the problematic code is in com.b.a.af class. Clearly that's the obfuscated name. How would I get the real class name from that obfuscated class name, in my own source code. Is there any way to lookup the mapping that ProGuard does? Thanks!

If you have the mappings each class should look like this:
me.vader.event.EventMouseClick -> f:
int buttonID -> q
boolean mouseDown -> r
void <init>() -> <init>
void fire(int,boolean) -> a
int getButtonID() -> n
You can see the obvious before -> after convention. So finding the original names should be really easy.

Related

Function reference for class constructor nested within generic parent class

If I have
sealed class Foo<A> {
data class Bar<A>(val value: Int): Foo<A>()
}
and I want to refer to the Bar<Int> constructor as an implicit lambda using the :: operator, then none of the following are accepted as valid syntax:
Foo<Int>::Bar<Int>
::Foo.Bar<Int>
::(Foo.Bar<Int>) (the compiler tells me that this syntax is reserved for future use).
I can refer to it if I explicitly import the nested class constructor into the scope using
import com.package.Foo.Bar
which allows me to write ::Bar for the constructor and Bar<Int>::value for the property getter. But I have to do this for every nested constructor, and it kind of defeats the advantage of using the :: operator to save typing.
Is there a notation that I have missed which allows me to avoid having to import all nested class names and constructors?
Edit
My original example did not involve generics, which turns out was an oversimplification of the problem I had in my actual code that I am working on, which does use generics.
It turns out that for nested classes without generic parameters, the Foo::Bar notation actually works, so my original question had a false premise. It is, however, not possible to create callable references to constructors within generic classes. This is documented in the following bug report: https://youtrack.jetbrains.com/issue/KT-15952
It is a known bug in the language design: https://youtrack.jetbrains.com/issue/KT-15952
This bug report did however lead me to another workaround using type aliases which is equivalent to adding aliased imports, but has the advantage that you can put the alias where you want, and even share it between modules. In summary, this is the two only viable solutions I know of so far:
// Method one: Import Foo.Bar
import Foo.Bar as BarImported
sealed class Foo<A> {
data class Bar<A>(val value: A): Foo<A>()
}
val ctor: (Int) -> Foo<Int> = ::BarImported
val getter: (BarImported<Int>) -> Int = BarImported<Int>::value
// Method two: Alias Foo.Bar
typealias BarAlias<A> = Foo.Bar<A>
val ctor2: (Int) -> Foo<Int> = ::BarAlias
val getter2: (Foo.Bar<Int>) -> Int = BarAlias<Int>::value
What about wild card imports?
import com.package.Foo.*

Dlang: why are constructors not inherieted?

Is there a way to not have to repeatidly write this(parent class args) {super(parent class args);} when the arguments are exactly the same?
The code:
class Parent {
string name;
this(string name) {
this.name = name;
}
}
class Child : Parent {
}
unittest {
auto child = new Child("a name");
assert(child.name == "a name");
}
https://run.dlang.io/is/YnnezI
Gives me the compilation error:
Error: class onlineapp.Child cannot implicitly generate a default constructor when base class onlineapp.Parent is missing a default constructor
Java and C# don't inherit constructors either (unless that's changed in the last few years - I don't think C++ allowed it either until c++11), and D follows the same reasoning so you can read more by looking up things about them.
Basically though the reason is that subclasses must have their own unique state - at very least stuff like the vtable even if you don't declare any of your own variables - and thus a unique constructor is required. Otherwise you can have uninitialized members.
And if inheritance went the whole way, since Object has a this(), new AnyClass(); would compile and lead to a lot of invalid objects. (In regular D, if you declare any ctor with arguments, it disables the automatically-generated zero arg one.)
Now, D could in theory do what C++ does and auto-generate other args too... it just doesn't. Probably mostly because that is a relatively new idea in C++ and D's class system is primarily based on Java's older system.
But all that said, let me show you a trick:
this(Args...)(auto ref Args args) { super(args); }
stick that in your subclass and you basically inherit all the parent's constructors in one go. If the super doesn't compile for the given args, neither will this, so it doesn't add random things either. You can overload that with more specific versions if needed too, so it is a reasonable little substitute for a built-in language feature.

What is the purpose of empty class in Kotlin?

I was going through Kotlin reference document and then I saw this.
The class declaration consists of the class name, the class header
(specifying its type parameters, the primary constructor etc.) and the
class body, surrounded by curly braces. Both the header and the body
are optional; if the class has no body, curly braces can be omitted.
class Empty
Now I'm wondering what is the use of such class declaration without header and body
Empty classes can be useful to represent state along with other classes, especially when part of a sealed class. Eg.
sealed class MyState {
class Empty : MyState()
class Loading : MyState()
data class Content(content: String) : MyState()
data class Error(error: Throwable) : MyState()
}
In this way you can think of them like java enum entries with more flexibility.
tldr: they want to demonstrate it's possible
even an empty class is of type Any and therefore has certain methods automatically. I think in most cases, this does not make sense, but in the documentation case it's used to show the simplest possible definition of a class.
The Java equivalent would be:
public final class Empty {
}
From practical programmer day to day perspective empty class makes no much sense indeed. There are however cases where this behavior is desirable.
There are scenarios where we want to make sure that we want to define a class and at the same time, we want to make sure that instance of this class will never be created (type created from such class is called empty type or uninhabited type).
Perfect example of this is Kotlin Nothing class with do not have class declaration header and body (notice that it also have private constructor)
https://github.com/JetBrains/kotlin/blob/master/core/builtins/native/kotlin/Nothing.kt
There are few usages for Nothing in Kotlin language. One of them would be a function that does not return a value (do not confuse this with Unit where the function returns actually returns a value of type Unit). A typical example is an assertFail method used for testing or method that exits current process. Both methods will never actually return any value yet we need to explicitly say tell it to a compiler using special type (Nothing).
fun assertFail():Nothing {
throw Exception()
}
Nothing can be also used with start projections where type Function<*, String> can be in-projected to Function<in Nothing, String>
Another usage for empty class is type token or placeholder:
class DatabaseColumnName
class DatabaseTableName
addItem(DatabaseColumnName.javaClass, "Age")
addItem(DatabaseTableName.javaClass, "Person")
...
getItemsByType(DatabaseTableName.javaClass)
Some languages are using empty classes for metaprogramming although I haven't explored this part personally:
Advantages of an empty class in C++
An example of empty class usage from Spring Boot framework:
#SpringBootApplication
class FooApplication
fun main(args: Array<String>) {
runApplication<FooApplication>(*args)
}
It doesn't make much sense as a final result. However it can be useful in active development and at a design time as a placeholder of some sort, which may be expanded in the future. Such terse syntax allows you to quickly define such new types as needed. Something like:
class Person (
val FirstName: String,
val LastName: String,
// TODO
val Address: Address
)
class Address
I think main reason this is specifically mentioned in documentation is to demonstrate, that language syntax in general can be terse, not that it is specifically created for common usage.
Sealed classes, in a sense, an extension of enum classes: the set of values for an enum type is also restricted, but each enum constant exists only as a single instance, whereas a subclass of a sealed class can have multiple instances which can contain state.
reference

Create a new PSIClass with Generic type parameters

Newbie question on IntelliJ plugin development.
I need to generate a parameterised class (Class with generics) given the name of the class and the name of the type parameter, but I can not find how to?
It seems PSIClass does not support generics.
Example
Given
String className = "MyClass";
String typeName = "T"
I would like to have a PSIClass that represents this:
public class MyClass<T> { ... }
The goal is to dynamically add methods to such class and eventually write the complete class to a file. The class needs to declare the Type Variable because some methods will receive/return T
Thanks!
I have found a solution in the intelliJ developer forums. It doesn't seem to be the neatest one, but it works.
I'd recommend to use
PsiFileFactory.getInstance(...).createFileFromText("ClassName.java",
JavaFileType.INSTANCE, "class ClassName { ...}"), cast the result
to PsiJavaFile and use its getClasses[0] as the result.
Here is the link to the thread:
https://intellij-support.jetbrains.com/hc/en-us/community/posts/115000089970-Create-a-new-PSIClass-with-Generic-type-parameters?page=1#community_comment_115000122164

Discriminated unions in NHibernate

I'm wondering if there's any relatively easy way to extend NHibernate to support F#'s discriminated union. Not just a single IUserType or ICompositeUserType, but something generic that I can re-use regardless of the actual contents of the DU.
For example, suppose I have a property called RequestInfo, which is a union defined as:
type RequestInfo =
| Id of int
| Name of string
This compiles into an abstract RequestInfo class, with concrete subclasses Id and Name. I can get all this info out just fine with F# reflection. In this case, I could store it in the database with "RequestInfo_Tag", "RequestInfo_Id", "RequestInfo_Name".
As I'm a NHibernate newbie, what kind of problems am I going to run into trying to follow this approach? Are more complex cases going to be impossible to deal with? For example, what about nested discriminated unions? Is there a way I can "hand off" the reading of the rest of the union to another ICompositeUserType?
More importantly, will this mess up my querying capabilities? Meaning, will I have to know the actual column names in the DB; I won't be able to do Criteria.Eq(SomeDiscUnion) and have it all sorted out?
I'm not looking for a complete "provide code" answer, just some general advice if this is even worth going after (and some pointers on how), or if I should just rethink my model.
Thanks!
P.S. Not to be rude, but if your answer consists of "use C#", it's not very helpful.
I've not been brave enough to try using NHibernate with F#'s type system, but it might help to look from the perspective of what's actually generated by the F# compiler.
If you look at your Discriminated Union in reflector, there are actually three classes generated (and more if you count the private debug proxies).
public abstract class RequestInfo : IStructuralEquatable, IComparable, IStructuralComparable
The first class, RequestInfo, is abstract, and is actually implemented by the other types in the union.
// Nested Types
[Serializable, DebuggerTypeProxy(typeof(Program.RequestInfo._Id#DebugTypeProxy)), DebuggerDisplay("{__DebugDisplay()}")]
public class _Id : Program.RequestInfo
{
// Fields
[DebuggerBrowsable(DebuggerBrowsableState.Never), CompilerGenerated, DebuggerNonUserCode]
public readonly int id1;
// Methods
[CompilerGenerated, DebuggerNonUserCode]
public _Id(int id1);
}
[Serializable, DebuggerTypeProxy(typeof(Program.RequestInfo._Name#DebugTypeProxy)), DebuggerDisplay("{__DebugDisplay()}")]
public class _Name : Program.RequestInfo
{
// Fields
[DebuggerBrowsable(DebuggerBrowsableState.Never), CompilerGenerated, DebuggerNonUserCode]
public readonly string name1;
// Methods
[CompilerGenerated, DebuggerNonUserCode]
public _Name(string name1);
}
so when you do:
let r=Id(5)
let s=Name("bob")
r and s are instances of _Id and _Name, respectively.
So the answer to your question is likely the answer to one of the following questions:
How do I map to an abstract class in nhibernate?
How can I make NHibernate use a factory method?
How can I create map Nhibernate to immutable objects?
How do I do implement a custom type in NHibernate (presumably with IUserType).
Unfortunately, I'm not savvy enough to give you a coherent answer to any of those, but I'm sure someone else here has done at least one of these three solutions.
I'd like to think that you can use the same methods used for Inheritance Strategies, using, for example, a discriminator column, but I'm afraid the lack of a default constructor makes this problematic. So I'm inclined to think that using a custom type is the solution.
After some fiddling, here's a (possibly buggy and or broken) custom user type:
type RequestInfo =
| Id of int
| Name of string
type RequestInfoUserType() as self =
interface IUserType with
member x.IsMutable = false
member x.ReturnedType = typeof<RequestInfo>
member x.SqlTypes = [| NHibernate.SqlTypes.SqlType(Data.DbType.String); NHibernate.SqlTypes.SqlType(Data.DbType.Int32); NHibernate.SqlTypes.SqlType(Data.DbType.String) |]
member x.DeepCopy(obj) = obj //Immutable objects shouldn't need a deep copy
member x.Replace(original,target,owner) = target // this might be ok
member x.Assemble(cached, owner) = (x :> IUserType).DeepCopy(cached)
member x.Disassemble(value) = (x :> IUserType).DeepCopy(value)
member x.NullSafeGet(rs, names, owner)=
// we'll use a column as a type discriminator, and assume the first mapped column is an int, and the second is a string.
let t,id,name = rs.GetString(0),rs.GetInt32(1),rs.GetString(2)
match t with
| "I" -> Id(id) :> System.Object
| "N" -> Name(name) :> System.Object
| _ -> null
member x.NullSafeSet(cmd, value, index)=
match value with
| :? RequestInfo ->
let record = value :?> RequestInfo
match record with
| Id(i) ->
cmd.Parameters.Item(0) <- "I"
cmd.Parameters.Item(1) <- i
| Name(n) ->
cmd.Parameters.Item(0) <- "N"
cmd.Parameters.Item(2) <- n
| _ -> raise (new ArgumentException("Unexpected type"))
member x.GetHashCode(obj) = obj.GetHashCode()
member x.Equals(a,b) =
if (Object.ReferenceEquals(a,b)) then
true
else
if (a=null && b=null) then
false
else
a.Equals(b)
end
This code could surely be made more generic, and should probably not be in your actual domain layer, but I thought it would be useful to take a stab at a F# implementation of IUserType.
Your mapping file would then do something like:
<property name="IdOrName" type="MyNamespace.RequestInfoUserType, MyAssembly" >
<column name="Type"/>
<column name="Id"/>
<column name="Name"/>
</property>
You probably can get away without a column for "Type" with a slight tweak to the custom UserType code.
I don't know how these custom user types work with queries/ICriteria, as I haven't really worked with custom user types much before.