What does "global" mean in certain gem5 DPRINTF log messages where I expect a SimObject name instead? - gem5

While debugging a problem with --debug-flag Cache, I noticed that this printf:
bool
MSHR::handleSnoop(PacketPtr pkt, Counter _order)
{
DPRINTF(Cache, "%s for %s\n", __func__, pkt->print());
prints as:
7306617000: Cache: global: handleSnoop for WriteReq [80a70800:80a70803] UC D=110e0000
which was a bit confusing since most DPRINTF lines have the full path to a simobject as in the system.cpu5.dcache for:
7306617000: Cache: system.cpu5.dcache: sendWriteQueuePacket: write WriteReq [80a70800:80a70803] UC D=110e0000
What does this global mean?
Tested in gem5 3ca404da175a66e0b958165ad75eb5f54cb5e772.

global just means that the DPRINTF is being called from neither a SimObject, nor from a class that does implements the name() method.
By expanding the definition of DPRINTF we see that it calls name():
#define DPRINTF(x, ...) do { \
using namespace Debug; \
if (DTRACE(x)) { \
Trace::getDebugLogger()->dprintf_flag( \
curTick(), name(), #x, __VA_ARGS__); \
} \
} while (0)
and name() is defined on the SimObject base class:
virtual const std::string name() const { return params()->name; }
However, if a class does not derive from SimObject nor implement a custom name(), it just resolves to the global name() declared in src/base/trace.hh:
// Return the global context name "global". This function gets called when
// the DPRINTF macros are used in a context without a visible name() function
const std::string &name();
which is implemented as:
const std::string &name()
{
static const std::string default_name("global");
return default_name;
}
So on the above example, MSHR is not a SimObject, but Cache is.

Related

What parameter should I feed to Frida `ObjC.api.class_addMethod()` to make it happy?

I want to use Frida to add a class method to the existing Objective C class on Mac OS. After I read the Frida docs, I tried the following code:
const NSString = ObjC.classes.NSString
function func (n) { console.log(n) }
var nativeCb = new NativeCallback(func, 'void', ['int'])
ObjC.api.class_addMethod(
NSString.handle,
ObjC.selector('onTest:'),
nativeCb,
ObjC.api.method_getTypeEncoding(nativeCb)
)
The above code looks straightforward. However, after the ObjC.api.class_addMethod() call, the attached App and the Frida REPL both froze, it looks that the pointers are not right.
I have tried many possible parameter values for a whole night but still can figure the problem out. What's wrong with my code?
Only two issues:
method_getTypeEncoding() can only be called on a Method, which the NativeCallback is not. You could pass it the handle of an existing Objective-C method that has the same signature as the one you're adding, or use Memory.allocUtf8String() to specify your own signature from scratch.
Objective-C methods, at the C ABI level, have two implicit arguments preceding the method's arguments. These are:
self: The class/instance the method is being invoked on.
_cmd: The selector.
Here's a complete example in TypeScript:
const { NSAutoreleasePool, NSString } = ObjC.classes;
const onTest = new NativeCallback(onTestImpl, "void", ["pointer", "pointer", "int"]);
function onTestImpl(selfHandle: NativePointer, cmd: NativePointer, n: number): void {
const self = new ObjC.Object(selfHandle);
console.log(`-[NSString onTestImpl]\n\tself="${self.toString()}"\n\tn=${n}`);
}
function register(): void {
ObjC.api.class_addMethod(
NSString,
ObjC.selector("onTest:"),
onTest,
Memory.allocUtf8String("v#:i"));
}
function test(): void {
const pool = NSAutoreleasePool.alloc().init();
try {
const s = NSString.stringWithUTF8String_(Memory.allocUtf8String("yo"));
s.onTest_(42);
} finally {
pool.release();
}
}
function exposeToRepl(): void {
const g = global as any;
g.register = register;
g.test = test;
}
exposeToRepl();
You can paste it into https://github.com/oleavr/frida-agent-example, and then with one terminal running npm run watch you can load it into a running app using the REPL: frida -n Telegram -l _agent.js. From the REPL you can then call register() to plug in the new method, and test() to take it for a spin.

Macros with return value

I'm trying to reproduce this pattern in Swift
#define mustBeKindOfClassFailedReturn(object, objectClass, ret) \
if(![object isKindOfClass:objectClass]) { \
NSLog(([NSString stringWithFormat:#"%# must be kind of %# class, current class is %#", object, NSStringFromClass(objectClass), NSStringFromClass([object class])])) \
return ret; }
used like this
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView
layout:(UICollectionViewLayout*)collectionViewLayout
insetForSectionAtIndex:(NSInteger)section {
mustNotBeNilFailedReturn(self.adapter, UIEdgeInsetsZero)
mustBeKindOfClassFailedReturn(self.adapter, [WBCollectionViewSectionAdapter class], UIEdgeInsetsZero)
Does anyone know a good solution to this?
Edit
I know about guard but using guard i have to rewrite a lot of code each time i'll have to override a method in my subclasses for exemple
/**
* mustOverride
*/
#define mustOverride \
{ NSLog(#"You must override this function") }
#define mustOverrideFailedReturn(ret) \
{ mustOverride \
return ret; }
EDIT 2
I've ended with solution is it the optimal one ?
func needOverride(function: String = __FUNCTION__, file: String = __FILE__, line: Int = __LINE__) -> Bool {
REVLogManager.SharedInstance.logErrorMessage("You must override this function", function: function, file: file, line: line, exception: nil, error: nil)
return false
}
func doesObject(function: String = __FUNCTION__, file: String = __FILE__, line: Int = __LINE__, matchingObject: AnyObject!, matchesClass matchingClass: AnyClass) -> Bool {
guard matchingObject.isKindOfClass(matchingClass) else {
let message = "\(matchingObject) must be kind of \(matchingClass) class, current class is \(matchingObject.dynamicType)"
REVLogManager.SharedInstance.logErrorMessage(message, function: function, file: file, line: line, exception: nil, error: nil)
return false
}
return true
}
I'm calling the method like this
public func actualScrollOffsetDistanceWithScrollView(scrollView: UIScrollView!) -> Float {
guard needOverride() else { return 0.0 }
return 0.0
}
And
guard doesObject(matchingObject: self, matchesClass: REVListSectionAdapter.classForCoder()) else { return }
Swift doesn't have a macro capability of this kind.
In terms of accomplishing your goal. The pattern you are following would most correctly be handled using guard statements. A function containing a guard statement must exit the enclosing scope (or trap) and may do so with a return.
Please check the Swift documentation for information about Control Flow and Early Exit control
My answer follows the same legacy pattern using in Swift. You can use classForCoder, but I prefer dynamicType for type checking.
func mustBeKindOfClassFailedReturn(object: AnyObject, objectClass: AnyClass, returnVal: Any?) {
if !object.isKindOfClass(objectClass) {
print("\(object) must be kind of \(objectClass) class, current class is \(object.dynamicType)")
return returnVal
}
return nil // or UIEdgeInsetsZero, or whatever
}
You may also get similar results with !(object is objectClass), but things get tricky when comparing certain number types. See Swift type inference and type checking issue
You can also replace AnyObject and Any with NSObject if you know you're dealing with Objective-C types. From your comment it seems like ret could be a value type, so that's why I make it an Any type.
Swift has a better solution for this kind of problem, the guard statement. In this case, just put this in your method.
guard let adapter = self.adapter as? WBCollectionViewSectionAdapter else {
/* return value if the adapter is not setup properly. */
return .Zero
}
/* continue with valid and correctly classed adapter */
If you're looking for a way to handle this for sub classes, you may want to consider generics. It will allow you implicit type safety without having to rewrite logic in your subclasses.

Accessing a C/C++ structure of callbacks through a DLL's exported function using JNA

I have a vendor supplied .DLL and an online API that I am using to interact with a piece of radio hardware; I am using JNA to access the exported functions through Java (because I don't know C/C++). I can call basic methods and use some API structures successfully, but I am having trouble with the callback structure. I've followed the TutorTutor guide here and also tried Mr. Wall's authoritative guide here, but I haven't been able to formulate the Java side syntax for callbacks set in a structure correctly.
I need to use this exported function:
BOOL __stdcall SetCallbacks(INT32 hDevice,
CONST G39DDC_CALLBACKS *Callbacks, DWORD_PTR UserData);
This function references the C/C++ Structure:
typedef struct{
G39DDC_IF_CALLBACK IFCallback;
//more omitted
} G39DDC_CALLBACKS;
...which according to the API has these Members (Note this is not an exported function):
VOID __stdcall IFCallback(CONST SHORT *Buffer, UINT32 NumberOfSamples,
UINT32 CenterFrequency, WORD Amplitude,
UINT32 ADCSampleRate, DWORD_PTR UserData);
//more omitted
I have a G39DDCAPI.java where I have loaded the DLL library and reproduced the API exported functions in Java, with the help of JNA. Simple calls to that work well.
I also have a G39DDC_CALLBACKS.java where I have implemented the above C/C++ structure in a format works for other API structures. This callback structure is where I am unsure of the syntax:
import java.util.Arrays;
import java.util.List;
import java.nio.ShortBuffer;
import com.sun.jna.Structure;
import com.sun.jna.platform.win32.BaseTSD.DWORD_PTR;
import com.sun.jna.win32.StdCallLibrary.StdCallCallback;
public class G39DDC_CALLBACKS extends Structure {
public G39DDC_IF_CALLBACK IFCallback;
//more omitted
protected List getFieldOrder() {
return Arrays.asList(new String[] {
"IFCallback","DDC1StreamCallback" //more omitted
});
}
public static interface G39DDC_IF_CALLBACK extends StdCallCallback{
public void invoke(ShortBuffer _Buffer,int NumberOfSamples,
int CenterFrequency, short Amplitude,
int ADCSampleRate, DWORD_PTR UserData);
}
}
Edit: I made my arguments more type safe as Technomage suggested. I am still getting a null pointer exception with several attempts to call the callback. Since I'm not sure of my syntax regarding the callback structure above, I can't pinpoint my problem in the main below. Right now the relevant section looks like this:
int NumberOfSamples=65536;//This is usually 65536.
ShortBuffer _Buffer = ShortBuffer.allocate(NumberOfSamples);
int CenterFrequency=10000000;//Specifies center frequency (in Hz) of the useful band
//in received 50 MHz wide snapshot.
short Amplitude=0;//The possible value is 0 to 32767.
int ADCSampleRate=100;//Specifies sample rate of the ADC in Hz.
DWORD_PTR UserData = null;
G39DDC_CALLBACKS callbackStruct= new G39DDC_CALLBACKS();
lib.SetCallbacks(hDevice,callbackStruct,UserData);
//hDevice is a handle for the hardware device used-- works in other uses
//lib is a reference to the library in G39DDCAPI.java-- works in other uses
//The UserData is a big unknown-- I don't know what to do with this variable
//as a DWORD_PTR
callbackStruct.IFCallback.invoke(_Buffer, NumberOfSamples, CenterFrequency,
Amplitude, ADCSampleRate, UserData);
EDIT NO 2:
I have one callback working somewhat, but I don't have control over the buffers. More frustratingly, a single call to invoke the method will result in several runs of the custom callback, usually with multiple output files (results vary drastically from run to run). I don't know if it is because I am not allocating memory correctly on the Java side, because I cannot free the memory on the C/C++ side, or because I have no cue on which to tell Java to access the buffer, etc. Relevant code looks like:
//before this, main method sets library, starts DDCs, initializes some variables...
//API call to start IF
System.out.print("Starting IF... "+lib.StartIF(hDevice, Period)+"\n")
G39DDC_CALLBACKS callbackStructure = new G39DDC_CALLBACKS();
callbackStructure.IFCallback = new G39DDC_IF_CALLBACK(){
#Override
public void invoke(Pointer _Buffer, int NumberOfSamples, int CenterFrequency,
short Amplitude, int ADCSampleRate, DWORD_PTR UserData ) {
//notification
System.out.println("Invoked IFCallback!!");
try {
//ready file and writers
File filePath = new File("/users/user/G39DDC_Scans/");
if (!filePath.exists()){
System.out.println("Making new directory...");
filePath.mkdir();
}
String filename="Scan_"+System.currentTimeMillis();
File fille= new File("/users/user/G39DDC_Scans/"+filename+".txt");
if (!fille.exists()) {
System.out.println("Making new file...");
fille.createNewFile();
}
FileWriter fw = new FileWriter(fille.getAbsoluteFile());
//callback body
short[] deBuff=new short[NumberOfSamples];
int offset=0;
int arraySize=NumberOfSamples;
deBuff=_Buffer.getShortArray(offset,arraySize);
for (int i=0; i<NumberOfSamples; i++){
String str=deBuff[i]+",";
fw.write(str);
}
fw.close();
} catch (IOException e1) {
System.out.println("IOException: "+e1);
}
}
};
lib.SetCallbacks(hDevice, callbackStructure,UserData);
System.out.println("Main, before callback invocation");
callbackStructure.IFCallback.invoke(s_Pointer, NumberOfSamples, CenterFrequency, Amplitude, ADCSampleRate, UserData);
System.out.println("Main, after callback invocation");
//suddenly having trouble stopping DDCs or powering off device; assume it has to do with dll using the functions above
//System.out.println("StopIF: " + lib.StopIF(hDevice));//API function returns boolean value
//System.out.println("StopDDC2: " + lib.StopDDC2( hDevice, Channel));
//System.out.println("StopDDC1: " + lib.StopDDC1( hDevice, Channel ));
//System.out.println("test_finishDevice: " + test_finishDevice( hDevice, lib));
System.out.println("Program Exit");
//END MAIN METHOD
You need to extend StdCallCallback, for one, otherwise you'll likely crash when the native code tries to call the Java code.
Any place you see a Windows type with _PTR, you should use a PointerType - the platform package with JNA includes definitions for DWORD_PTR and friends.
Finally, you can't have a primitive array argument in your G39DDC_IF_CALLBACK. You'll need to use Pointer or an NIO buffer; Pointer.getShortArray() may then be used to extract the short[] by providing the desired length of the array.
EDIT
Yes, you need to initialize your callback field in the callbacks structure before passing it into your native function, otherwise you're just passing a NULL pointer, which will cause complaints on the Java or native side or both.
This is what it takes to create a callback, using an anonymous instance of the declared callback function interface:
myStruct.callbackField = new MyCallback() {
public void invoke(int arg) {
// do your stuff here
}
};

how to write an inline llvm pass

I want to write an llvm pass in order to make inline optimization therefore I call the method getAnalysis() but I have Segmentation fault.. Why? this is the code I am using:
using namespace llvm;
namespace {
struct MyInline : public ModulePass {
static char ID;
MyInline2() : ModulePass(ID) {}
virtual bool runOnModule(Module &M) {
errs() << "Hello2: ";
CallGraph &CG = getAnalysis<CallGraph>();
return false;
}
};
}
char MyInline::ID = 0;
static RegisterPass<MyInline> X("MyInline", "MyInline Pass", false, false);
To use getAnalysis(), you must first override getAnalysisUsage(), presumably to have the necessary analysis data set up for you.
getAnalysisUsage - This function should be overriden by passes that
need analysis information to do their job. If a pass specifies that it
uses a particular analysis result to this function, it can then use
the getAnalysis() function, below.

Repeat the same code in several classes in Objective-C

I have this two functions in my project, that will be identical across several classes.
I cannot create a common base class, since they inherit from different classes (some are UIViewControllers, some are NSObjects, etc.).
I tried with categories, but again, as I don't have a base class, there isn't a single place where to put them. Neither I want the functions to be available in all UIViewControllers, so creating a category there wouldn't help.
How can I add this code to the classes I want without copy & paste?
Just for the record, I'm implementing dynamic log levels in cocoalumberjack, and the code I need to add is the following:
static int ddLogLevel = LOG_LEVEL_WARN;
+ (int)ddLogLevel
{
return ddLogLevel;
}
+ (void)ddSetLogLevel:(int)logLevel
{
ddLogLevel = logLevel;
}
A bit messy perhaps, but you could use a #define. Create a header file with the following in it:
//LoggingCode.h
#define LOGGING_CODE static int ddLogLevel = LOG_LEVEL_WARN; \
\
+ (int)ddLogLevel \
{ \
return ddLogLevel; \
} \
\
+ (void)ddSetLogLevel:(int)logLevel \
{ \
ddLogLevel = logLevel; \
}
Make sure the header file is included whenever you want to use this code, and just insert LOGGING_CODE where you want it.
#include "LoggingCode.h"
LOGGING_CODE
The C preprocessor will do the rest.
Since you can't inherit from a common class, you could make a static class that you would call from both of your other classes.
Edit:
StaticClass.h
+(int)commonddLogLevel;
+(void)commonddSetLogLevel:(int)logLevel;
Class1.h
+(int)ddLogLevel;
+(void)ddSetLogLevel:(int)logLevel;
Class1.m
+(int)ddLogLevel {
[StaticClass commonddLogLevel];
}
+(void)ddSetLogLevel:(int)logLevel {
[StaticClass commonddSetLogLevel:logLevel];
}
Class2.h
+(int)ddLogLevel;
+(void)ddSetLogLevel:(int)logLevel;
Class2.m
+(int)ddLogLevel {
[StaticClass commonddLogLevel];
}
+(void)ddSetLogLevel:(int)logLevel {
[StaticClass commonddSetLogLevel:logLevel];
}