Rust calling C, static const in C code - c

I have used rust-bindgen to generate rust interface code.
Now in the C code you can find this:
extern const struct mps_key_s _mps_key_ARGS_END;
#define MPS_KEY_ARGS_END (&_mps_key_ARGS_END)
Note that in the hole rest of the code _mps_key_ARGS_END does not appear again.
The macro MPS_KEY_ARGS_END gets used regularly amung other simular mps_key_s.
Now the code produced by rust-bindgen is this:
pub static _mps_key_ARGS_END: Struct_mps_key_s;
Now in C code here is a example usage:
extern void _mps_args_set_key(mps_arg_s args[MPS_ARGS_MAX], unsigned i,
mps_key_t key);
_mps_args_set_key(args, 0, MPS_KEY_ARGS_END);
In rust it looks like this:
pub fn _mps_args_set_key(args: [mps_arg_s, ..32u], i: ::libc::c_uint,
key: mps_key_t);
Now I try to call it like this:
_mps_args_set_key(args, 0 as u32, _mps_key_ARGS_END );
But I get a error:
error: mismatched types: expected *const Struct_mps_key_s, found
Struct_mps_key_s (expected *-ptr, found enum Struct_mps_key_s)
I am not a good C programmer, and I dont even understand where these C static even get there values from.
Thanks for your help.
Edit:
Update based on the answer of Chris Morgan.
I added this code (note, I replaced *const mps_key_s with mps_key_t):
pub static MPS_KEY_ARGS_END: mps_key_t = &_mps_key_ARGS_END;
Just for some extra information on why Im using mps_key_t, in C:
typedef const struct mps_key_s *mps_key_t;
In rust:
pub type mps_key_t = *const Struct_mps_key_s;
This seams seam to work better then befor but now Im getting a bad crash:
error: internal compiler error: unexpected failure note: the compiler
hit an unexpected failure path. this is a bug. note: we would
appreciate a bug report:
http://doc.rust-lang.org/complement-bugreport.html note: run with
RUST_BACKTRACE=1 for a backtrace task 'rustc' failed at 'expected
item, found foreign item _mps_key_ARGS_END::_mps_key_ARGS_END
(id=1102)',
/home/rustbuild/src/rust-buildbot/slave/nightly-linux/build/src/libsyntax/ast_map/mod.rs:327

#define MPS_KEY_ARGS_END (&_mps_key_ARGS_END)
The & part indicates that it is taking a pointer to the object, that the type of MPS_KEY_ARGS_END will be mps_key_s const*. In Rust, that is *const mps_key_s (a raw pointer), and can be achieved in the same way as in C, &_mps_key_ARGS_END. You can define MPS_KEY_ARGS_END in a way that you can use conveniently like this:
static MPS_KEY_ARGS_END: *const mps_key_s = &_mps_key_ARGS_END;

Related

VS linker can't find PsGetProcessWow64Process

I am trying to compile one driver in VS, but it shows -
Severity Code Description Project File Line Suppression State
Error LNK2019 unresolved external symbol __imp__PsGetProcessWow64Process#4 referenced in function _GetProcessModule#8 Garhal C:\Users\Raitis\source\repos\GarHal_CSGO\Garhal\memory.obj 1
Quickly enough, I found a place, where this PsGetProcessWow64Process is being used https://prnt.sc/uffavf
But it is defined, and it's even an official ntos.h function. Just pressing F12 on it finds it easily - https://prnt.sc/uffbjg
Screenshot from error list - https://prnt.sc/uffc6t
The problem is that this in undocumented functions and the linker is having a hard time finding where is the function to put a pointer to it in the generated binary, so first include ntifs.h before ntddk.h like this
#include <ntifs.h>
#include <ntddk.h>
it must be before ntddk or you will get weird errors
then add this line :
NTKERNELAPI PVOID PsGetProcessWow64Process(__in PEPROCESS Process);
which is the signature of the function and now you are ready to call that function
another way to get it is using function pointers and resolving it at run time
#include <ntddk.h>
typedef struct _PEB32 {
UCHAR InheritedAddressSpace;
UCHAR ReadImageFileExecOptions;
UCHAR BeingDebugged;
UCHAR Spare;
ULONG Mutant;
ULONG ImageBaseAddress;
ULONG/*PPEB_LDR_DATA32*/ Ldr;
} PEB32, *PPEB32;
typedef PPEB32 (NTAPI * pfn_PsGetProcessWow64Process) (PEPROCESS Process);
pfn_PsGetProcessWow64Process PsGetProcessWow64Process = NULL;
RtlInitUnicodeString (&usFunctionName, L"PsGetProcessWow64Process");
PsGetProcessWow64Process = (pfn_PsGetProcessWow64Process) (SIZE_T)MmGetSystemRoutineAddress (&usFunctionName);
pPEB32 = PsGetProcessWow64Process (pEProcess);

