Getting RCW value of System.__ComObject in windbg script - com

I am trying to write a Windbg script where i have 1k addresses in a file.
For each address, at offset 0x30 is a COM object.
I want to get all native pointers from COM object. I know how to do it manually like below. I am having trouble for iterating it in script.
From a System.__ComObject, !do <comobject> gives RCW: in text. Dumping RCW using !DumpRCW gives me IUnknown pointer that i need.
Name: System.__ComObject
MethodTable: 00007ffcf2941330
EEClass: 00007ffcf22264b0
RCW: 000001d3634f3460
Size: 32(0x20) bytes
File: C:\Windows\Microsoft.Net\assembly\GAC_64\mscorlib\v4.0_4.0.0.0__b77a5c561934e089\mscorlib.dll
Fields:
MT Field Offset Type VT Attr Value Name
00007ffcf2949de8 40005b2 8 System.Object 0 instance 0000000000000000 __identity
00007ffcf294d1f8 400045c 10 ...ections.Hashtable 0 instance 0000000000000000 m_ObjectToDataMap
0:000> !DumpRCW /d 000001d35a9e0d70
Managed object: 000001d37976a708
Creating thread: 000001d35d552a60
IUnknown pointer: 000001d31e63ce28
COM Context: 000001dffecab0f8
Managed ref count: 1
IUnknown V-table pointer : 00007ffcd3f0edb8 (captured at RCW creation time)
Flags:
COM interface pointers:
IP Context MT Type
000001d31e63ce20 000001dffecab0f8 00007ffc949869c0 NativeClass.ClassX
000001d31e63ce28 000001dffecab0f8 00007ffc949868e0 NativeClass.ClassX
For script, the issue is :
How to get RCW value from ComObject using script ? The fields in System.__ComObject are null.
Script that i have so far:
0:000> .foreach /f ( obj "d:\windbg\debug1.allmanagedtxs.small.txt") { .printf "%p\n", obj; !do poi(${obj}+0x30) }
000001d378daa6d8
Name: System.__ComObject
MethodTable: 00007ffcf2941330
EEClass: 00007ffcf22264b0
RCW: 000001d3634f3460
Size: 32(0x20) bytes
File: C:\Windows\Microsoft.Net\assembly\GAC_64\mscorlib\v4.0_4.0.0.0__b77a5c561934e089\mscorlib.dll
Fields:
MT Field Offset Type VT Attr Value Name
00007ffcf2949de8 40005b2 8 System.Object 0 instance 0000000000000000 __identity
00007ffcf294d1f8 400045c 10 ...ections.Hashtable 0 instance 0000000000000000 m_ObjectToDataMap
000001d37976a728
Name: System.__ComObject
MethodTable: 00007ffcf2941330
EEClass: 00007ffcf22264b0
RCW: 000001d35a9e0d70
Size: 32(0x20) bytes
File: C:\Windows\Microsoft.Net\assembly\GAC_64\mscorlib\v4.0_4.0.0.0__b77a5c561934e089\mscorlib.dll
Fields:
MT Field Offset Type VT Attr Value Name
00007ffcf2949de8 40005b2 8 System.Object 0 instance 0000000000000000 __identity
00007ffcf294d1f8 400045c 10 ...ections.Hashtable 0 instance 0000000000000000 m_ObjectToDataMap

