Saturday, June 7, 2014

Grace Hopper documentary (crowd funding)

I suffer from a little bit of hero worship for Grace Hopper (1906 - 1992).  She is often credited with writing the first compiler in 1952, and was an important contributor to the development of COBOL.

There is a crowd-funded effort to produce a documentary on her:

http://www.indiegogo.com/projects/born-with-curiosity-the-grace-hopper-documentary

I would like to see this documentary succeed because I really would like to know more about her than appears in Wikipedia.

Update: Grace Hopper on Letterman:
    https://www.youtube.com/watch?v=1-vcErOPofQ
She really was charming.

Thursday, June 5, 2014

clang/llvm optimize -O3 understands free()


Wow, I just found an amazing bug, although I'm not "bug" is the right word for it.

I have an object delete function:

void e_del(e_t *e)
{
    if (e == NULL || e->signature != E_SIGNATURE) abort();
    e->signature = 0;
    free(e);
}

I have int signature at the end of the e_t structure, set at object creation to a known value (E_SIGNATURE).  Then, I can check periodically to make sure that a valid object is being used.  This detects a variety of bugs, like writing past the end of a buffer in the e_t structure, or just an invalid pointer.  The setting of signature to zero in e_del() is to detect a double call to e_del() with the same object.

In my unit tests, I coded a double-delete to make sure it worked, but abort didn't get called!  Instead, it double-freed!

Silly me, I must have a stupid error in my logic.  Re-build without optimization to make it easier to set breakpoints and single step.  Works.  Works fine.  Without optimization, my code works.  With optimize level 3, it doesn't.  I generated assembly language for optimize and non-optimize cases, and guess what.  At optimize 3, the zero of signature is gone.  Completely gone.

I had a theory, which I tested by changing free(e) to printf("%p", e) and guess what.  At optimize 3, the zero of signature reappeared.  The code worked as expected.  Change printf back to free, and the zero of signature disappeared again.

Apparently, clang/llvm knows what free() is for.  It knows that only a buggy program would try to access a heap segment after it is freed.  So for any non-buggy (and non-multi-threaded) program, it is safe to throw away the "e->signature = 0" line.   My problem is that I DON'T want to assume a bug-free program.  I want to do a good job of detecting bugs.

How to fix?  A variation on Linux's ACCESS_ONCE macro which I named VOL:

#define VOL(_x, _type) (*(volatile _type *)&(_x))
. . .
VOL(e->signature, int) = 0;
free(e);

