ghidra: how to get static variables using ghidra python api? - x86-64

I have a following c code (from a benchmark):
int main(int argc, char *argv[])
{
static char buf[10] = "";
/* OK */
buf[9] = 'A';
return 0;
}
I am using ghidra api to get some information out of the binary (precompiled using flag -g). I want to get the variables defined in the function (or globally).
function.getStackFrame().getStackVariables()
gives me variables defined within the function, but it doesn't detect buf, as it is defined as static. From ghidra gui I was able to see that the variables is defined in the "main" under namespaces.
Is there way to get these type of variables (or global variables in general)?

If you compile with gcc, a static variable defined within a function (e.g., the variable buf, in your case) is represented as a global variable that starts with the same name and ends with a compiler-assigned numeric suffix. Such a variable will be assigned within Ghidra to the "global" namespace, rather than the function's namespace.
In Ghidra, each default global variable name ends with the variable's address. Each default local variable name starts with "local_" and ends with the variable's stack offset.
I've only used the Java API. But the Ghidra class hierarchy should be the same, regardless of whether you use Java or Python. Here is an example Java script that will list all non-default global and local variables in the current program:
// Lists non-default global and local variables in the current program.
//#category Example
import ghidra.app.script.GhidraScript;
import ghidra.program.database.ProgramDB;
import ghidra.program.database.symbol.NamespaceManager;
import ghidra.program.database.symbol.SymbolManager;
import ghidra.program.model.listing.Function;
import ghidra.program.model.listing.Variable;
import ghidra.program.model.symbol.Symbol;
import ghidra.program.model.symbol.SymbolType;
public class ListVariables extends GhidraScript {
#Override
public void run() throws Exception {
// List globals
SymbolManager smgr = (SymbolManager)currentProgram.getSymbolTable();
NamespaceManager nmgr =
((ProgramDB)currentProgram).getNamespaceManager();
for (Symbol sym : smgr.getSymbols(nmgr.getGlobalNamespace())) {
if (monitor.isCancelled()) return;
if (sym.getSymbolType() == SymbolType.LABEL) {
String sname = sym.getName();
if (!sname.endsWith(sym.getAddress().toString())) {
printf("global : %s\n", sname);
}
}
}
//List local variables
for (Function func :
currentProgram.getFunctionManager().getFunctions(true)) {
for (Variable var : func.getLocalVariables()) {
if (monitor.isCancelled()) return;
String vname = var.getName();
if (!vname.startsWith("local_")) {
printf("%s : %s\n", func.getName(), vname);
}
}
}
}
}
The script writes its output to the Ghidra console window. Double-clicking a function or variable name in the Ghidra console window will jump the listing to the corresponding function/variable.

Related

Can I use in Google Apps Scripts a defined Class in a library with ES6 (V8)?

I'm trying to use a class defined in a library but I only receive an error as a result.
[LibraryProject]/library/model/Update.gs
class Update {
constructor(obj = {}) {
if(typeof obj == "string"){
options = JSON.parse(obj);
}
Object.assign(this, obj);
}
text(){
return (this.message && this.message.text)?this.message.text:''
}
}
TASKS
✅ Create a new version of the project. (File > Manage versions...)
✅ Load this library in another project [Alias: CustomService] (Resources > Libraries...)
✅ Use functions of CustomService
❌ Use class of CustomService
If I try to use a Class
[NormalProject]/index.gs
function test (){
Logger.log(CustomService.libraryFunction())
var update = new CustomService.Update("");
Logger.log(update)
}
TypeError: CustomService.Update is not a constructor (línea 3, archivo "Code")
How can I instantiate an Object of this Class?
If I run...
Logger
As written in the official documentation,
Only the following properties in the script are available to library users:
enumerable global properties
function declarations,
variables created outside a function with var, and
properties explicitly set on the global object.
This would mean every property in the global this object are available to library users.
Before ES6, All declarations outside a function (and function declaration themselves) were properties of this global object. After ES6, There are two kinds of global records:
Object record- Same as ES5.
Function declarations
Function generators
Variable assignments
Declarative record - New
Everything else - let, const, class
Those in the declarative record are not accessible from the global "object", though they are globals themselves. Thus, the class declaration in the library is not accessible to library users. You could simply add a variable assignment to the class to add a property to the global object(outside any function):
var Update = class Update{/*your code here*/}
References:
Library official documentation
Global environment records
Related Answers:
ES6- What about introspection
Do let statements create properties on the global object
Based on your tests, it appears that you cannot directly import a class from a GAS library. I'd recommend creating a factory method to instantiate the class instead.
Something along these lines:
// Library GAS project
/**
* Foo class
*/
class Foo {
constructor(params) {...}
bar() {...}
}
/* globally accessible factory method */
function createFoo(fooParams) {
return new Foo(fooParams);
}
// Client GAS project
function test() {
var foo = FooService.createFoo(fooParams);
Logger.log(foo.bar());
}