ANTLR4 C Grammar Not Supporting __cdecl?

I am running ANTLR 4.2 and using the canonical C grammar from:
https://github.com/antlr/grammars-v4/tree/master/c
I am doing the following steps: (using batch files from the ANTLR4 book)
antlr C.g4
javac C*.java
grun C compilationUnit -tokens test.c
Where test.c has the following code:
PASSING:
typedef
void
(*EFI_SET_MEM) (
void *Buffer,
UINTN Size,
UINT8 Value
);
FAILING:
error is: line 3:9 no viable alternative at input 'typedefvoid(__cdecl*'
typedef
void
(__cdecl *EFI_SET_MEM) (
void *Buffer,
UINTN Size,
UINT8 Value
);
The only difference is __cdecl. I tried several changes to fix this, e.g.:
functionSpecifier
: ('inline'
| '_Noreturn'
| '__inline__' // GCC extension
| '__cdecl'
| '__stdcall')
| gccAttributeSpecifier
| '__declspec' '(' Identifier ')'
;
...but this is not working. Any ideas on how to fix this problem? Since what I'm doing doesn't care about the calling convention, creating this lexer rule makes the problem go away:
Cdecl
: '__cdecl'
-> skip
;
I still wish I had a real solution.
__cdecl is used in C++ to declare an interface as using the C-calling convention for linkage (explicitly with undecorated names and the like). __cdecl is C++ (and I believe specific to certain compilers on top of that), not C, so the C grammar doesn't specify it.
I'm not sure why your proposed fix isn't working, tho.

Problem with strong type-checking in lint (warning 632)

I'm working to polish some existing C code in order to port it to a new compiler (embedded software, we're switching hardware). So I'm trying to scrub the current code with lint, and I'm stumped by an assignment that lint has decided is a strong-typing violation.
The error I'm getting:
--- Module: GenericFileName.c
GenericFileName.c ... Warning 632: Assignment to strong type
(SubStructureType_T) in context: assignment
The lines of code to which it refers (names changed for readability):
void foo(void)
{
extern const StructureType_T parent;
const SubStructureType_T *localChild;
localChild = parent.child; //<-- lint complains about this assignment
...
}
The relevant parts of StructureType_T:
typedef struct
{
const struct SubStructureType_T *child;
...
}StructureType_T;
And finally, the lint option to enable strong-type checking:
-strong(AcXJcb)
Any insight would be greatly appreciated. I've searched around for help on this but haven't found much. I guess lint is a pretty old tool. Thanks for reading!
Is it const SubStructureType_T, as in foo, or const struct SubStructureType_T as in the typedef? Note that the keyword "struct" only appears in the 2nd definition.
Are they the same?

idt_table undefined! warning when compiling kernel module