I Hate to parse strings :) but here is a recipe again for parsing strings
it is on a live session adapt it to parse from file
/// <reference path="JSProvider.d.ts" />
function log(x) {
host.diagnostics.debugLog(x + "\n")
}
function exec(cmdstr) {
return host.namespace.Debugger.Utility.Control.ExecuteCommand(cmdstr);
}
function rcw(first) {
var obs = exec("!DumpHeap -short -type System.__ComObject")
for (i of obs) {
var cstr = "!do -nofields " + i
foo = exec(cstr)
for (j of foo) {
if (j.includes("RCW") == true) {
blah = exec("!DumpRCW " + j.substr(j.lastIndexOf(" ") + 1))
for (k of blah) {
if (k.includes("IUnknown pointer") == true) {
log(k)
}
}
}
}
}
}
executing this on a live target
.load jsprovider
.scriptload foo.js
0:007> dx #$scriptContents.rcw()
IUnknown pointer: 00000227da903bf0
IUnknown pointer: 00000227da73e618
IUnknown pointer: 00000227da73dd10
IUnknown pointer: 00000227f4a765f0
IUnknown pointer: 00000227f4a77888
IUnknown pointer: 00000227f4a74ea0
#$scriptContents.rcw()
actual clickety click notice the 3bf0
0:007> !DumpHeap -short -type System.__ComObject
00000227dc23b218
00000227dc23f620
00000227dc23f640
00000227dc25e7d0
00000227dc25faa0
00000227dc25fac0
0:007> !DumpObj /d 00000227dc23b218
Name: System.__ComObject
MethodTable: 00007ffda24adad8
EEClass: 00007ffda2492608
RCW: 00000227da7450e0
Size: 32(0x20) bytes
File: C:\WINDOWS\Microsoft.Net\assembly\GAC_64\mscorlib\v4.0_4.0.0.0__b77a5c561934e089\mscorlib.dll
Fields:
MT Field Offset Type VT Attr Value Name
00007ffda2518948 40005b8 8 System.Object 0 instance 0000000000000000 __identity
00007ffda251bb18 4000462 10 ...ections.Hashtable 0 instance 0000000000000000 m_ObjectToDataMap
0:007> !DumpRCW /d 00000227da7450e0
Managed object: 00000227dc23b218
Creating thread: 00000227da6e30b0
IUnknown pointer: 00000227da903bf0
COM Context: 00000227da72c668
Managed ref count: 1
IUnknown V-table pointer : 00007ffdc3252190 (captured at RCW creation time)
Flags:
COM interface pointers:
IP Context MT Type
00000227da903bf0 00000227da72c668 00007ffd4a1b5c88 TestDispatchUtility.DispatchUtility+IDispatchInfo
btw the binary used is from here

Related

How does one access a derived classes member variables from within the superclass in Tcl?

