What does the prefix in NSLog mean? - objective-c

When I use NSLog, I get output similar to the following:
2012-01-24 17:05:32:860 App[21856:71939] {logging goes here}
I recognize that '2012-01-24 17:05:32:860' is the date, 'App' is the app name, but I have no clue what '[21856:71939]' means. Can someone fill me in on what that is and where it's generated at?
All I'm trying to do is get logging that lines up nicely so it's easy to read, but the '[21856:71939]' varies in digits enough to mess up any alignment attempts. If I knew how the numbers in '[21856:71939]' were generated, I could add spaces as needed to make it line up correctly, but that's my only idea at this point.
Any help would be much appreciated :)

21856 is the process id. 71939 is the thread id.
You can generate this portion of the log on your own using:
[NSString stringWithFormat:#"[%ld,%lx]",
(long) getpid(),
(long) pthread_mach_thread_np(pthread_self())];
Edit 2014-09-23:
At least on the simulator in iOS 8, the second number is now the pthread_threadid_np of the thread.
__uint64_t threadId;
if (pthread_threadid_np(0, &threadId)) {
threadId = pthread_mach_thread_np(pthread_self());
}
[NSString stringWithFormat:#"[%ld,%llu]", (long) getpid(), threadId]

IIRC, the 21856 is the process PID, and the 71939 is some sort of thread identifier.

It's a thread ID, but I don't actually know how they are generated.
you can grab it yourself using this
pthread_mach_thread_np(pthread_self())
but that doesn't answer how you would set it up with correct lining. On the other note, when you're debugging, go to the last tab (Show the log Navigator), double click on Debug App, it'll show up nicely

Related

Strange behavior inside fork block

I have a block which looks like this:
fork
begin
$display("before repeat");
repeat (delay_before_rsp2data) #1ps;
$display("after repeat");
$display("some information");
`ovm_do_on_with("do some stuff");
end
join_none
In almost all cases it works fine, but in one case (that I found), after the `ovm_do_on_with line, it jumps back to the repeat line, and continuing from there. I know this is happening, because what is displayed is:
before repeat
after repeat
some information
[all the displays from the `ovm_do_on_with part]
after repeat
some information
[all the displays from the `ovm_do_on_with part]
I've tried putting the whole 'repeat' line inside a before end block, switching it with a for loop, and a few more combinations like that, but always the same behavior.
Any idea what could be causing this?
It seems that you are executing the fork ... join_none more than one time (probably in loop) and I guess the delay_before_rsp2data is random.
If this is the case, then the after repeat you saw may not be from the same thread as the before repeat.
My suggestion, add some kind of id to debug and track which thread it is from. For example
int id=0;
task my_fork;
fork
automatic int k; // !! must be automatic
begin
id++; k = id;
$display("before repeat, id %d", k);
repeat(delay) #1ps;
$display("after repeat, id %d", k);
`uvm_do_on_with();
end
join_none
endtask
Then you should be able to track the threads and correlate them.
Remember to use automatic variable inside fork join_none so that it's thread has unique id.
Some quick example:
http://www.edaplayground.com/x/4vRd

top command in Mac OS X got truncated

I'm trying to use the "top" command in MacOS X to determine which app is using the resources.
When I do:
top -stats "pid,command"
the command column is truncated, if the process name is too long.
if you look at the activity monitor, the process name is shown properly (with full name) + icon. My questions are:
how to get the full process name?
sometimes the app icon show next to the process name, is there anyway to do the similar thing using objective-c? should I simply navigate to the app contents folder and grab the icns image?
First, if you're trying to get the data programmatically, driving top is almost definitely not what you want to do.
But, to answer your direct questions:
how to get the full process name?
There is no way to control the truncation of commands. You can use the -ncols parameter to set the width of the output for non-interactive output, but that doesn't stop top from truncating if it wants to.
sometimes the app icon show next to the process name, is there anyway to do the similar thing using objective-c? should I simply navigate to the app contents folder and grab the icns image?
No. How would you deal with apps that have multiple .icns files, e.g., for document icons? (Try it with iTunes, for example. If you pick the first .icns, you get the AIFF document icon; if you pick the last, you get the internal-use recent TV shows icon.)
The right way to do it is to get the NSBundle for the application, then do something like this:
NSString *iconFile = [bundle objectForInfoDictionaryKey:#"CFBundleIconFile"];
if (iconFile) {
NSString *iconPath = [bundle pathForResource:iconFile ofType:#"icns"];
// load and display the icon
}
So, how do you actually want to do this, if not by driving top?
Well, what you're asking for is actually not a well-defined thing. OS X has four different notions of task/process/program/application that don't correspond 1-to-1, and that makes life difficult if you want to write a mashup of two programs that use different notions—e.g., top deals in BSD processes, while Activity Monitor deals in OS X applications.
If what you actually want is the same list top uses, it's open source, so you can read it and do the same thing it does.
But the simplest way to get the list of BSD processes is probably the interfaces in libproc.h, in particular proc_listallpids and proc_pidinfo. For example:
int dump_proc_names() {
int buf[16384];
int count = proc_listallpids(&buf, 16384*sizeof(int));
for (int i = 0; i != count; ++i) {
int pid = buf[i];
char path[MAXPATHLEN+1] = {0};
int ret = proc_pidinfo(pid, PROC_PIDPATHINFO, 0,
&path, sizeof(path));
if (ret < 0) {
printf("%d: error %s (%d)\n", pid, strerror(errno), errno);
} else {
printf("%d: %s\n", pid, path);
}
}
}
Obviously in real code you're going to want to allocate the buffer dynamically, return the values instead of just dumping them, get more than just the paths, etc. But this is enough to give you the basic idea. (When you go to get additional information, be aware that you if you ask for any struct, you will get an EPERM error unless you have rights to see every member of that struct. So, don't go asking for PROC_PIDTASKALLINFO if you only want PROC_PIDT_SHORTBSDINFO.
Anyway, since this API deals with BSD processes (and Mach tasks), not applications, it won't directly help you get at the NSBundle you want to provide Activity Monitor-style features.
There is no way to do this that's entirely correct, but you can probably get away with something like this:
NSString *path = processPath;
while (path && ![path isEqualTo:#"/"]) {
NSBundle *bundle = [NSBundle bundleWithPath:path];
if (bundle) {
if ([bundle executablePath != processPath]) return nil;
return bundle;
}
path = [path stringByDeletingLastPathComponent];
}
There are probably alternative ways to do this, each with different tradeoffs. For example, using -[NSWorkspace runningApplications], storing the results in a dictionary mapping the bundle executable path to the bundle, and using that to look up each process is simple, but it only seems to be useful for applications owned by the current user (and probably in the current session). On the other hand, enumerating all bundles on the system, or asking Spotlight, or similar would probably be too slow to do on the fly, but would go out of date if you cached them on first run.
Another option, in place of libproc, is to use libtop.
Unfortunately, Apple doesn't provide it. They do have a libtop implementation, which they use for their top tool, but it's actually embedded in the source to top and not available from outside. You can find the source (at the link above) and embed it into your program the same way top itself does.
Alternatively, both GNU and BSD process utilities have Mac ports (although knowing which name to use with Homebrew/MacPorts/Google search isn't always easy…), so you could build one of those and use it.
However, unless you're trying to write cross-platform software (or already know how to write this code for linux or FreeBSD or whatever), I think that just adds extra complexity.

Quartz Composer Objective C compare previous with current input

I'm trying to build something that will only fire a command once per keyboard input (as opposed to every frame like QC does natively). In order to do so, I'm trying to listen in on the keyboard inputs (via Freeboard) and compare the current input versus a previous version.
What seems to be happening is the previous version is getting wiped every time the patch executes, so my conditional to compare strings is failing every time. Here's some code to make it a bit clearer:
- (BOOL)execute:(id <QCPlugInContext>)context atTime:(NSTimeInterval)time withArguments:(NSDictionary *)arguments
{
self.outputPrevious=previousCharacter;
if ([self.inputCharacter caseInsensitiveCompare:previousCharacter]){
self.outputText=#"SAME";
}
else {
self.outputText=#"CHANGE";
}
previousCharacter = [NSString stringWithString:self.inputCharacter];
[previousCharacter retain];
return YES;
}
where self.outputText is the text that tells me the result of the if, self.outputPrevious is telling me what the previous character input was, and self.inputCharacter is the current keyboard input.
previousCharacter is defined in the header and instantiated in -init, so it shouldn't be being reset every time.
I've tried pretty much everything with this, so if you have any ideas or insights, that would be awesome. Thanks!
Figured it out eventually. Full solution can be found here

Code only works if I NSLog some values - but why?

I'm writing a simple QR code generator (just for fun and to learn some Obj-C), and I'm working on tracing the outline of connected "modules" (i.e. the black squares that make up a QR code). This is in order to have nicer vector output than simply making a bunch of rects for each module.
Long story short, my outline-tracing code works - BUT ONLY if I make sure to call NSLog in a specific place! If I remove the NSLog-call, the code loops! I'm literally doing nothing but logging. And it doesn't matter what I log; I just have to call NSLog or things break.
The tracing algorithm is simple enough: Go clockwise around the shape of connected modules. When you hit a corner, turn right until you're back to following the outline of the shape. Stop when you reach the starting point again. The shape can have two modules that share a corner-point. The tracing-loop will thus hit that point twice. This is expected, and the code handles it correctly - if I call NSLog.
Otherwise, the code will say that a certain point is a corner the first time it sees it, and not a corner the second time, which causes the tracing to loop around. Detecting if something's a corner-point is not dependent on anything except the x and the y coordinates of the point and an array of module objects - but neither the modules nor the array changes while the tracing is going on, so given the same x,y you should always get the same result. And it does – if I call NSLog.
Without NSLog, the coordinates – e.g. (10,9) – is corner on moment, and a moment later (10,9) is suddenly not a identified as a corner. But with an NSLog-call, (10,9) is correctly seen as a corner-point every time.
Again: I change absolutely nothing; I just log something - anything! And suddenly it works. It's like it's saying that 2 == 2 is true or false, unless I tell it to log 2 and 2, in which case 2 == 2 is always true, as it should be.
Here's the flaky code. It's hard to understand out of context, but there's a lot of context, so I hope this is enough. Everything is integers (no fuzzy floating point values).
do { // start going around the shape
// If this isn't here or simply commented out, the code loops.
NSLog(#"foobar"); // doesn't matter what I log - I just need to log something
// Branch: Is current x,y a corner-point? This should
// always return the same result given the same X and Y
// values, but it only does if NSLog is there!
if( [self cornerAtX:x Y:y] ) {
// add the point to the path
[path addPoint:NSMakePoint(x, y)];
// rotate the direction clockwise, until
// the direction is following the edge of the
// the shape again.
do {
dt = dx;
dx = -dy;
dy = dt;
} while( ![self boundaryFromX:x Y:y inDirectionX:dx Y:dy] );
}
// continue along direction
x += dx;
y += dy;
} while( !(sx == x && sy == y) ); // we're back to the start of the shape, so stop
If anyone can tell me why NSLog can make code work (or rather: Why not using NSLog makes working code break), I'd be happy to hear it! I hope someone can make sense of it.
Make sure cornerAtX:Y: always returns something—i.e., that there's no code path that fails to return a value.
Otherwise, it may very well “return” whatever the last function you called returns, in which case calling NSLog (which doesn't return a value, but may ultimately call a function that does) causes it to “return” something different, which may always be something that's considered true.
The compiler should warn you if you fail to return a value from a function or method that you declared as doing so. You should listen to it. Turn on all the warnings you can get away with and fix all of them.
You should also turn on the static analyzer (also included in that post), as it, too, may tell you about this bug, and if it does, it will tell you step-by-step how it's happening.
There's not much to go on here, but I'd guess that it's either an uninitialized variable or some sort of memory stomping. NSLog probably uses both stack and heap memory, so it could affect those.
Have you tried replacing NSLog with some other meaningless operation? If that will also work then I suppose problem is linked to [self cornerAtX: x Y: y].
Another possibility is that the problem is time-related. NSLog takes time to execute, so if QR code is loaded in another thread you can see this kind of behavior.

how to properly debug in xCode and Objective-C

I was wondering if there is an effective way to debug problems in xcode while coding in Objective-C. I create webpages constantly and code in jquery and javascript where you can set various alert boxes in different places in your code to determine if your script is properly executing sections. Can you do something like that in xcode to make sure that your script is executing methods properly and creating variables properly?
Thanks
Use the debugger - that's what it is there for! Set breakpoints by clicking in the grey are next to the line of code you want to break on. When this line of code is going to be excuted, the debugger will kick in and highlight the current place in execution. You can hover the cursor over variables in the IDE to examine their values, view the current call-stack (to see here this code has been called from) and get a list of local variables to help track program state. You can modify variable properties here too which often makes debugging simpler.
Execute code line by line by 'Stepping Over' (cmd+shift+o), which executes the current line, 'Stepping Into' (cmd_shift+i) which steps into the current line of code (if it is a function), or 'Stepping Out' to return back up the call stack.
If you want to stick to 'old-school' printf style debugging, go with NSLoging output to console.
NSLog(#"this text appears");
prints the following to the console:
this text appears
To print some basic variable values:
CGFloat pi = 3.14;
NSString *aFloatString = [NSString stringWithFormat:#"%.2f", pi];
NSLog(#"pi is equal to: %#", aFloatString);
Prints:
pi is equa to: 3.14
Standard c formatters can be used in NSLog i.e %d for int, %.2f for a float to 2 decimal places etc. Use %# for NSString*s.
Remember that NSLog will remain in production code unless you #IFDEF it out of release builds (or something similar), so if you don't want a performance hit, or embarrassing console logs to accompany the app you will want to remove them.
I've been known to litter functions that dump the following to console - and it isn't good:
OUTPUT:
Number of vertices is: 1200
<Requested reduction>
Can I kick it?
....
....
YES. I. CAN!
Number of vertices is: 800
Could have done with removing things like that :|
yes, the debugger can do all the things you want to do (just set some breakpoints - right click where you want them - then build&debug)
You can try writing to the console.
NSLog(#"Some status message here");
NSLog(#"The value of myObject is:%#", myObject);
To view the output of your application, while running with Xcode, click Run->Console and you will see all of the output from your application.