How to read from NativeReturnValue returned by NativeFunction in Frida? - frida

// test.ts
Java.perform(function() {
var malloc = new NativeFunction(
Module.findExportByName('libc.so', 'malloc'),
'pointer', // ret type
['uint32'] // arg type
);
var p = malloc(4);
p.readU8(); // error
});
I'm trying to compile the above .ts file to .js with frida-compile. I tried to read from the variable p with .readU8() but error occurs: Property 'readU8' does not exist on type 'NativeReturnValue'
From the source code it's defined as:
type NativeReturnValue = NativePointer | UInt64 | Int64 | number | boolean | any[];
I know little about TypeScript, seems NativeReturnValue is some kind of NativePointer, but how to cast ?
Thanks.

Related

Matching std::optional<bool> with Clang AST

I'm trying to write a clang-tidy check for std::optional<bool> r = 5 to catch implicit conversions to bool.
|-DeclStmt <line:4:5, col:30>
| `-VarDecl <col:5, col:29> col:25 r 'std::optional<bool>':'std::optional<bool>' cinit
| `-ExprWithCleanups <col:29> 'std::optional<bool>':'std::optional<bool>'
| `-ImplicitCastExpr <col:29> 'std::optional<bool>':'std::optional<bool>' <ConstructorConversion>
| `-CXXConstructExpr <col:29> 'std::optional<bool>':'std::optional<bool>' 'void (int &&) noexcept(is_nothrow_constructible_v<bool, int>)'
| `-MaterializeTemporaryExpr <col:29> 'int' xvalue
| `-IntegerLiteral <col:29> 'int' 5
So far, I have match implicitCastExpr(hasDescendant(cxxConstructExpr())) where I'm matching for an implicitCastExpr with a cxxConstructoExpr. The problem is I want to narrow the match on cxxConstructExpr to find only cases where bool is the template argument. Does anyone know how to do this?
Inside cxxConstructExpr(...), you also need to use hasType, classTemplateSpecializationDecl, hasTemplateArgument, refersToType, and booleanType.
Here is a shell script invoking clang-query that finds implicit conversions to std::optional<bool> from a type other than bool:
#!/bin/sh
query='m
implicitCastExpr( # Implicit conversion
hasSourceExpression( # from a
cxxConstructExpr( # constructor expr
hasType( # whose type is
classTemplateSpecializationDecl( # a template specialization
hasName("::std::optional"), # of std::optional
hasTemplateArgument( # with template argument
0, refersToType(booleanType()) # bool,
)
)
),
unless( # unless
hasArgument( # the constructor argument
0, expr( # is an expr with
hasType( # type
booleanType() # bool.
)
)
)
)
)
)
)'
clang-query -c="$query" "$#"
(I use a shell script so I can format the query expression and add comments.)
Test input test.cc:
// test.cc
// Test clang-query finding implicit conversions to optional<bool>.
#include <optional> // std::optional
void f()
{
std::optional<bool> r = 5; // reported
std::optional<int> s = 6; // not reported
std::optional<bool> t = false; // not reported
}
// EOF
Invocation of the script (saved as cmd.sh):
$ ./cmd.sh test.cc -- --std=c++17
Match #1:
[...path...]/test.cc:8:27: note: "root" binds here
std::optional<bool> r = 5; // reported
^
1 match.
I used Clang+LLVM-14.0.0, although I don't think I've used anything particularly recent here.
Figuring out these match expressions can be quite difficult. The main reference is the AST Matcher Reference, but even with that, it often requires a lot of trial and error.

Type inference is dynamic on operator overloading with extension in Dart