I'm trying to use gate_desc *idt_table in a kernel module. The set_trap_gate() function defined in desc.h uses this pointer. In desc.h is also a definition : extern gate_desc idt_table[].
I tried different things:
use idt_table in my module without definition or affectation
affect idt_table with my (valid) idt_table address
I get either an id_table undefined warning during compilation or incomplete type for idt_table.
creating a new var named for instance gate_desc *it = (gate_desc *)#; And copy the set_trap_gate, set_gate, write_idt_entry, pack_gate functions from sched.h to my module file (renaming them, and using it instead of idt_table). This compiles fine but when inserting my module I get an unknown symbol in module (ret -1) error.
(there is no reference in my module to idt_table, and the functions I use from sched do use my variable).
I tried to see where in the files included by sched.h was defined idt_table, but couldn't find it!
Does someone know how I could use, the idt_table pointer from sched.h (affecting it with the corrct address) or create a new pointer?
Theoretically, you could implement a non-init-section set_trap_gate() via:
void set_trap_gate(int n, void *addr)
{
struct { uint16_t lim; struct desc_struct *idt_table; }
__attribute__((packed)) idt;
__asm__ ("sidt %0" : : "m"(idt) : "memory");
_set_gate(idt.idt_table + n, 15, 0, addr);
}
But that'd be CPU-local, i.e. it's not guaranteed to modify any other IDT but the one of the CPU it's running on. Also, it might fall foul of writeprotected memory.
What exactly is it you're trying to achieve ?

How to get function's name from function's pointer in Linux kernel?