How to control argument passing policy in pybind11 wrapping of std::function?

I have a class in c++ that I'm wrapping into python with pybind11. That class has a std::function, and I'd like to control how the arguments to that function are dealt with (like return value policies). I just can't find the syntax or examples to do this...
class N {
public:
using CallbackType = std::function<void(const OtherClass*)>;
N(CallbackType callback): callback(callback) { }
CallbackType callback;
void doit() {
OtherClass * o = new OtherClass();
callback(o);
}
}
wrapped with
py::class_<OtherClass>(...standard stuff...);
py::class_<N>(m, "N")
.def(py::init<N::CallbackType>(),
py::arg("callback"));
I all works: I can do this in python:
def callback(o):
dosomethingwith(o)
k = N(callback)
, but I'd like to be able to control what happens when callback(o); is called - whether python then will take ownership of the wrapped o variable or not, basically.
I put a printout in the destructor of OtherClass, and as far as I can tell, it never gets called.
OK, I think I figured it out:
Instead of std::function, use a pybind11::function:
using CallbackType = pybind11::function
and then
void doit(const OtherClass &input) {
if (<I want to copy it>) {
callback(pybind11::cast(input, pybind11::return_value_policy::copy));
} else {
callback(pybind11::cast(input, pybind11::return_value_policy::reference));
}
}
I see nothing in pybind11/functional that allows you to change the ownership of the parameters at the point of call, as the struct func_wrapper used is function local, so can not be specialized. You could provide another wrapper yourself, but in the code you can't know whether the callback is a Python function or a bound C++ function (well, technically you can if that bound C++ function is bound by pybind11, but you can't know in general). If the function is C++, then changing Python ownership in the wrapper would be the wrong thing to do, as the temporary proxy may destroy the object even as its payload is stored by the C++ callback.
Do you have control over the implementation of class N? The reason is that by using std::shared_ptr all your ownership problems will automagically evaporate, regardless of whether the callback function is C++ or Python and whether it stores the argument or not. Would work like so, expanding on your example above:
#include <pybind11/pybind11.h>
#include <pybind11/functional.h>
namespace py = pybind11;
class OtherClass {};
class N {
public:
using CallbackType = std::function<void(const std::shared_ptr<OtherClass>&)>;
N(CallbackType callback): callback(callback) { }
CallbackType callback;
void doit() {
auto o = std::make_shared<OtherClass>();
callback(o);
}
};
PYBIND11_MODULE(example, m) {
py::class_<OtherClass, std::shared_ptr<OtherClass>>(m, "OtherClass");
py::class_<N>(m, "N")
.def(py::init<N::CallbackType>(), py::arg("callback"))
.def("doit", &N::doit);
}

find variable Declaration reference Abstract syntax tree eclipse cdt C code

I have a c code like this
int x;
x = 5;
I used eclipse cdt to generate the AST, and traverse on it, so this is the code of the traversed class
public class RuleChk extends AbstractRule {
public RuleChk(IASTTranslationUnit ast) {
super("RuleChk", false, ast);
shouldVisitDeclarations = true;
shouldVisitParameterDeclarations = true;
}
#Override
public int visit(IASTSimpleDeclaration simpleDecl) {
//if this node has init, e.g: x = 5, do business
if(VisitorUtil.containNode(simpleDecl, CASTExpressionStatement){
// Now I have the x = 5 node,
// I want to get the reference node of it's declaration
// I mean (int x;) node
IASTNode declNode = ?????
}
return super.visit(parameterDeclaration);
}
}
what I want to visit the node that only has assignation(Initialization) and get the reference of declaration node for that varaiable.
I'm not sure how VisitorUtil works (it's not from the CDT code), but I assume it gives you a way to access the the found node. So:
Given the IASTExpressionStatement node that was found, use IASTExpression.getExpression() to get the contained expression.
See if it's an IASTBinaryExpression, and that is getOperator() is IASTBinaryExpression.op_assign.
Use IASTBinaryExpression.getOperand1() to get the assignment expression's left subexpression. Check that it's an IASTIdExpression, and get the variable it names via IASTIdExpression.getName().
Now that you have the name, use IASTName.resolveBinding() to get the variable's binding. This is the variable's representation in the semantic program model.
To find the variable's definition, use IASTTranslationUnit.getDefinitionsInAST(IBinding) if you only want it to look in the current file, or IASTTranslationUnit.getDefinitions(IBinding) if you want it to look in included header files as well (the latter requires the project to be indexed). The IASTTranslationUnit can be obtained from any IASTNode via IASTNode.getTranslationUnit().