I try to implement pipe-operator overriding |
extension Pipe on Object {
operator |(Function(Object) f) => f(this);
}
typedef Id = A Function<A>(A);
Id id = <A>(A a) => a;
var t1 = id("test"); // String t1
var t2 = "test" | id; // dynamic t2
with the generic Id function above, on id("test") is detected as String, but "test" | id is dynamic which is very problematic.
How can I fix this?
EDIT
Thankfully, #jamesdlin has answered and suggested:
extension Pipe on Object {
Object operator |(Object Function(Object) f) => f(this);
}
the result has improved as
var t2 = "test" | id; // Object t2
I also tried with generic as follows:
extension Pipe<A, B> on A {
B operator |(B Function(A) f) => f(this);
}
I expected it would go better because I thought the generic A B is more specific and better than Object ; however, the result goes as bad as before:
var t2 = "test" | id; // dynamic t2
Why the generic does not work? Is there any way to make the dart compiler infer it as string ?
Your operator | extension does not have a declared return type. Its return type therefore is implicitly dynamic. Also note its callback argument does not specify a return type either, so that also will be assumed to be dynamic.
Declare return types:
extension Pipe on Object {
Object operator |(Object Function(Object) f) => f(this);
}
(Answering your original question about a NoSuchMethodError: when you did
var x = "test" | id;
x | print;
x has type dynamic, but extension methods are static; they are compile-time syntactic sugar and will never work on dynamic types. Consequently, x | print attempts to call operator | on the object that x refers to, but that object doesn't actually have an operator |.)

How to give a reference an explicit lifetime in rust? [duplicate]

This question already has answers here:
Return local String as a slice (&str)
(7 answers)
Closed 8 months ago.
I'm trying to return a Result<(), &str> in rust, where the &str has embedded data about any errors which have occurred. For example, say I have the following code:
struct Foo {
pub mynum :i32,
}
impl Foo {
fn do_something(&self) -> Result<(), &str> {
if self.mynum % 12 == 0 {
return Err(&format!("error! mynum is {}", self.mynum))
}
Ok(())
}
}
fn main() {
let foo_instance = Foo{
mynum: 36,
};
let result = foo_instance.do_something().unwrap();
println!("{:?}",result)
}
If I run this in the rust playground, I get
error[E0515]: cannot return value referencing temporary value
--> src/main.rs:9:20
|
9 | return Err(&format!("error! mynum is {}", self.mynum))
| ^^^^^-----------------------------------------^
| | |
| | temporary value created here
| returns a value referencing data owned by the current function
which isn't desired.
How do I tell the Rust compiler that to create a &str with lifetime 'a where 'a is the lifetime of self? I don't want to use 'static if possible, and I don't want to load Foo with extra members..
You should not return a &str in this case because the underlying object the &str is referencing gets dropped when the function terminates. Essentially, you are attempting to return a reference to a temporary value which gets deleted. See this article on differences between String and &str.
String is probably what you want instead. This compiles:
fn do_something(&self) -> Result<(), String> {
if self.mynum % 12 == 0 {
return Err(format!("error! mynum is {}", self.mynum));
}
Ok(())
}

Pattern Matching does not allow me to change values

so I am currently working on a new programming language tr-lang
and I am currently in the process of writing the parser of the language
this piece of code is where the bug lies
BlockToken::İse(bip) => {
let ise = &mut parsed[bip]; // Access method 1
match ise.typ {
TokenType::İse ( mut yoksa ) => {
yoksa = Some(ip);
},
TokenType::Yoksa ( mut tp ) => {
tp = Some(ip);
},
_ => unreachable!(),
}
ip + 1
},
BlockToken::İken(bip) => {
let iken = parsed.get_mut(bip).unwrap(); // Trying other access methods
match iken.typ {
TokenType::İken ( mut yoksa ) => {
yoksa = Some(ip + 1);
},
_ => unreachable!(),
}
bip
},
_ => unimplemented!(),
};
and this is part of the code that parses and produces an executable program
and it gives a few warnings but i think the problem lies in these ones:
warning: variable `yoksa` is assigned to, but never used
--> src/parser/parser.rs:121:54
|
121 | ... TokenType::İse ( mut yoksa ) => {
| ^^^^^
|
= note: consider using `_yoksa` instead
warning: value assigned to `yoksa` is never read
--> src/parser/parser.rs:122:37
|
122 | ... yoksa = Some(ip);
| ^^^^^
|
= help: maybe it is overwritten before being read?
warning: variable `tp` is assigned to, but never used
--> src/parser/parser.rs:124:56
|
124 | ... TokenType::Yoksa ( mut tp ) => {
| ^^
|
= note: consider using `_tp` instead
warning: value assigned to `tp` is never read
--> src/parser/parser.rs:125:37
|
125 | ... tp = Some(ip);
| ^^
|
= help: maybe it is overwritten before being read?
warning: variable `yoksa` is assigned to, but never used
--> src/parser/parser.rs:134:55
|
134 | ... TokenType::İken ( mut yoksa ) => {
| ^^^^^
|
= note: consider using `_yoksa` instead
warning: value assigned to `yoksa` is never read
--> src/parser/parser.rs:135:37
|
135 | ... yoksa = Some(ip + 1);
| ^^^^^
|
= help: maybe it is overwritten before being read?
as you can see for some reason even though i pattern-match like usual when i try to set the value to something else it treats the variables as different
and instead of changing the value of yoksa/tp the end result just does not change anything
i tried changing the way i access ise/iken however it didn't change anything
i also tried using if let instead of match
it doesn't change the value of ise.typ.yoksa or ise.typ.tp
for extra info BlockToken is this enum
enum BlockToken {
İse(usize),
İken(usize),
İkiNoktaNokta(usize),
}
Token is this struct
struct Token {
pub typ: TokenType,
pub line: usize,
pub col: usize,
}
what i want from here is the ability to change the contents of the enum structs İse, İken and Yoksa
it can be unsafe although a safe method is preferred
Use Option::replace to fit the new value into the mutable option:
yoksa.replace(ip + 1);
Also you probably want a mutable reference:
TokenType::İken(ref mut yoksa)
I think you need to match on a mutable reference when matching otherwise you are just creating a local variable and mutating that.
For example this code:
#[derive(Debug)]
enum Blah {
A(u64),
}
mod test {
use super::Blah;
#[test]
fn test_match() {
let mut a = Blah::A(23);
println!("{:?}", a);
match a {
Blah::A(ref mut x) => *x = 5,
}
println!("{:?}", a);
}
}
will output:
running 1 test
A(23)
A(5)
If you run it with cargo test -- --nocapture.

How do I Override ToString in a Composite Type in F#?

I'm learning about creating composite* types in F# and I ran into a problem. I have this type and a ToString override.
type MyType =
| Bool of bool
| Int of int
| Str of string
with override this.ToString() =
match this with
| Bool -> if this then "I'm True" else "I'm False"
| Int -> base.ToString()
| Str -> this
let c = Bool(false)
printfn "%A" c
I get an error inside the ToString override that says "This constructor is applied to 0 argument(s) but expects 1". I was pretty sure this code wouldn't compile, but it shows what I'm trying to do. When I comment out the override and run the code, c is printed out as "val c : MyType = Bool false". When I step into that code, I see that c has a property Item set to the boolean false. I can't seem to access this property in the code however. Not even if I annotate c.
How should I be overriding ToString in this situation?
* I'm pretty sure these are called composite types.
When you are using a Discriminated Union (DU) (that's the appropriate name for that type), you need to unpack the value in the match statement like this:
type MyType =
| Bool of bool
| Int of int
| Str of string
with override this.ToString() =
match this with
| Bool(b) -> if b then "I'm True" else "I'm False"
| Int(i) -> i.ToString()
| Str(s) -> s
let c = Bool(false)
printfn "%A" c
The Item property that you're seeing is an implementation detail and is not intended to be accessed from F# code. Merely using this doesn't work because the DU is a wrapper around the value, so this refers to the wrapper, not to the contained value.

Resources