Avoiding messiness with debug stuff in code - iphone

When I write something, half the effort tends to go into adding clear and concise debug output, or functionality that can be enabled/disabled when that something needs debugging.
An example of debug functionality is a downloader class where I can turn on a #define which makes it "pretend" to download the file and simply hand me back the one I have already. That way I can test to see what happens when a user downloads a file, without having to wait for the network to physically grab the file every single time. This is great functionality to have, but the code gets messier with the #ifdefs.
I eventually end up with a bunch of #defines like
// #define DEBUG_FOOMODULE_FOO
// #define DEBUG_BARMODULE_THINGAMAJIG
// ...
which are uncommented for the stuff I want to look at. The code itself turns out something like
- (void)something
{
#ifdef DEBUG_FOOMODULE_FOO
DebugLog(#"something [x = %#]", x);
#endif
// ...
#ifdef DEBUG_FOOMODULE_MOO
// etc
}
This works great for writing / maintaining the code, but it does nothing for the appearance of the code.
How do people write effortless on-the-fly long-term debug "stuff" anyway?
Note: I'm not only talking about NSLogging here... I'm also talking about stuff like the pretend-download above.

I read several libraries before writing my own and saw two approaches: macro + C functions (NSLogger) or macro + Singleton (GTMLogger, Cocoa Lumberjack).
I wrote my naive implementation here using macro + singleton. I do this during runtime:
[Logger singleton].logThreshold = kDebug;
trace(#"hi %#",#"world); // won't show
debug(#"hi %#",#"world);
You could do the same for packages instead log levels. If I want it gone, I change the #defines. Here is the code involved:
#define trace(args...) [[Logger singleton] debugWithLevel:kTrace line:__LINE__ funcName:__PRETTY_FUNCTION__ message:args];
if (level>=logThreshold){
// ...
}
If you want something more sophisticated look into Lumberjack, it has a register class facility to toggle logging for some classes.

Having two functions and then select them appropriately either at run-time or when compiling seems like a clean approach to me. This makes it possible to have one download.c and one download_debug.c file with the same functions except with different implementations. Then link with the appropriate one if you are building with -DDEBUG or not.
Otherwise, using function pointers works as well for run-time selecting functions.
If you insist of having debug code interspersed throughout your functions, you are pretty much setting up yourself for a mess :) But, you can of course break out those snippets into separate functions and then do the above (or make them no-ops as in the DLog example).

For your case, you could have separate logging macros, say MooLog and FooLog, that all conditionally compile based upon separate flags.
#ifdef DEBUG_FOO
# define FooLog(fmt, ...) NSLog((#"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
#else
# define FooLog(...)
#endif
#ifdef DEBUG_MOO
# define MooLog(fmt, ...) NSLog((#"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
#else
# define MooLog(...)
#endif
Your complex logic everywhere now becomes this:
- (void)something
{
// This only gets logged if the "DEBUG_FOO" flag is set.
FooLog(#"something [x = %#]", x);
// This only gets logged if the "DEBUG_MOO" flag is set.
MooLog(#"Something else [y = %#]", y);
}

Related

Speed-critical section in gcc?

I'm already using -O3, so I don't think I can do much better in general, but the generated assembly is still a tight fit for the timing requirements. Is there a way to, for example, tell avr-gcc to keep non-speed-critical code out of a speed-critical section?
if (READY)
{
ACKNOWLEDGE();
SETUP_PART1();
SETUP_PART2();
//start speed-critical section
SYNC_TO_TIMER();
MINIMAL_SPEED_CRITICAL_CODE();
//end speed-critical section
CLEANUP();
}
A tedious reading of the -O3-optimized assembly listing (.lss file) shows that SETUP_PART2(); has been reordered to come between SYNC_TO_TIMER(); and MINIMAL_SPEED_CRITICAL_CODE();. That's a problem because it adds time spent in the speed-critical section that doesn't need to exist.
I don't want to make the critical section itself any longer than it needs to be, so I'm hesitant to relax the optimization. (the same action that causes this problem may also be what makes the final version fit inside the time available) So how can I tell it that "this behavior" needs to stay pure and uncluttered, but still optimize it fully?
I've used inline assembly before, so I'm sure I could figure out again how to communicate between that and C without completely tying up or clobbering registers, etc. But I'd much rather stick with 100% C if I can, and let the compiler figure out how not to run over itself.
Not quite the direct answer that I as looking for, but I found something that works. So it's technically an XY problem, but I'll still take a direct answer to the question as stated.
Here's what I ended up doing:
1. Separate the speed-critical section into its own function, and prevent it from inlining:
void __attribute__((noinline)) _fast_function(uint8_t arg1, uint8_t arg2)
{
//start speed-critical section
SYNC_TO_TIMER();
MINIMAL_SPEED_CRITICAL_CODE(arg1, arg2);
//end speed-critical section
}
void normal_function(void)
{
if (READY)
{
ACKNOWLEDGE();
SETUP_PART1();
SETUP_PART2(); //determines arg1, arg2
_fast_function(arg1, arg2);
CLEANUP();
}
}
That keeps the speed-critical stuff together, and by itself. It also adds some overhead, but that happens OUTSIDE the fast part, where I can afford it.
2. Manually unroll some loops:
The original code was something like this:
uint8_t data[3];
uint8_t byte_num = 3;
while(byte_num)
{
byte_num--;
uint8_t bit_mask = 0b10000000;
while(bit_mask)
{
if(data[byte_num] & bit_mask) WEIRD_OUTPUT_1();
else WEIRD_OUTPUT_0();
bit_mask >>= 1;
}
}
The new code is like this:
#define WEIRD_OUTPUT(byte,bit) \
do \
{ \
if((byte) & (bit)) WEIRD_OUTPUT_1(); \
else WEIRD_OUTPUT_0(); \
} while(0)
uint8_t data[3];
WEIRD_OUTPUT(data[2],0b10000000);
WEIRD_OUTPUT(data[2],0b01000000);
WEIRD_OUTPUT(data[2],0b00100000);
WEIRD_OUTPUT(data[2],0b00010000);
WEIRD_OUTPUT(data[2],0b00001000);
WEIRD_OUTPUT(data[2],0b00000100);
WEIRD_OUTPUT(data[2],0b00000010);
WEIRD_OUTPUT(data[2],0b00000001);
WEIRD_OUTPUT(data[1],0b10000000);
WEIRD_OUTPUT(data[1],0b01000000);
WEIRD_OUTPUT(data[1],0b00100000);
WEIRD_OUTPUT(data[1],0b00010000);
WEIRD_OUTPUT(data[1],0b00001000);
WEIRD_OUTPUT(data[1],0b00000100);
WEIRD_OUTPUT(data[1],0b00000010);
WEIRD_OUTPUT(data[1],0b00000001);
WEIRD_OUTPUT(data[0],0b10000000);
WEIRD_OUTPUT(data[0],0b01000000);
WEIRD_OUTPUT(data[0],0b00100000);
WEIRD_OUTPUT(data[0],0b00010000);
WEIRD_OUTPUT(data[0],0b00001000);
WEIRD_OUTPUT(data[0],0b00000100);
WEIRD_OUTPUT(data[0],0b00000010);
WEIRD_OUTPUT(data[0],0b00000001);
In addition to dropping the loop code itself, this also replaces an array index with a direct access, and a variable with a constant, each of which offers its own speedup.
And it still barely fits in the time available. But it does fit! :)
You can try to use a memory barrier to prevent ordering code across it:
__asm volatile ("" ::: "memory");
The compiler will not move volatile accesses or memory accesses across such a barrier. It might however move other stuff across it like arithmetic that does not involve memory access.
If the compiler is reordering code, that it's a valid compilation w.r.t. the C language standard, which means that you'll have some hard time avoiding it by pure C code hacks.
If you are after speed, then consider writing WEIRD_OUTPUT(data[2],0b10000000); etc. as inline asm, or writing the whole function in assembly. This gives you definite control over the timing (not considering IRQs), whereas the C language standard does not make any statements on program timing whatsoever.

Swift: macro for __attribute__((section))

This is kind of a weird and un-Swift-thonic question, so bear with me.
I want to do in Swift something like the same thing I'm currently doing in Objective-C/C++, so I'll start by describing that.
I have some existing C++ code that defines a macro that, when used in an expression anywhere in the code, will insert an entry into a table in the binary at compile time. In other words, the user writes something like this:
#include "magic.h"
void foo(bool b) {
if (b) {
printf("%d\n", MAGIC(xyzzy));
}
}
and thanks to the definition
#define MAGIC(Name) \
[]{ static int __attribute__((used, section("DATA,magical"))) Name; return Name; }()
what actually happens at compile time is that a static variable named xyzzy (modulo name-mangling) is created and allocated into the special magical section of my Mach-O binary, so that running nm -m foo.o to dump the symbols shows something a lot like this:
0000000000000098 (__TEXT,__eh_frame) non-external EH_frame0
0000000000000050 (__TEXT,__cstring) non-external L_.str
0000000000000000 (__TEXT,__text) external __Z3foob
00000000000000b0 (__TEXT,__eh_frame) external __Z3foob.eh
0000000000000040 (__TEXT,__text) non-external __ZZ3foobENK3$_0clEv
00000000000000d8 (__TEXT,__eh_frame) non-external __ZZ3foobENK3$_0clEv.eh
0000000000000054 (__DATA,magical) non-external [no dead strip] __ZZZ3foobENK3$_0clEvE5xyzzy
(undefined) external _printf
Through the magic of getsectbynamefromheader(), I can then load the symbol table for the magical section, scan through it, and find out (by demangling every symbol I find) that at some point in the user's code, he calls MAGIC(xyzzy). Eureka!
I can replicate the whole second half of that workflow just fine in Swift — starting with the getsectbynamefromheader() part. However, the first part has me stumped.
Swift has no preprocessor, so spelling the magic as elegantly as MAGIC(someidentifier) is impossible. I don't want it to be too ugly, though.
As far as I know, Swift has no way to insert symbols into a given section — no equivalent of __attribute__((section)). This is okay, though, since nothing in my plan requires a dedicated section; that part just makes the second half easier.
As far as I know, the only way to get a symbol into the symbol table in Swift is via a local struct definition. Something like this:
func foo(b: Bool) -> Void {
struct Local { static var xyzzy = 0; };
println(Local.xyzzy);
}
That works, but it's a bit of extra typing, and can't be done inline in an expression (not that that'll matter if we can't make a MAGIC macro in Swift anyway), and I'm worried that the Swift compiler might optimize it away.
So, there are three questions here, all about how to make Swift do things that Swift doesn't want to do: Macros, attributes, and creating symbols that are resistant to compiler optimization.
I'm aware of #asmname but I don't think it helps me since I can already deal with demangling on my own.
I'm aware that Swift has "generics", but they seem to be closer to Java generics than to C++ templates; I don't think they can be used as a substitute for macros in this particular case.
I'm aware that the code for the Swift compiler is now open-source; I've skimmed bits of it in vain; but I can't read through all of it looking for tricks that might not even be there.
Here is the answer to your question about preprocessor (and macros).
Swift has no preprocessor, so spelling the magic as elegantly as MAGIC(someidentifier) is impossible. I don't want it to be too ugly, though.
Swift project has a preprocessor (but, AFAIK, it is not distributed with Swift's binary).
From swift-users mailing list:
What are .swift.gyb files?
It’s a preprocessor the Swift
team wrote so that when they needed to build, say, ten nearly-identical
variants of Int, they wouldn’t have to literally copy and paste the same
code ten times. If you open one of those files, you’ll see that they’re
mainly Swift code, but with some lines of code intermixed that are written in Python.
It is not as beautiful as C macros, but, IMHO, is more powerful.
You can see the available commands with ./swift/utils/gyb --help command after cloning the Swift's git repo.
$ swift/utils/gyb --help
usage, etc (TL;DR)...
Example template:
- Hello -
%{
x = 42
def succ(a):
return a+1
}%
I can assure you that ${x} < ${succ(x)}
% if int(y) > 7:
% for i in range(3):
y is greater than seven!
% end
% else:
y is less than or equal to seven
% end
- The End. -
When run with "gyb -Dy=9", the output is
- Hello -
I can assure you that 42 < 43
y is greater than seven!
y is greater than seven!
y is greater than seven!
- The End. -
My example of GYB usage is available on GitHub.Gist.
For more complex examples look for *.swift.gyb files in #apple/swift/stdlib/public/core.

Replace a macro with a different definition in Eclipse?

I'm working on a project which defines globals like this:
// Define an correctly-sized array of pointers to avoid static initialization.
// Use an array of pointers instead of an array of char in case there is some alignment issue.
#define DEFINE_GLOBAL(type, name, ...) \
void * name[(sizeof(type) + sizeof(void *) - 1) / sizeof(void *)];
Which apparently works fine, but causes Eclipse to show every single usage of one of these globals as an error.
I would prefer that it be this:
#define DEFINE_GLOBAL(type, name, ...) \
type name;
But I can't change this file, so is there a way to tell Eclipse to pretend that that's the macro's definition?
If you #define the preferred definition after the initial (unwanted) definition, Eclipse seems to use the most recent definition when it does the dynamic macro expansion.
Thus, if you re-#define the macro in the file you are editing, this may solve your problem.
Granted that this is a kludge and may cause unforeseen problems, it may work for your implementation.

Macro without definition in C

What is the use/applicability of macro function without definition:
#ifndef __SYSCALL
#define __SYSCALL(a, b)
#endif
One can find this macro in Linux system in header file /usr/include/asm/msr.h
I also notice macro of following kind.
#define _M(x) x
And only reason to defined this kind of macro that I can think to make code uniform. like in #define SOMETHING (1 << 0). Is there any other hidden(better) use of this kind of macros?
An answer with example will be very helpful. Also
can someone provide me a text/link to read about this.
One of the most common case of a macro of this form:
#define _M(x) x
is to provide backwards compatibility for compilers that only supported the original K&R dialect of C, that predated the now-ubiquitous ANSI C dialect. In the original K&R dialect of the language, function arguments were not specified when declaring the function. In 1989, ANSI standardized the language and incorporated a number of improvements, including function prototypes that declared the number of type of arguments.
int f(int x, double y); /* ANSI C. K&R compilers would not accept this */
int f(); /* Function declared in the original K&R dialect */
While compilers that support the original K&R dialect of C are rare (or extinct) these days, a lot of software was written when both kinds of compilers needed to be supported, and macros provided an easy way to support both. There are still a lot of headers laying about that provide this backwards compatibility.
To provide backwards compatibility for K&R compilers, many header files have the following:
#if ANSI_PROTOTYPES
# define _P(x) x
#else
# define _P(x) ()
#endif
...
int f _P((int x, double y));
If the ANSI_PROTOTYPES definition has been correctly set (either by the user or by some prior #ifdef logic), then you get the desired behavior:
If ANSI_PROTOTYPES is defined, the definition expands to int f(int x, double y).
If ANSI_PROTOTYPES is not defined, the definition expands to int f()
This is often used with conditional expressions to disable a macro by causing it to be preprocessed to nothing. For example (simplified):
#ifdef DEBUG
#define ASSERT(x) if(!(x)) { abort(); }
#else
#define ASSERT(x) /* nothing */
#endif
Just a follow-up to my question.
I got good answers. but I am also adding some more helpful example where macros without definition are useful, one can find it helpful in future:
(1): Why do I see THROW in a C library?
uses to share header file between C and C++. The macro name is _THROW(x)
#ifdef __cplusplus
#define __THROW(x) throw(x)
#else
#define __THROW(x)
#endif
(2) to eliminate warnings when a function parameter isn't used:
This use is for c++. In C it will cause an error too few arguments But in C++ it works with no error: (codepad linked)
#define UNUSED(x)
int value = 0;
int foo(int UNUSED(value))
{
return 42;
}
int main(){
foo(value);
}
(for this I added c++ tag in my question)
Additionally,
(3): The use of #define _M(x) x is as follows, just to makes code line up uniformly:
/* Signed. */
# define INT8_C(c) c
# define INT16_C(c) c
# define INT32_C(c) c
# if __WORDSIZE == 64
# define INT64_C(c) c ## L
# else
# define INT64_C(c) c ## LL
# endif
the file is: /usr/include/stdint.h
It means that code that uses that macro will conditionally preprocess away to nothing.
As simple examples, consider debug code, logging or assertions.
This is probably a debug macro or an platform macro. For example lets say I have a debugger attached to INT3. I might have this when I'm debugging
#define debug() INT3()
Then to be safe I'll add this to production code (to make sure I took them all out)
#define debug()
This looks like something similar
It could be that in some cases on some systems this code needs to make a call -- for example on a certain CPU architecture or OS. But on your system it is just no-oped.

Best way to add a "forCount" control structure to Objective-C?

Adam Ko has provided a magnificent solution to this question, thanks Adam Ko.
BTW if, like me, you love the c preprocessor (the thing that handles #defines), you may not be aware there is a handy thing in XCode: right click on the body of one of your open source files, go down near the bottom .. "Preprocess". It actually runs the preprocessor, showing you the overall "real deal" of what is going to be compiled. It's great!
This question is a matter of style and code clarity. Consider it similar to questions about subtle naming issues, or the best choice (more readable, more maintainable) among available idioms.
As a matter of course, one uses loops like this:
for(NSUInteger _i=0; _i<20; ++_i)
{
.. do this 20 times ..
}
To be clear, the effect is to to do something N times. (You are not using the index in the body.)
I want to signal clearly for the reader that this is a count-based loop -- ie, the index is irrelevant and algorithmically we are doing something N times.
Hence I want a clean way to do a body N times, with no imperial entanglements or romantic commitments. You could make a macro like this:
#define forCount(N) for(NSUinteger __neverused=0; __neverused<N; ++__neverused)
and that works. Hence,
forCount(20)
{
.. do this 20 times ..
}
However, conceivably the "hidden" variable used there could cause trouble if it collided with something in the future. (Perhaps if you nested the control structure in question, among other problems.)
To be clear efficiency, etc., is not the issue here. There are already a few different control structures (while, do, etc etc) that are actually of course exactly the same thing, but which exist only as a matter of style and to indicate clearly to the reader the intended algorithmic meaning of the code passage in question. "forCount" is another such needed control structure, because "index-irrelevant" count loops are completely basic in any algorithmic programming.
Does anyone know the really, really, REALLY cool solution to this? The #define mentioned is just not satisfying, and you've thrown in a variable name that inevitably someone will step on.
Thanks!
Later...
A couple of people have asked essentially "But why do it?"
Look at the following two code examples:
for ( spaceship = 3; spaceship < 8; ++spaceship )
{
beginWarpEffectForShip( spaceship )
}
forCount( 25 )
{
addARandomComet
}
Of course the effect is utterly and dramatically different for the reader.
After all, there are alresdy numerous (totally identical) control structures in c, where the only difference is style: that is to say, conveying content to the reader.
We all use "non-index-relative" loops ("do something 5 times") every time we touch a keyboard, it's as natural as pie.
So, the #define is an OKish solution, is there a better way to do it? Cheers
You could use blocks for that. For instance,
void forCount(NSUInteger count, void(^block)()) {
for (NSUInteger i = 0; i < count; i++) block();
}
and it could be used like:
forCount(5, ^{
// Do something in the outer loop
forCount(10, ^{
// Do something in the inner loop
});
});
Be warned that if you need to write to variables declared outside the blocks you need to specify the __block storage qualifier.
A better way is to do this to allow nested forCount structure -
#define $_TOKENPASTE(x,y) x##y
#define $$TOKENPASTE(x,y) $_TOKENPASTE(x, y)
#define $itr $$TOKENPASTE($_itr_,__LINE__)
#define forCount(N) for (NSUInteger $itr=0; $itr<N; ++$itr)
Then you can use it like this
forCount(5)
{
forCount(10)
{
printf("Hello, World!\n");
}
}
Edit:
The problem you suggested in your comment can be fixed easily. Simply change the above macro to become
#define $_TOKENPASTE(x,y) x##y
#define $$TOKENPASTE(x,y) $_TOKENPASTE(x, y)
#define UVAR(var) $$TOKENPASTE(var,__LINE__)
#define forCount(N) for (NSUInteger UVAR($itr)=0, UVAR($max)=(NSUInteger)(N); \
UVAR($itr)<UVAR($max); ++UVAR($itr))
What it does is that it reads the value of the expression you give in the parameter of forCount, and use the value to iterate, that way you avoid multiple evaluations.
On possibility would be to use dispatch_apply():
dispatch_apply(25, myQueue, ^(size_t iterationNumber) {
... do stuff ...
});
Note that this supports both concurrent and synchronous execution, depending on whether myQueue is one of the concurrent queues or a serial queue of your own creation.
To be honest, I think you're over addressing a non-issue.
If want to iterate over an entire collection use the Objective-C 2 style iterators, if you only want to iterate a finite number of times just use a standard for loop - the memory space you loose from an otherwise un-used integer is meaningless.
Wrapping such standard approaches up just feels un-necessary and counter-intuitive.
No, there is no cooler solution (not with Apple's GCC version anyways). The level at which C works requires you to explicitly have counters for every task that require counting, and the language defines no way to create new control structures.
Other compilers/versions of GCC have a __COUNTER__ macro that I suppose could somehow be used with preprocessor pasting to create unique identifiers, but I couldn't figure a way to use it to declare identifiers in a useful way.
What's so unclean about declaring a variable in the for and never using it in its body anyways?
FYI You could combine the below code with a define, or write something for the reader to the effect of:
//Assign an integer variable to 0.
int j = 0;
do{
//do something as many times as specified in the while part
}while(++j < 20);
Why not take the name of the variable in the macro? Something like this:
#define forCount(N, name) for(NSUInteger name; name < N; name++)
Then if you wanted to nest your control structures:
forCount(20, i) {
// Do some work.
forCount(100, j) {
// Do more work.
}
}