Code:
package require TclOO
oo::class create Supe {
variable cape boots
constructor {} {
puts -nonewline "Supe: "
puts [info class variables [self class]]
}
}
oo::class create Clark {
superclass Supe
variable glasses suit
constructor {} {
puts -nonewline "Clark: "
puts [info class variables [self class]]
next
}
}
set hero [Clark new]
Output:
Clark: glasses suit
Supe: cape boots
Is it possible to get a list of Clark's member variables from within Supe's constructor without passing them into Supe as an argument?
Ultimately, the goal is to dynamically set derived class variables from a dict argument:
foreach {varName} [info class variables [self class]] {
variable $varName [dict get $args $varName]
}
If the above code can be used in the superclass constructor, it would avoid putting it in each derived class constructor.
You can get the name of the object with self object, or just self. You can then get the class of the object with info object class. And finally, you can get the member variables of a class with info class variables.
Putting it all together results in:
[info class variables [info object class [self]]]
My take does not add to the answer already given, but looks at the motivating problem of the OP:
Ultimately, the goal is to dynamically set derived class variables
from a dict argument:
What I have been using in the past to batch-update an object's state is sth. along the lines of:
oo::class create C {
variable a b
constructor {aDict} {
my variable {*}[lsort -unique [my lookupVars [info object class [self]]]]
# dict with aDict {;}
lassign [dict values $aDict] {*}[dict keys $aDict]
}
method lookupVars {currentClass} {
set v [info class variables $currentClass]
foreach scl [info class superclasses $currentClass] {
if {$scl eq "::oo::object"} {
break
}
lappend v {*}[my lookupVars $scl]
}
return $v
}
method print {} {
foreach v [info object vars [self]] {
my variable $v
puts "<$v> [set $v]"
}
}
}
The key items are:
lookupVars is a naturally recursive implementation walking the class, direct, and indirect superclasses to collect of defined per-class variables. This follows up on what Donal describes as a discovery of "properties". Note that this is limited in several ways (e.g., mixins are ignored, also TclOO's internal linearisation scheme is not reflected, no control for duplicates etc.)
lassign can be used to set multiple variables at once. Alternatively, but with some side effects, dict with "loads" a given dict's content into variables available for the current scope. my variable ?varName ...? will provide method-local links to the collected per-class variables. This way, you save a script-level loop and don't have to filter the provided dict for unmatched keys.
Watch:
oo::class create D {
superclass C
variable c d
}
oo::class create E {
superclass D
variable e f
}
[D new {a 1 b 2 c 3 d 4}] print
[E new {a 1 b 2 c 3 d 4 f 5 e 8 x 3}] print
[D new {a 1 b 2 c 3 d 4 f 5 x 3}] print

JNI, How to access the current Java thread in JNI

is there a way to get Java thread(ID, name) from JNI. I am not talking about passing Thread.currentThread().getId() from java to JNI. Does JNI provide API to access currently running thread?
You can (as mentioned by Alex) resort to java.lang.Thread.
// First, we have to find Thread class
jclass cls = (*env)->FindClass(env, "java/lang/Thread");
// Then, we can look for it's static method 'currentThread'
/* Remember that you can always get method signature using javap tool
> javap -s -p java.lang.Thread | grep -A 1 currentThread
public static native java.lang.Thread currentThread();
descriptor: ()Ljava/lang/Thread;
*/
jmethodID mid =
(*env)->GetStaticMethodID(env, cls, "currentThread", "()Ljava/lang/Thread;");
// Once you have method, you can call it. Remember that result is
// a jobject
jobject thread = (*env)->CallStaticObjectMethod(env, cls, mid);
if( thread == NULL ) {
printf("Error while calling static method: currentThread\n");
}
// Now, we have to find another method - 'getId'
/* Remember that you can always get method signature using javap tool
> javap -s -p java.lang.Thread | grep -A 1 getId
public long getId();
descriptor: ()Jjavap -s -p java.lang.Thread | grep -A 1 currentThread
*/
jmethodID mid_getid =
(*env)->GetMethodID(env, cls, "getId", "()J");
if( mid_getid == NULL ) {
printf("Error while calling GetMethodID for: getId\n");
}
// This time, we are calling instance method, note the difference
// in Call... method
jlong tid = (*env)->CallLongMethod(env, thread, mid_getid);
// Finally, let's call 'getName' of Thread object
/* Remember that you can always get method signature using javap tool
> javap -s -p java.lang.Thread | grep -A 1 getName
public final java.lang.String getName();
descriptor: ()Ljava/lang/String;
*/
jmethodID mid_getname =
(*env)->GetMethodID(env, cls, "getName", "()Ljava/lang/String;");
if( mid_getname == NULL ) {
printf("Error while calling GetMethodID for: getName\n");
}
// As above, we are calling instance method
jobject tname = (*env)->CallObjectMethod(env, thread, mid_getname);
// Remember to retrieve characters from String object
const char *c_str;
c_str = (*env)->GetStringUTFChars(env, tname, NULL);
if(c_str == NULL) {
return;
}
// display message from JNI
printf("[C ] name: %s id: %ld\n", c_str, tid);
// and make sure to release allocated memory before leaving JNI
(*env)->ReleaseStringUTFChars(env, tname, c_str);
You can find full sample here: https://github.com/mkowsiak/jnicookbook/tree/master/recipes/recipeNo044

is there an object constructor in rebol

I usually program by functions in an "instinctive" manner, but my current problem can be easily solved by objects, so I go ahead with this method.
Doing so, I am trying to find a way to give an object a constructor method, the equivalent of init() in python, for example.
I looked in the http://www.rebol.com/docs/core-fr/fr-index.html documentation, but I couldn't find anything relevant.
There is no special constructor function in Rebol, but there is a possibility to write ad hoc init code if you need it on object's creation in the spec block. For example:
a: context [x: 123]
b: make a [
y: x + 1
x: 0
]
So, if you define your own "constructor" function by convention in the base object, you can call it the spec block on creation. If you want to make it automatic, you can wrap that in a function, like this:
a: context [
x: 123
init: func [n [integer!]][x: n]
]
new-a: func [n [integer!]][make a [init n]]
b: new-a 456
A more robust (but bit longer) version of new-a that would avoid the possible collision of passed arguments to init with object's own words would be:
new-a: func [n [integer!] /local obj][
also
obj: make a []
obj/init n
]
You could also write a more generic new function that would take a base object as first argument and automatically invoke a constructor-by-convention function after cloning the object, but supporting optional constructor arguments in a generic way is then more tricky.
Remember that the object model of Rebol is prototype-based (vs class-based in Python and most other OOP languages), so the "constructor" function gets duplicated for each new object created. You might want to avoid such cost if you are creating a huge number of objects.
To my knowledge, there is no formal method/convention for using object constructors such as init(). There is of course the built-in method of constructing derivative objects:
make prototype [name: "Foo" description: "Bar"]
; where type? prototype = object!
My best suggestion would be to define a function that inspects an object for a constructor method, then applies that method, here's one such function that I've proposed previously:
new: func [prototype [object!] args [block! none!]][
prototype: make prototype [
if in self 'new [
case [
function? :new [apply :new args]
block? :new [apply func [args] :new [args]]
]
]
]
]
The usage is quite straightforward: if a prototype object has a new value, then it will be applied in the construction of the derivative object:
thing: context [
name: description: none
new: [name: args/1 description: args/2]
]
derivative: new thing ["Foo" "Bar"]
note that this approach works in both Rebol 2 and 3.
Actually, by reading again the Rebol Core documentation (I just followed the good old advice: "Read The French Manual"), there is another way to implement a constructor, quite simple:
http://www.rebol.com/docs/core-fr/fr-rebolcore-10.html#section-8
Of course it is also in The English Manual:
http://www.rebol.com/docs/core23/rebolcore-10.html#section-7
=>
Another example of using the self variable is a function that clones
itself:
person: make object! [
name: days-old: none
new: func [name' birthday] [
make self [
name: name'
days-old: now/date - birthday
]
]
]
lulu: person/new "Lulu Ulu" 17-May-1980
print lulu/days-old
7366
I find this quite convenient, and this way, the constructor lies within the object. This fact makes the object more self-sufficient.
I just implemented that successfully for some geological stuff, and it works well:
>> source orientation
orientation: make object! [
matrix: []
north_reference: "Nm"
plane_quadrant_dip: ""
new: func [{Constructor, builds an orientation object! based on a measurement, as given by GeolPDA device, a rotation matrix represented by a suite of 9 values} m][
make self [
foreach [a b c] m [append/only matrix to-block reduce [a b c]]
a: self/matrix/1/1
b: self/matrix/1/2
c: self/matrix/1/3
d: self/matrix/2/1
e: self/matrix/2/2
f: self/matrix/2/3
g: self/matrix/3/1
h: self/matrix/3/2
i: self/matrix/3/3
plane_normal_vector: reduce [matrix/1/3
matrix/2/3
matrix/3/3
]
axis_vector: reduce [self/matrix/1/2
self/matrix/2/2
self/matrix/3/2
]
plane_downdip_azimuth: azimuth_vector plane_normal_vector
plane_direction: plane_downdip_azimuth - 90
if (plane_direction < 0) [plane_direction: plane_direction - 180]
plane_dip: arccosine (plane_normal_vector/3)
case [
((plane_downdip_azimuth > 315) or (plane_downdip_azimuth <= 45)) [plane_quadrant_dip: "N"]
((plane_downdip_azimuth > 45) and (plane_downdip_azimuth <= 135)) [plane_quadrant_dip: "E"]
((plane_downdip_azimuth > 135) and (plane_downdip_azimuth <= 225)) [plane_quadrant_dip: "S"]
((plane_downdip_azimuth > 225) and (plane_downdip_azimuth <= 315)) [plane_quadrant_dip: "W"]
]
line_azimuth: azimuth_vector axis_vector
line_plunge: 90 - (arccosine (axis_vector/3))
]
]
repr: func [][
print rejoin ["Matrix: " tab self/matrix
newline
"Plane: " tab
north_reference to-string to-integer self/plane_direction "/" to-string to-integer self/plane_dip "/" self/plane_quadrant_dip
newline
"Line: " tab
rejoin [north_reference to-string to-integer self/line_azimuth "/" to-string to-integer self/line_plunge]
]
]
trace_te: func [diagram [object!]][
len_queue_t: 0.3
tmp: reduce [
plane_normal_vector/1 / (square-root (((plane_normal_vector/1 ** 2) + (plane_normal_vector/2 ** 2))))
plane_normal_vector/2 / (square-root (((plane_normal_vector/1 ** 2) + (plane_normal_vector/2 ** 2))))
]
O: [0 0]
A: reduce [- tmp/2
tmp/1
]
B: reduce [tmp/2 0 - tmp/1]
C: reduce [tmp/1 * len_queue_t
tmp/2 * len_queue_t
]
L: reduce [- axis_vector/1 0 - axis_vector/2]
append diagram/plot [pen black]
diagram/trace_line A B
diagram/trace_line O C
diagram/trace_line O L
]
]
>> o: orientation/new [0.375471 -0.866153 -0.32985 0.669867 0.499563 -0.549286 0.640547 -0.0147148 0.767778]
>> o/repr
Matrix: 0.375471 -0.866153 -0.32985 0.669867 0.499563 -0.549286 0.640547 -0.0147148 0.767778
Plane: Nm120/39/S
Line: Nm299/0
Another advantage of this way is that variables defined by the "new" method directly belongs to the object "instance" (I ran into some trouble, with the other methods, having to mention self/ sometimes, having to initialize variables or not).
I'm trying to find out how OO works in REBOL. Prototypical indeed. Yesterday I came across this page, which inspired me to the classical OO model below, without duplication of functions:
;---- Generic function for class or instance method invocation ----;
invoke: func [
obj [object!]
fun [word!]
args [block!]
][
fun: bind fun obj/.class
;---- Class method names start with a dot and instance method names don't:
unless "." = first to-string fun [args: join args obj]
apply get fun args
]
;---- A class definition ----;
THIS-CLASS: context [
.class: self ; the class refers to itself
;---- Class method: create new instance ----;
.new: func [x' [integer!] /local obj] [
obj: context [x: x' .class: none] ; this is the object definition
obj/.class: self/.class ; the object will refer to the class
; it belongs to
return obj
]
;---- An instance method (last argument must be the instance itself) ----;
add: func [y obj] [
return obj/x + y
]
]
Then you can do this:
;---- First instance, created from its class ----;
this-object: THIS-CLASS/.new 1
print invoke this-object 'add [2]
;---- Second instance, created from from a prototype ----;
that-object: this-object/.class/.new 2
print invoke that-object 'add [4]
;---- Third instance, created from from a prototype in another way ----;
yonder-object: invoke that-object '.new [3]
print invoke yonder-object 'add [6]
;---- Fourth instance, created from from a prototype in a silly way ----;
silly-object: yonder-object/.class/.class/.class/.class/.new 4
print silly-object/.class/add 8 silly-object
print this-object/.class/add 8 silly-object
print THIS-CLASS/add 8 silly-object
(It works in REBOL 2, and prints 3, 6, 9, 12, 12, 12 successively.) Hardly any overhead. Probably it won't be difficult to find a dozen of other solutions. Exactly that is the real problem: there are too many ways to do it. (Maybe we'd better use LoyalScript.)