This "volatilizes" access to e->signature, forcing the optimizer to leave the operation alone.  (FYI - my reason for making my own macro is that ACCESS_ONCE uses the gcc-specific built-in "typeof()" to remove the need to pass in the data type.  But I didn't want my code to be gcc-specific.)

I've done a lot of multi-threaded programming in my day, most-recently experimenting with lock-free, non-blocking designs, so I've had to worry about the optimizer from time to time.  But this is the first time I've ever had a simple, single-threaded, straight-line code work wrong due to the optimizer.  Think about what this means.  The optimizer knows what free() is for, knows that the freed segment shouldn't be accessed after the free, and makes code generation decisions on that basis.  I wonder what else the optimizer thinks it knows...

UPDATE: in its first posting, mistakenly attributed this issue to gcc.  I forgot that my Mac now uses the clang/llvm compiler.  I tried this with true gcc, and it did NOT omit the clear of signature.

UPDATE2: I changed the assignment of zero to signature to a memset of the whole structure:

void e_del(e_t *e)
{
    if (e == NULL || e->signature != E_SIGNATURE) abort();
    memset(e, 0, sizeof(*e));
    free(e);
}

The compiler did NOT optimize out the memset.  I'm guessing that it thought the memset function might have side effects, which is interesting since memset is a compiler builtin.  In fact, if signature is the only field in e_t, the memset compiles to the exact same instructions as the zero assignment.

UPDATE3: Wow, optimizers are surprising.  I found a case where the memset() IS optimized away.  I tried telling the compiler that e points at volatile memory, and it STILL optimized it away.   I'm back to using VOL() on the individual fields.  Again, this is all clang/llvm on Mac.  I've never seen gcc optimize away code based on knowing what free() does.

Tuesday, June 3, 2014

Easy Familiarity

I was at a software conference a couple weeks ago where I attended some sessions on functional programming.  I, like many imperative programmers, am finding functional a bit foreign and hard to internalize, and I enjoyed listening to some experienced practitioners talk about it.

In one session, the presenter said, "simple is not the same thing as easy."  "Simple" is a characteristic of a thing.  It is simple or it is complex.  A "hello world" program is simple; spaghetti code is complex.  "Easy" relates to an individual.  I find pointer-intensive software to be easy.  Garry Casparov finds chess easy.  The presenter's point was that we should strive to make simple software (complexity is the single greatest enemy to quality).  In his opinion, functional languages can make many programs more simple than in imperative languages.  This, in spite of the fact that many imperative programmers would find the functional program difficult to understand, due to lack of familiarity.

In another session, the presenter said, "readable != familiar".  Same idea, slightly different spin.  When I first learned C, I found conditional expressions to have low readability:
    int max_xy = (x > y) ? x : y;
Almost thirty years later, I don't give it a second thought.  Did it become magically more readable?  No, the construct was always readable.  I became more familiar.  On the other hand, I've had maybe 20 years experience with regular expressions, and they are still virtually a "write-only" language.  Regular expressions fundamentally have low readability.

simple != easy
readable != familiar

Both encourage us to not fear change, to not assume that if X was good enough for my grandfather, then it's good enough for me.  I find it strange that programmers would resist new ways of thinking, new approaches, new language features.  Our profession barely existed 50 years ago, it changes every year.  And yet, in my early years, I knew programmers who resisted C because you couldn't do things that you could do in assembly language.  A few years later, people were doubting that C++ could ever be usable in embedded systems.  (Now Java is being embedded, for goodness sake!)  Personal computer operating systems have progressed from simple program loaders (e.g. MSDOS) to full Unix with virtual memory and symmetric multiprocessor capability.

And still programmers resist the new, the different.  (I'm no better!  I'm still don't consider myself a good OO programmer.  I've done very little C++.)

One guy at the conference went so far as to say (approximately), "If you don't learn functional programming, in 5 years there will be a name for your job: 'maintenance.'"  I'm not sure that's true -- there are still a lot of new non-OO C code being written -- but it gives me pause ... and motivation to learn some more Haskell.

Monday, May 26, 2014

Memorial Day

I'll admit it: I'm inconsistent and possibly even hypocritical about the military.  As a young pup, I toyed with pacifism, but couldn't figure out how to be consistent.  My later teenage years held some fear of being drafted into the Vietnam war.  I've always been uncomfortable with nationalism and jingoism, both of which give patriotism a bad name.

And yet...

Soldiers throughout history have gone to war with the goal of preventing harm to the ones they love and the societies they live in.  I believe that very few soldiers fight out of a sense of pure hatred.  These men and women really have offered their lives up in the service of others.  And while some soldiers have performed terrible acts, most perform their duties to the best of their abilities.

So each memorial day, I wrestle with these conflicting feelings.  But one thing I never feel conflicted about is a deep sense of respect I feel to the men and women who have put their lives in danger, and sorrow at those who have died trying to do the right thing.

I feel this way for soldiers on all sides of every conflict.  As a Jew, I have no respect for Nazism.  But I do feel respect for German soldiers who were fed lies about Jews and made to fight, and I feel sorrow for German soldiers killed.  I'll never forgive the Nazi leaders who knew they were spreading lies; I completely forgive the foot soldiers who thought they were defending their families and society.

So please pause for a moment today and pay your respects to the soldiers of every country throughout history who have given their lives trying to do the right thing.

Monday, May 19, 2014

Fast, lock-free, non-blocking queue

In my copious spare time (insert laugh-track here), I have developed a fairly simple queue that features:
  • Fixed size (size specified at queue creation time).
  • Non-blocking (enqueuing to a full queue returns immediately with status; dequeuing from an empty queue returns immediately with status).
  • Single Producer, Single Consumer (SPSC).
  • No dynamic memory allocates or frees during enqueue and dequeue operations.  Messages are void pointers (null pointers not allowed).
  • High performance.  On my Macbook Air, streaming data through a queue averages 11 ns per message (queue size=32), while ping-pong latency is 69 ns (one-way).
  • Tested on Mac OSX 10.9 (Mavericks) and Linux 2.6 and 3.5 kernels.  At present, I only recommend the 64-bit x86 processor family, due to the fact that I take advantage of its programmer-friendly memory model.  In the future I hope to generalize it to be efficient on other processor types.
I'm making it available as public domain (or more-accurately, as CC0), which means you can use it for any purpose without restriction.

You can get the module and its documentation here: https://github.com/fordsfords/q/tree/gh-pages

In addition to the queue itself, I produced semi-literate internals documentation  I'm rather proud of my semi-literate documentation system.

Sunday, May 18, 2014

Cache Line Size and Alignment

I've been doing some fiddling around with a high-performance queue, and have noticed something.  There is a wide-spread belief that CPU caches have a line size of 64 bytes.

Alas, all the world is not X86.

Modern PowerPC cache line size is 128 bytes.  Same with Itanium-2.  IBM's system Z CPUs have a line size of 256 bytes.

I saw the results of this personally with our Itanium Linux machine.  My queue performed VERY poorly.  I increased the padding between critical fields to assume a 128-byte cache line, and magically the performance improved dramatically.

While I'm on the subject, I heard from a smart person that cache lines do not necessarily align themselves on the corresponding memory boundaries.  I.e. assuming a 64-byte line size and a cache miss, a memory access to address 0 would load a cache line with 0-63.  However, if that access were instead to address 32, it would load a cache line with 32-95.

However, I have not been able to verify this experimentally.  I've tried on X86, SparcV9, and Itanium, and they all appear to align the caches to a multiple of the cache line size.  I.e. an access to address 32 would load 0-63.

If anybody has clarification here, I would appreciate a note.  Thanks.


UPDATE: another colleague of mine has stated categorically that order of access will NOT affect the mapping of cache lines to memory addresses.  That matches my experimental evidence.

Thursday, May 8, 2014

Blank is beautiful

We all  know that we should comment our code.  But it's hard.  We know that obvious comments are pointless, and can even reduce readability by clutter:

    i++;  /* increment i */

You are reasonable to assume that the reader knows the programming language, so don't include those kinds of obvious comments.  But while writing code, you can be a poor judge of what is obvious; it's ALL obvious to you!

But there is one kind of comment that the coder *is* the best judge for: blank lines.

Writing code is a bit like writing prose.  You split your writing into paragraphs, where each paragraph represents a single coherent unit of thought.  Consider this fragment of code adapted from a heap sort algorithm:

    while (end > 0) {
        temp = a[end];
        a[end] = a[0];
        a[0] = temp;
        end--;
        sift_down(a, 0, end);
    }

I see four "units" of thought here.  The first is that we are going to loop until the size of the heap becomes zero.  The second is that we are swapping the head with last leaf of the heap.  The third is that we are removing the last leaf from the heap, and the fourth is sifting down the new top of heap to its proper location.  Four units of thought should be four paragraphs.  But this code doesn't contain any paragraph breaks.  Maybe this example isn't severe, but I've seen screen after screen of code packed together.  It's hard to read because it's hard to *find* the units.

I think this is a big improvement (I didn't include a blank line after the "while" because the indention itself provides a visual break.):

    while (end > 0) {
        temp = a[end];
        a[end] = a[0];
        a[0] = temp;

        end--;

        sift_down(a, 0, end);
    }

The author may not be a good judge of obvious v.s. non-obvious, but at least he knows which groups of lines represent individual units of thought.

So, maybe we're agreed on blank lines.  What about textual comments?  I've seen many people who usually add a comment to each paragraph.  For example:

    /* loop until the size of the heap becomes zero */
    while (end > 0) {
        /* swap head of heap with last leaf */
        temp = a[end];
        a[end] = a[0];
        a[0] = temp;

        end--;  /* Remove that last leaf (the old head) */

        /* re-balance the heap */
        sift_down(a, 0, end);
    }

Better?  Or are the comments unnecessary because the code itself is obvious?  I think "temp=a; a=b; b=temp;" is a common-enough idiom that calling it swap may be unnecessary.  But is it obvious that "a[0]" and "a[end]" represent the head and last leaf nodes of the heap?  Different people may have different opinions.  And what about the third comment?  I think everybody would agree that "end--;  /* decrement end */" would be absurd.  But saying that it removes the last leaf from the heap might be helpful to those unfamiliar with the standard array implementation of an ordered heap.  And the fourth comment?  Would the average programmer know what the "sift_down()" operation is for an ordered heap?  (You DO all know what an ordered heap is, right?)

I have mixed feelings.  As a maintainer, I usually view comments with suspicion since they are often not updated as the code is modified.  But as a coder I try (and often fail) to add comments when the "what" is obvious, but the "why" may not be.  We know what "end--;" does: it decrements "end".  But why are we decrementing it?  Because we are removing the last leaf.

But the "why" question can be asked recursively.  Why are we removing the last leaf?  When do we stop asking "why"?  Here's where judgment comes in, and as I said, the coder is often the worst person to make that judgment call.  Which is why 99% of code is poorly-commented!

I think the value of these particular textual comments is debatable.  The value of the blank lines is not.  In my opinion, the blank lines are the most important comments in the code fragment.


One more point about code paragraphs and their conceptual units of thought: what about making the source one line shorter by moving the "end--" higher-up?

    /* loop until the size of the heap becomes zero */
    while (end > 0) {
        /* swap head of heap with last leaf, and remove it */
        temp = a[end];
        a[end--] = a[0];
        a[0] = temp;

        /* Re-balance the heap */
        sift_down(a, 0, end);
    }

I feel this is bad.  Yes, the code is the same - the post-decrement modifies the right array element.  But this is mixing two conceptual units of thought into one paragraph.  Swapping head and last leaf, followed by removing the last leaf is NOT a single unit of thought; it's two.  If your command has the word "and" in it, please consider breaking the paragraph up.  But even worse is that the order of operatioons described in the comment is not embodied by the code.  The "remove it" is second step, but the code for it is right smack in the middle of the first step.  (Don't worry, modern compilers won't generate less-efficient code if you make end--; a separate line.)

If you really want to compress this code vertically, I would combine the swap onto one source line:

        temp = a[end];  a[end] = a[0];  a[0] = temp;


While I'm at it, PLEASE comment the end brace of functions with the function's name!

    int heap_sort(...)
    {
        ...
    }  /* heap_sort */


And please add TWO blank lines between the end of one function the start of the next.

Monday, April 28, 2014

Cute "sed" Trick: rotate file

I wanted a script that would invoke a process, passing in a port number from a circular pool of ports.  When the process exits and restarts, I want the script to pass in the *next* port from the pool.

    PORT=`head -1 port_file.txt`
    sed -i -e '1h;1d;$G' port_file.txt

In the above "sed" command:

  • The "-i" causes the file "port_file.txt" to be edited in-place.
  • The "1h" sed command yanks the first line into the "hold" space.
  • The "1d" sed command deletes the first line (prevents it from being output).
  • The "$G" command appends the hold space after the last line of the file.

Thus, given that "port_file.txt" contains:
    12000
    12001
    12002
    12003
the above two commands will leave the file with:
    12001
    12002
    12003
    12000
and "PORT" set to 12000.

Monday, April 21, 2014

Old C Coding Habits Die Hard

Old habits die hard.

In their 1978 book "The C Programming Language", Brian Kernighan and Dennis Ritchie described a version of C which has since become known as "K&R" C.  For those of you who aren't older than dirt, K&R C differed in many ways from modern C.  For example:

    foo(c, v)
    int c;
    char **v;
    {

Whoa!  What's that?  Original K&R C didn't let you declare the formal parameter types in-line with the function definition, you had to declare them between the ")" and the "{".  Also, functions defaulted to being of type "int".

Lots of fossilized programmers like me were forced into habits in the old days which have outlived their need.  Now, a lot of younger programmers getting out of school have as their first real-world experience the job of maintaining that old code, learning those same obsolete habits through osmosis.


LOCAL VARIABLES

In K&R C, local variables *had* to be declared at the top of the function.  With C89, locals could be declared at the start of any compound statement (i.e. after any "{").  Finally, as of C99 locals could be declared basically anywhere.

In my opinion, it makes sense for a variable to be declared and initialized immediately before (or very close to) its first usage.  Doing this conveys valuable information for a future code maintainer: this variable isn't used prior to this line.  I can't tell you how often I spent time doing reverse searches for a variable to see where else it is being used.

Here's some "old habits" code:

    foo_find(...)
    {
        int found = 0;
        ...tens of lines...
        while (! found) {

With this, you might go straight to the top of "foo()" to see how "found" is declared and initialized, but then you still have to search the tens of intervening lines to see how "found" might changed.

I prefer this:

    foo_find(...)
    {
        ...tens of lines...
        int found = 0;
        while (! found) {

Sure, there might be a 20-year-old compiler which can't handle it, but anybody using a 20-year-old compiler has bigger problems than this.


GLOBAL VARIABLES

Another habit which I think might be a K&Rism: declaration of global variables at the top of the file. I might be wrong, but I suspect that K&R C disallows global variables to be declared after some functions are defined.  As with local variables, this restriction is no longer in force.  So, if you have a group of functions which implement an abstraction that uses globals, but the abstraction is not significant enough to justify putting them in their own file, I think it makes sense to put the globals associated with the abstraction in front of the first implementation function.  For example:

    #define FOO_MAX_NUM 67
    typedef foo_t struct {...};
    foo_t foo_storage[FOO_MAX_NUM];
    static int foo_num_stored = 0;

    foo_t *foo_create(...)
    {

This code, including the #define, the typedef, and the global variables, may well be positioned after other functions are already defined.  Once again, it helps a code reader know that the definitions are not used in the preceding code.


INCLUDE FILES

In the above example, "FOO_MAX_NUM" and "foo_t" are defined close to the code, instead of at the top of the file.  But many programmers wouldn't even put them at the top of the file, they would put them in an include file "foo.h".

I don't think this is a K&Rism.  It's just a habit to put all typedefs and #defines in the include file.  But again, I advocate for keeping things as localized as possible.  Definitions and declarations which are internal implementation details to an abstraction should be hidden from general view.  C++ may do a better job of managing the external and internal details of an abstraction, but the guidelines should be followed in C as well.

Wednesday, April 16, 2014

strtol preferred over atoi

We've all done it: parsed command-line parameters and converting numeric strings to integers using "atoi()".  And (hopefully) we've all felt guilty about it, because "atoi()" sucks.

Let's say I have a program, "blunjo", which takes a "-d" option with numeric debug level (0=no debug, 1=a little debug, 2=a lot of debug).  So I might use it like this:

    blunjo -d 1 input_file1 input_file2 ...

Inside the code I probably call "getopt()" and include the code fragment:

    case 'd':
        debug_opt = atoi(optarg);
        break;

So, what happens if the user forgets exactly how to use it and enters this:

    blunjo -d input_file1 input_file2 ...

In this case, "optarg" points at "input_file1", which "atoi()" happily converts to zero, turns off debug, and silently skips processing "input_file1".  Might be nice if it actually told the user that "input_file1" is an invalid integer and printed the usage string.

Enter "strtol()".  It's a little more complicated to use (also more flexible):

    long int strtol(const char *nptr, char **endptr, int base);

The Linux man page contains two interesting bits:

If endptr is not NULL, strtol() stores the address of the first invalid character in *endptr. If there were no digits at all, strtol() stores the original value of nptr in *endptr (and returns 0). In particular, if *nptr is not '\0' but **endptr is '\0' on return, the entire string is valid.

... the calling  program  should  set  errno to 0 before the call, and then determine if an error occurred by checking whether errno has a non-zero value after the call.

So this is better code:

    case 'd':
        char *p = NULL;  errno = 0;
        debug_opt = strtol(optarg, &p, 10);
        if (errno != 0 || p == optarg || p == NULL || *p != '\0') {
            usage("Invalid numeric value for -d option"); }
Note that you must make sure that "optarg" is non-null before calling strtol.  If you use getopt and specify "d:" then getopt will guarantee a non-null "optarg".  But if you are parsing the command-line string yourself, beware of the user entering "-d" with nothing at all following it - the next "argv[]" will be null.  Also note that the "p==NULL" check is technically not necessary; so long as "optarg" is non-null, "p" will never be left at null.  However, given that I'm not responsible for the code that sets "p", it just seems like good practice to include the sanity check before dereferencing it.

Here's a macro to make it all even easier, handle 0x-prefixed hexidecimal, and even prints a programmer-friendly error specifying the file:line of the call to it:

    #define SAFE_ATOL(a,l) do { \
      char *in_a = a; char *temp = NULL; long result; errno = 0; \
      if (*in_a == '0' && *(in_a+1) == 'x') \
        result = strtol(in_a+2, &temp, 16); \
      else \
        result = strtol(in_a, &temp, 10); \
      if (errno!=0 || temp==in_a || temp==NULL || *temp!='\0') { \
        fprintf(stderr, "%s:%d, Error, invalid numeric value for %s: '%s'\n", \
           __FILE__, __LINE__, #l, in_a); \
        exit(1); \
      } \
      l = result; /* "return" value of macro */ \
    } while (0)
Here's a usage of the macro:

    case 'd':

        SAFE_ATOL(optarg, debug_opt);
Note that on errors, it abruptly exits the program.

Finally, there is also "strtoll()" which returns a long long int, and has the same error-checking.  The functions "strtoul()" and "strtoull()" are similar but for unsigned.

EDIT: I'm pleased to discover that the function "inet_pton()" does a good job of error checking a dotted-decimal IP address.  For example, adding garbage to the end of a valid IP address is flagged as an error.

EDIT2: I've enhanced the above macro in a few ways and put it on my github. See: https://github.com/fordsfords/safe_atoi

Monday, April 14, 2014

Password strength

I disagree with a lot of "password strength" measures.  Most measures want you to include upper and lower case, digits, special characters, etc.  I don't feel they are necessary, and don't give you as much "security" as you might think (like substituting zero for the letter "o").

Then along came Randall Munroe with an XKCD cartoon which does a much better job of explaining it than I ever could:

Password Strength


Most of the password strength "meters" that you see on sites are based on the idea that digits, special characters, and mixed-case are the magic elixir for strong passwords.  I was quite dismayed to discover that most of them consider "P@ssw0rd" to be very secure, which is absurd.  Then I found zxcvbn:


Finally, a password strength meter which knows that "P@ssw0rd" is low security (score=0 of 4, crack time 0 seconds)!  Whereas "correcthorsebatterystaple" is very secure (score=4 of 4, crack time 65 years).

Another password method that I've heard hyped which I disagree with is the haystack approach.  According to this author, the password "D0g....................." (21 dots) is very strong.  This is ONLY true for brute-force password cracking, which is NOT how serious crackers work.  They do dictionary and repeated character analysis.  According to zxcvbn, "D0g....................." is weak (score=0, crack time 84 seconds).  YES!

One fly in all this ointment: many systems limit your password length, sometimes to as few as 8 characters.  This makes it very hard to use 4 random words, meaning that you probably need to go the random route.  For the 8 random character password "0ZhyUQ63", zxcvbn rates it 4 of 4, with centuries required to crack it.  Whereas "saytroll" is weak, with 22-second crack time.  (Note that "S@yTr0ll" is still weak, with a 7-minute crack time - so much for magic elixirs.)

BTW, my wiki has a somewhat longer article on password strength.

Monday, March 17, 2014

Environment for Cron Jobs

I never remember the environment variables that are set for "cron" jobs?  So I created a cron job on each of our platforms with the "set" command.

Unfortunately, this post is of limited usefulness.  Your system administrator can override the defaults, which would make my findings inaccurate for you.  And it is possible that some of the variables shown below already represent our local administrator's overrides.  Also, different versions of the OSes and of Bash will affect the symbols.  But it's a start.  :-)

I've highlighted the PATH since that is my most-often desired information.

Solaris

HOME=(account home dir)
IFS= 
LOGNAME=(account name)
MAILCHECK=600
OPTIND=1
PATH=/usr/bin:
SHELL=(account login shell)
TZ=(system timezone)

HP-UX

ERRNO=10
FCEDIT=/usr/bin/ed
HOME=(account home dir)
IFS=' 
'
LINENO=36
LOGNAME=(account name)
MAILCHECK=600
OLDPWD=(account home dir)
OPTARG
OPTIND=1
PATH=/usr/bin:/usr/sbin:.
PPID=(parent process ID)
PS2='> '
PS3='#? '
PS4='+ '
PWD=(account home dir)
RANDOM=(some random number)
SECONDS=0
SHELL=(account login shell)
TMOUT=0
TZ=(system timezone)
_=';'

I'm surprised to see "." in PATH.  I've always been taught that having "." in your path is dangerous, although most of the danger comes from having it early in your path (if you are "cd"ed into somebody else's directory, they might have an executable named "ls" which does an "rm -rf $HOME").

Linux

BASH=/bin/sh
BASHOPTS=cmdhist:extquote:force_fignore:hostcomplete:interactive_comments:progcomp:promptvars:sourcepath
BASH_ALIASES=()
BASH_ARGC=()
BASH_ARGV=()
BASH_CMDS=()
BASH_LINENO=([0]="0")
BASH_SOURCE=([0]="(command)")
BASH_VERSINFO=([0]="4" [1]="1" [2]="2" [3]="1" [4]="release" [5]="x86_64-redhat-linux-gnu")
BASH_VERSION='4.1.2(1)-release'
DIRSTACK=()
EUID=(account effective UID)
GROUPS=()
HOME=(account home dir)
HOSTNAME=(system host name)
HOSTTYPE=x86_64
IFS=' 
'
LOGNAME=(account name)
MACHTYPE=x86_64-redhat-linux-gnu
OLDPWD=(account home dir)
OPTERR=1
OPTIND=1
OSTYPE=linux-gnu
PATH=/usr/bin:/bin
PIPESTATUS=([0]="0")
POSIXLY_CORRECT=y
PPID=(parent process ID)
PS4='+ '
PWD=(account home dir)
SHELL=(account login shell)
SHELLOPTS=braceexpand:hashall:interactive-comments:posix
SHLVL=2
TERM=dumb
UID=(account UID)
USER=(account name)
_=

I suspect if a different login shell were chosen, that a lot of symbols, expecially "BASH_*", would not be there.

AIX

AUTHSTATE=compat
ERRNO=10
FCEDIT=/usr/bin/ed
HOME=(account home dir)
IFS=' 
'
LANG=en_US
LC__FASTMSG=true
LINENO=36
LOCPATH=/usr/lib/nls/loc
LOGIN=(account name)
LOGNAME=(account name)
MAILCHECK=600
NLSPATH=/usr/lib/nls/msg/%L/%N:/usr/lib/nls/msg/%L/%N.cat
ODMDIR=/etc/objrepos
OLDPWD=(account home dir)
OPTIND=1
PATH=/usr/bin:/etc:/usr/sbin:/usr/ucb:/usr/bin/X11:/sbin:/usr/java14/jre/bin:/usr/java14/bin
PPID=(parent process ID)
PS2='> '
PS3='#? '
PS4='+ '
PWD=(account home dir)
RANDOM=(some random number)
SECONDS=0
SHELL=/bin/bash
TERM=dumb
TMOUT=0
TZ=(system timezone)
USER=(account name)
_=';'

At first, I thought that the PATH was being loaded from a .bashrc or something, but the PATH shown does not match the account's .bashrc, .profile, etc.  I wonder if perhaps the system admin overrode the default.

FreeBSD

HOME=(account home dir)
IFS=' 
'
LOGNAME=(account name)
OPTIND=1
PATH=/usr/bin:/bin
PPID=(parent process ID)
PS1='$ '
PS2='> '
PS4='+ '
SHELL=(account login shell)
USER=(account name)

MacOS

BASH=/bin/sh
BASH_ARGC=()
BASH_ARGV=()
BASH_EXECUTION_STRING=
BASH_LINENO=()
BASH_SOURCE=()
BASH_VERSINFO=([0]="3" [1]="2" [2]="48" [3]="1" [4]="release" [5]="x86_64-apple-darwin10.0")
BASH_VERSION='3.2.48(1)-release'
DIRSTACK=()
EUID=(account effective UID)
GROUPS=()
HOME=(account home dir)
HOSTNAME=(system host name)
HOSTTYPE=x86_64
IFS=' 
'
LOGNAME=(account name)
MACHTYPE=x86_64-apple-darwin10.0
OPTERR=1
OPTIND=1
OSTYPE=darwin10.0
PATH=/usr/bin:/bin
POSIXLY_CORRECT=y
PPID=(parent process ID)
PS4='+ '
PWD=(account home dir)
SHELL=(account login shell)
SHELLOPTS=braceexpand:hashall:interactive-comments:posix
SHLVL=1
TERM=dumb
UID=(account UID)
USER=(account name)
_=/bin/sh

I suspect if a different login shell were chosen, that a lot of symbols, expecially "BASH_*", would not be there.

Wednesday, February 19, 2014

Type "n" for Safety! or Strncpy() Considered Risky

Everybody knows that "strncpy()" is the "safe" version of "strcpy()", right?  No chance of going past the destination buffer, right?

Um ...

Here's a nice code fragment I found in some old code (names changed to protect the innocent):

    char foo[MAX_LINE_LEN] = "";
    ...
        case 'F':
            strncpy(foo, optarg, sizeof(foo));
            foo_str = foo;
            foo_len = strlen(foo);

The "n" in "strncpy()" makes sure that if the "optarg" is longer than "foo", it only copies "MAX_LINE_LEN" characters.  No buffer overrun.  Nice and safe, right?

But look at what the man page for "strncpy()" says:
Warning:  If there is no null byte among the first n bytes of src, the string placed in dest will not be null-terminated.
If optarg has "MAX_LINE_LEN" or more non-null characters, "foo" ends up without a null termination!  What happens to the "strlen(foo)"?  It runs right off the end and sooner or later will almost certainly result in a seg fault.  (I heard from a co-worker that we had to fix a lot of instances of this same bug in our code base.)

---

You could fix this bug by adding one line below the "strncpy()":
            foo[sizeof(foo)-1] = '\0';
But I don't like this either.  It leaves intact a different objection I have with the original code: it silently truncates something that the user might not want truncated.  Good tools should not silently do anything different than what the user requested.

So, how about this:
        case 'F':
            foo[sizeof(foo)-1] = '\0';
            strncpy(foo, optarg, sizeof(foo));
            if (foo[sizeof(foo)-1] != '\0') {
                fprintf(stderr, "Warning message!");
                foo[sizeof(foo)-1] = '\0';
            }
GAH!  I've seen code like this and I don't like it.  That code is non-obvious.

Here's a tip for writing good code.  How would you verbally describe the basic high-level approach to somebody?  Would you say:
First set a null at the end of the buffer.  We do this because we want to find out if the strncpy function truncates the string.  If so, then that null will be overwritten with the last character copied.  So we after copying, we check that last character; if the null was overwritten, then we warn the user that it was truncated, and then we add the final null (thus truncating it even further).
No, you wouldn't.  You would say something more like:
If the string fits, copy it.  If it doesn't, warn the user and copy in as much as fits, and null-terminate it.
How about this:
        case 'F':
            if (strlen(optarg) < sizeof(foo))
                strcpy(foo, optarg);
            else {
                fprintf(stderr, "Warning message!");
                memcpy(foo, optarg, sizeof(foo)-1);
                foo[sizeof(foo)-1] = '\0';
            }
            ...

I like this better; it flows almost exactly as the description does.

And yes, there is an irrational part of me that wants to use "strncpy()" inside the "if" statement, even though it isn't needed.  You're just "supposed to".  But "strcpy()" IS more efficient, and it is possible to go overboard with the whole "belt and braces" thing.  However, I would not object to somebody using "strncpy()" there.

I guess the moral of the story is: just because the function has an "n" in it doesn't mean that people are going to use it safely.

Friday, February 7, 2014

Configure a Cron Job with a Wiki

I have some periodic cron jobs that need extra configuration.  For example, one of them generates a report on bug statistics on a code branch basis.  So I need to tell it which code branches to process.  I could just put the list of branch tags on the command line of the report generator, and just use "crontab -e" while logged in to modify it.  However, I want anybody to be able to maintain the list, without having to know my password or the syntax for crontab.

It turns out that we installed Mediawiki locally for our own internal wiki.  So I created a wiki page with a table listing the code branches that are active.  Then I wrote a script which uses "curl" to fetch that wiki page and parse out the branches.  This gives me a nice web-based GUI interface to the tool that everybody is already familiar with.  Everybody here knows how to use Wikipedia, so anybody can go in and change the list of branches.

After doing some additional development, I wanted to be able to include additional configuration for the cron job which I didn't particularly want displayed on the wiki page.  You can use <!--HTML-style comments--> with Mediawiki and it won't display it on the page.  Unfortunately, it completely withholds the comment from the html of the page.  I.e. you can't see it even if you display source of the page.  You only see the comment when you edit the page.

So here's what I ended up with:

#!/bin/sh
# all.sh
# Generate QA report for all active releases.  Runs via cron nightly.

date
# Read wiki page and select rows in the release table ("|" in col 1).
# Uses "action=edit" so that are included (for option processing).
curl 'http://localwiki/index.php?title=page_title&action=edit' | egrep "^\|" >all.list

# read the contents of all.list, line at a time.  Each line is an entry in the table of active releases.
while read ILINE; do :
    # Extract target milestone (link text of web-based report page).
    TARGET_MILESTONE=`echo "$ILINE" | sed -n 's/^.*_report.html \(.*\)\].*$/\1/p'`
    # Extract the (optional) set of command-line options.
    OPTS=`echo "$ILINE" | sed -n 's/^.*--OPTS:\([^:]*\):.*$/\1/p'`

    eval ./qa_report $OPTS \"$TARGET_MILESTONE\" 2>&1
done <all.list

The "sed" commands use "-n" to suppress printing of lines to stdout.  Adding a "p" suffix to the end of a sed command forces a print, if the command is successful.  So, for example, the line:
    OPTS=`echo "$ILINE" | sed -n 's/^.*--OPTS:\([^:]*\):.*$/\1/p'`
If the contents of $ILINE does not contain match the pattern (i.e. does not have an option string), the "s" command is not successful and therefore doesn't print, leaving OPTS empty.

One final interesting note: the use of "eval" to run the qa_report.sh script.  Why couldn't you just use this?
    ./qa_report $OPTS "$TARGET_MILESTONE" 2>&1

Let's say that $TARGET_MILESTONE is "milestone" and the contents of $OPT is:
    -a "b c" -d "e f"
If you omit the "eval", you would expect the resulting command line to be:
    ./qa_report -a "b c" -d "e f" "milestone" 2>&1
I.e. the qa_report tool will see "b c" as the value for the "-a" option, and "e f" as the value for the "-d" option.  But the shell doesn't work this way.  The line:
    ./qa_report $OPTS \"$TARGET_MILESTONE\" 2>&1
will expand $OPTS, but it won't group "b c" as a single entity for -a.  Without "eval", the "-a" option will only see the two-character value "b (with the quote mark).  I found a good explanation for this; the short version is that the shell does quote processing before it does symbol expansion.  So essentially, the thing you need to do is have the shell parse the command line twice.

The "eval" form of the command works like this:
    eval ./qa_report $OPTS \"$TARGET_MILESTONE\" 2>&1
First the shell looks at this command line and parses it with "eval" as the command and the rest as "eval"s parameters.  It does the symbol substitution.  Thus, the thing that gets passed to "eval" is:
    ./qa_report -a "b c" -d "e f" "milestone"
What does the eval command do with that?  It passes it to the shell for parsing!  In this pass, "./qa_report" is the command, and the rest are the parameters.  Since the shell is parsing it from scratch, it will group "b c" as a single entity, letting the "-a" option pick it up as a single string.

Monday, February 3, 2014

Syns, Syn Cookies, TCP Listen Backlog: More Complicated than You Think


No, syncookies don't have anything to do with dieting.  But they did come up as I learned that the TCP listen backlog is more complicated than I thought.  This article should help those of you trying to support TCP servers with lots of clients, especially if large numbers of clients can try to connect at the same time.  (For example, a popular web server.)  This is Linux-oriented; I'm not sure how applicable the info is for other OSes.

---

Here is an article which talks about the TCP listen backlog. Here are some quotes:
    The backlog has an effect on the maximum rate at which a server can accept new TCP connections on a socket. ... Many systems (particularly BSD-derived or influenced) silently truncate this value (the backlog parameter to the listen() system call) to 5 — version 1.2.13 of the Linux kernel [really old - SF] does this ... Using small values for the listen backlog was one of the major causes of poor web server performance with many operating systems up until recently. ... The backlog parameter is silently truncated to SOMAXCONN ... defined as 128 in /usr/src/linux/socket.h for 2.x kernels.
---

Here is a brilliant writeup that taught me about "syncookies", and how they can lead to hung clients. Basically, if the listen backlog (a.k.a. the SYN queue) fills up and more client connection requests (SYNs) come in, the server will *act* like it is accepting them by responding with syncookies. But the kernel won't actually set up state for those connections or inform the app of the new connection. Instead, the server waits for the client to respond with the ACK (the third step of the 3-way handshake). That ACK contains enough information for the server to reconstruct the initial SYN, and the kernel proceeds to open the connection as normal. HOWEVER, if the client's ACK gets lost in the switch or the NIC or whatever, then the client will be left thinking the connection was accepted and is ready, and the server will have no memory of it.

This leads to a genuine hang if the application protocol depends on the server sending the first message, like SMTP or MySQL. In these cases, the client app will hang forever waiting for the server to send its message.

---

Here is an article which gives advice on how to set up systems that can accept lots of TCP connections. Here's a quote:
    Three system configuration parameters must be set to support a large number of open files and TCP connections with large bursts of messages. Changes can be made using the /etc/rc.d/rc.local or /etc/sysctl.conf script to preserve changes after reboot. In either case, you can write values directly into these files (e.g. "echo 32832 > /proc/sys/fs/file-max").
    • /proc/sys/fs/file-max: The maximum number of concurrently open files. We recommend a limit of at least 32,832.
    • /proc/sys/net/ipv4/tcp_max_syn_backlog: Maximum number of remembered connection requests, which are still did not receive an acknowledgment from connecting client. The default value is 1024 for systems with more than 128Mb of memory, and 128 for low memory machines. If server suffers of overload, try to increase this number.
    • /proc/sys/net/core/somaxconn: Limit of socket listen() backlog, known in userspace as SOMAXCONN. Defaults to 128. The value should be raised substantially to support bursts of request. For example, to support a burst of 1024 requests, set somaxconn to 1024.
Here are some commands I entered on our host Saturn:

   sford@Saturn$ cat /proc/sys/net/core/somaxconn
   128
   sford@Saturn$ cat /proc/sys/net/ipv4/tcp_max_syn_backlog
   2048
   sford@Saturn$ cat /proc/sys/fs/file-max
   3263962
   sford@Saturn$

Looks like the main thing we need to do is increase somaxconn, and maybe tcp_max_syn_backlog as well.

---

One small concern. I saw various references to SOMAXCONN as being a constant in a system include file. It apparently lives in different places, depending on the OS flavor/version; I found it here:

   sford@Saturn$ find /usr/include | xargs egrep SOMAXCONN
   /usr/include/bits/socket.h:#define SOMAXCONN 128

So now the question becomes, if we update the tuning parameter, do we also have to modify the include file? My gut says no. I'm thinking that maybe if you built the kernel from source, you would perhaps change the default via that include, but on a running system you simply override that default and you can magically use larger numbers in the listen() call.