How to get function's name from function's pointer in C?
Edit: The real case is: I'm writing a linux kernel module and I'm calling kernel functions. Some of these functions are pointers and I want to inspect the code of that function in the kernel source. But I don't know which function it is pointing to. I thought it could be done because, when the system fails (kernel panic) it prints out in the screen the current callstack with function's names. But, I guess I was wrong... am I?
I'm surprised why everybody says it is not possible. It is possible on Linux for non-static functions.
I know at least two ways to achieve this.
There are GNU functions for backtrace printing: backtrace() and backtrace_symbols() (See man). In your case you don't need backtrace() as you already have function pointer, you just pass it to backtrace_symbols().
Example (working code):
#include <stdio.h>
#include <execinfo.h>
void foo(void) {
printf("foo\n");
}
int main(int argc, char *argv[]) {
void *funptr = &foo;
backtrace_symbols_fd(&funptr, 1, 1);
return 0;
}
Compile with gcc test.c -rdynamic
Output: ./a.out(foo+0x0)[0x8048634]
It gives you binary name, function name, pointer offset from function start and pointer value so you can parse it.
Another way is to use dladdr() (another extension), I guess print_backtrace() uses dladdr(). dladdr() returns Dl_info structure that has function name in dli_sname field. I don't provide code example here but it is obvious - see man dladdr for details.
NB! Both approaches require function to be non-static!
Well, there is one more way - use debug information using libdwarf but it would require unstripped binary and not very easy to do so I don't recommend it.
That's not directly possible without additional assistance.
You could:
maintain a table in your program mapping function pointers to names
examine the executable's symbol table, if it has one.
The latter, however, is hard, and is not portable. The method will depend on the operating system's binary format (ELF, a.out, .exe, etc), and also on any relocation done by the linker.
EDIT: Since you've now explained what your real use case is, the answer is actually not that hard. The kernel symbol table is available in /proc/kallsyms, and there's an API for accessing it:
#include <linux/kallsyms.h>
const char *kallsyms_lookup(unsigned long addr, unsigned long *symbolsize,
unsigned long *ofset, char **modname, char *namebuf)
void print_symbol(const char *fmt, unsigned long addr)
For simple debug purposes the latter will probably do exactly what you need - it takes the address, formats it, and sends it to printk, or you can use printk with the %pF format specifier.
In the Linux kernel, you can use directly "%pF" format of printk !
void *func = &foo;
printk("func: %pF at address: %p\n", func, func);
The following works me on Linux:
printf the address of the function using %p
Then do an nm <program_path> | grep <address> (without the 0x prefix)
It should show you the function name.
It works only if the function in question is in the same program (not in a dynamically linked library or something).
If you can find out the load addresses of the loaded shared libraries, you can subtract the address from the printed number, and use nm on the library to find out the function name.
You can't diectly but you can implement a different approach to this problem if you want. You can make a struct pointer instead pointing to a function as well as a descriptive string you can set to whatever you want.
I also added a debugging posebilety since you problably do not want these vars to be printet forever.
// Define it like this
typedef struct
{
char *dec_text;
#ifdef _DEBUG_FUNC
void (*action)(char);
#endif
} func_Struct;
// Initialize it like this
func_Struct func[3]= {
#ifdef _DEBUG_FUNC
{"my_Set(char input)",&my_Set}};
{"my_Get(char input)",&my_Get}};
{"my_Clr(char input)",&my_Clr}};
#else
{&my_Set}};
{&my_Get}};
{&my_Clr}};
#endif
// And finally you can use it like this
func[0].action( 0x45 );
#ifdef _DEBUG_FUNC
printf("%s",func.dec_text);
#endif
There is no way how to do it in general.
If you compile the corresponding code into a DLL/Shared Library, you should be able to enlist all entry points and compare with the pointer you've got. Haven't tried it yet, but I've got some experience with DLLs/Shared Libs and would expect it to work. This could even be implemented to work cross-plarform.
Someone else mentioned already to compile with debug symbols, then you could try to find a way to analyse these from the running application, similiar to what a debugger would do.
But this is absolutely proprietary and not portable.
If the list of functions that can be pointed to is not too big or if you already suspect of a small group of functions you can print the addresses and compare them to the one used during execution. Ex:
typedef void (*simpleFP)();
typedef struct functionMETA {
simpleFP funcPtr;
char * funcName;
} functionMETA;
void f1() {/*do something*/}
void f2() {/*do something*/}
void f3() {/*do something*/}
int main()
{
void (*funPointer)() = f2; // you ignore this
funPointer(); // this is all you see
printf("f1 %p\n", f1);
printf("f2 %p\n", f2);
printf("f3 %p\n", f3);
printf("%p\n", funPointer);
// if you want to print the name
struct functionMETA arrFuncPtrs[3] = {{f1, "f1"}, {f2, "f2"} , {f3, "f3"}};
int i;
for(i=0; i<3; i++) {
if( funPointer == arrFuncPtrs[i].funcPtr )
printf("function name: %s\n", arrFuncPtrs[i].funcName);
}
}
Output:
f1 0x40051b
f2 0x400521
f3 0x400527
0x400521
function name: f2
This approach will work for static functions too.
Use kallsyms_lookup_name() to find the address of kallsyms_lookup.
Use a function pointer that points to kallsyms_lookup, to call it.
Check out Visual Leak Detector to see how they get their callstack printing working. This assumes you are using Windows, though.
Alnitak's answer is very helpful to me when I was looking for a workaround to print out function's name in kernel module. But there is one thing I want to supplyment, which is that you might want to use %pS instead of %pF to print function's name, becasue %pF not works anymore at some newer verions of kernel, for example 5.10.x.
Not exactly what the question is asking for but after reading the answers here
I though of this solution to a similar problem of mine:
/**
* search methods */
static int starts(const char *str, const char *c);
static int fuzzy(const char *str, const char *c);
int (*search_method)(const char *, const char *);
/* asign the search_method and do other stuff */
[...]
printf("The search method is %s\n", search_method == starts ? "starts" : "fuzzy")
If your program needs this a lot you could define the method names along with a string in an XMacro and use #define X(name, str) ... #undef X in the code to get the corresponding string from the function name.
You can't. The function name isn't attached to the function by the time it's compiled and linked. It's all by memory address at that point, not name.
You wouldn't know how you look like without a reflecting mirror. You'll have to use a reflection-capable language like C#.

Resources