How to dynamically add a key:value property to c++ class, then make it accessible as class.property

In Python I have a flag class that I have found very useful. I'm newbe to c++, and can not seem to replicate this python functionality in c++. Rather than put up c++ code that didn't work, here's what I am looking to replicate, and I need some suggestions on where to go, templates, virtual, or ??
The requirement is being able to dynamically alter the members of the class, in python it's modifying the dict element of the class it's self that enables this.
In python:
import sys
args = []
... loads up args[] with keys:values looping through sys.argv[] ... blah blah blah
class Flag:
def __ init __(self, **args):
self. __ dict __.update(args)
now we enable flag.dynamicproperty
flag = Flag(**dict(args))
An example of use:
$ python script.py somedesc1 someval1 somedesc2 someval2
What this does is enables me to pass in parameters, as above, from the command-line and assign any number of them on-the-fly, and make then accessible by a flag.property (eg flag.somedesc1) call which returns somval1. Another way to maybe think about this is dynamically adding a key:value property to a C++ class.
An example of use in python code :
if flag.somedesc1 != '10': print someval1
I can't seem to make a comparable c++ work. I've looked into polymorphism, but these have to be assigned dynamically and then be accessible as a property of the class.
Ideas??? Surely c++ can do this, I'm just not sure where to start.
Okay, here is the solution I worked out; haven't tested it yet, but should work close enough to fit my needs using this format
flag.find(filename)
enum { filename, workers, runtime };
class flag {
vector<string> helplist;
public:
int add(int argc, char *argv[], string flag, string value, string description) {
string flagvalue;
flagvalue = value;
helplist.push_back(description);
for (int i; i < argv.length(); i++) {
if (argv[i]==flag) {
flagvalue = argv[i+1];
}
}
}
void showhelp() {
for (int i; i < helplist.length(); i++) {
cout << helplist[i] << endl;
}
}
};
No, you can't do this in C++. In C++, the members of a class are defined 100% at compile time. You cannot add any at runtime. The way to do this in C++ would be to have a member variable that's a map<string,string> that holds the key/value pairs, and then have a function string getVariable(string) that returns the value in the dictionary for that key.

Using boost::program_options with own template class possible?

I'm currently start using boost::program_options for parsing command line options as well as configuration files.
Is it possible to use own template classes as option arguments? That means, something like
#include <iostream>
#include "boost/program_options.hpp"
namespace po = boost::program_options;
template <typename T>
class MyClass
{
private:
T* m_data;
size_t m_size;
public:
MyClass( size_t size) : m_size(size) { m_data = new T[size]; }
~MyClass() { delete[] m_data; }
T get( size_t i ) { return m_data[i]; }
void set( size_t i, T value ) { m_data[i] = value; }
};
int main (int argc, const char * argv[])
{
po::options_description generic("General options");
generic.add_options() ("myclass", po::value< MyClass<int>(2) >(),
"Read MyClass");
return 0;
}
Trying to compile this I get an Semantic Issue (No matching function for call to 'value'). I guess I need to provide some casting to an generalized type but I have no real idea.
Can anybody help?
Thanks
Aeon512
I wouldn't know if boost::program_options allows the use-case you are trying, but the error you are getting is because your are trying to pass an object as a template type to po::value<>. If the size is known at compile-time, you could have the size be passed in as a template parameter.
template< typename T, size_t size >
class MyClass {
T m_data[size];
public:
// ...
};
And then use it like so:
po::value< MyClass<int, 2> >()
You should also look into using Boost.Array instead that I guess fulfills what you are trying to implement.
I would write it like this:
MyClass<int> mine(2);
generic.add_options() ("myclass", po::value(&mine), "Read MyClass");
Then all that needs to be done is to define an input stream operator like this:
std::istream& operator >>(std::istream& source, MyClass& target);
Then Boost Program Options will invoke this stream operator when the myclass option is used, and your object will be automatically populated according to that operator's implementation, rather than having to later call one of the Program Options functions to extract the value.
If you don't prefer the above syntax, something like should work too:
generic.add_options() ("myclass", po::value<MyClass<int> >()->default_value(MyClass<int>(2)), "Read MyClass");
This way you would be creating the instance of your class directly with your desired constructor argument outside of the template part where runtime behavior isn't allowed. I do not prefer this way because it's verbose and you end up needing to call more functions later to convert the value.