Evaluating a "variable variable"

I'm creating a dynamic variable ("Variable variable" in PHP parlance) with the following:
foo: "test1"
set to-word (rejoin [foo "_result_data"]) array 5
But how do I get the value of the resulting variable named "test1_result_data" dynamically? I tried the following:
probe to-word (rejoin [foo "_result_data"])
but it simply returns "test1_result_data".
As your example code is REBOL 2, you can use GET to obtain the value of the word:
>> get to-word (rejoin [foo "_result_data"])
== [none none none none none]
REBOL 3 handles contexts differently from REBOL 2. So when creating a new word you will need to handle it's context explicitly otherwise it will not have a context and you'll get an error when you try to set it. This is in contrast to REBOL 2 which set the word's context by default.
So you could consider using REBOL 3 code like the following to SET/GET your dynamic variables:
; An object, providing the context for the new variables.
obj: object []
; Name the new variable.
foo: "test1"
var: to-word (rejoin [foo "_result_data"])
; Add a new word to the object, with the same name as the variable.
append obj :var
; Get the word from the object (it is bound to it's context)
bound-var: in obj :var
; You can now set it
set :bound-var now
; And get it.
print ["Value of " :var " is " mold get :bound-var]
; And get a list of your dynamic variables.
print ["My variables:" mold words-of obj]
; Show the object.
?? obj
Running this as a script yields:
Value of test1_result_data is 23-Aug-2013/16:34:43+10:00
My variables: [test1_result_data]
obj: make object! [
test1_result_data: 23-Aug-2013/16:34:43+10:00
]
An alternative to using IN above could have been to use BIND:
bound-var: bind :var obj
In Rebol 3 binding is different than Rebol 2 and there are some different options:
The clumsiest option is using load:
foo: "test1"
set load (rejoin [foo "_result_data"]) array 5
do (rejoin [foo "_result_data"])
There is a function that load uses--intern--which can be used to bind and retrieve the word to and from a consistent context:
foo: "test1"
set intern to word! (rejoin [foo "_result_data"]) array 5
get intern to word! (rejoin [foo "_result_data"])
Otherwise to word! creates an unbound word that is not easy to utilize.
The third option is to use bind/new to bind the word to a context
foo: "test1"
m: bind/new to word! (rejoin [foo "_result_data"]) system/contexts/user
set m array 5
get m
probe do (rejoin [foo "_result_data"])
from http://www.rebol.com/docs/core23/rebolcore-4.html#section-4.6

...array<Object^>^ args

I'm reading C++/CLI. I see this stuff:
Object^ CreateInstanceFromTypename(String^ type, ...array<Object^>^ args)
{
if (!type)
throw gcnew ArgumentNullException("type");
Type^ t = Type::GetType(type);
if (!t)
throw gcnew ArgumentException("Invalid type name");
Object^ obj = Activator::CreateInstance(t, args);
return obj;
}
When calling it:
Object^ o = CreateInstanceFromTypename(
"System.Uri, System, Version=2.0.0.0, "
"Culture=neutral, PublicKeyToken=b77a5c561934e089",
"http://www.heege.net"
);
What is ...array^ args? If I remove ... ,there's a complied-error:
error C2665: 'CreateInstanceFromTypeName' : none of the 2 overloads could convert all the argument types
1> .\myFourthCPlus.cpp(12): could be 'System::Object ^CreateInstanceFromTypeName(System::String ^,cli::array<Type> ^)'
1> with
1> [
1> Type=System::Object ^
1> ]
1> while trying to match the argument list '(const char [86], const char [21])'
Like C++, C++/CLI has a mechanism for a variable amount of arguments. That is what the ... in front of the ...array<Object^>^ parameter means.
For type safety the C++/CLI designers added managed syntax to declare the type of the variable array.
Since it's just passing that parameter to the Activator::CreateInstance() function, I would look at what variable parameters the Activator function is looking for.