Recently, I had the occasion to play with some features of the amazingly powerful ImageMagick image manipulation tool. After playing with several of the command-line tools and manipulations I decided to look into the API provided through the MagickWand C interface to ImageMagick. To explore some of the features available at this layer I'm attempting to develop a bleed effect on an image; similar to if you had dipped a picture in water and then hung it up to dry. I'm hoping that my free time permits and I can turn this into a small series of posts detailing how I refine this tool (if I can eventually call it that).
Perhaps in a later post I'll get into what the code looks like and a dialog of what each part does but for now I'll just put up some of the early results and learning points that I've encountered. Ultimately, I'll get the code up on github and follow along with that here.
I'm using two images for this exercise: one that contains a rainbow of colors to test and another to represent the effect on a more likely picture.
Initially, I looked at just 'dragging' each color down the image while increasing the normalization scale along the vertical to give a wash out effect further down the image. This represents how the water would continue to wash color away as it 'pulled' higher colors down the hanging image. This worked well for the rainbow version of the image:
That result has a good 'bleed' in that stronger colors last longer down the vertical. However, with the colors in the house image the washout was too aggressive and wiped out much of the original content.
If you ignore the washout, though, it is clear that the draw of colors down the image is visible (especially around the windows) meaning that reducing the washout might still produce a more realistic effect if enough of the original image could be preserved.
With that in mind, I added the ability to preserve a percentage of the original image while applying the effect. This allows a user to tune the washout per image to get just the right look. For example, too much reuse (20%) on the house and the washout effect has little impact:
But taking that down to 7.5% gets closer to what I am looking for:
There is still plenty for me to do such as handling the edges and water line better and further manipulating the washed image. For example, adding additional transforms to the result to get more seep/bleed on the washed colors. The image below shows a simple kernel convolution to add blur to the pencils, for example.
Showing posts with label C. Show all posts
Showing posts with label C. Show all posts
Sunday, October 2, 2016
Tuesday, November 25, 2014
Order of Events
inet_ntoa uses static storage for the result it returns. The GNU implementation of inet_ntoa uses the following internally:
This makes the function thread-safe but this safety does not remove the need to worry about use within a single thread. Consider the following snippet of code:
Since inet_ntoa is used twice within the argument list the result is dependent on the order of evaluation of the arguments to printf. Regardless of which call gets evaluated first the output will always print the same IP address twice. On my system, the result is:
This is a result of two things: arguments are evaluated before their results are used by printf; and inet_ntoa overwrites static storage on each invocation. Looking at the instructions for this C code makes this clear:
The correct way to call inet_ntoa consecutively is to save each result to a local variable.
static __thread char buffer[18];
This makes the function thread-safe but this safety does not remove the need to worry about use within a single thread. Consider the following snippet of code:
#include <arpa/inet.h>
#include <stdio.h>
int main () {
struct in_addr a = { .s_addr = 1234567 }, b = { .s_addr = 7654321 };
return printf ("%s : %s\n", inet_ntoa (a), inet_ntoa (b));
}
Since inet_ntoa is used twice within the argument list the result is dependent on the order of evaluation of the arguments to printf. Regardless of which call gets evaluated first the output will always print the same IP address twice. On my system, the result is:
135.214.18.0 : 135.214.18.0
This is a result of two things: arguments are evaluated before their results are used by printf; and inet_ntoa overwrites static storage on each invocation. Looking at the instructions for this C code makes this clear:
.LC0:
.string "%s : %s\n"
.text
.globl main
.type main, @function
main:
pushl %ebp
movl %esp, %ebp
pushl %ebx
andl $-16, %esp
subl $32, %esp
movl $1234567, 24(%esp)
movl $7654321, 28(%esp)
movl 28(%esp), %eax
movl %eax, (%esp)
call inet_ntoa
movl %eax, %ebx ; pointer stored to static memory
movl 24(%esp), %eax
movl %eax, (%esp)
call inet_ntoa
movl $.LC0, %edx
movl %ebx, 8(%esp) ; arg2 to printf; pointer from above
movl %eax, 4(%esp) ; arg1 to printf; new pointer, same static memory
movl %edx, (%esp) ; arg0 (format string)
call printf
movl -4(%ebp), %ebx
leave
ret
The correct way to call inet_ntoa consecutively is to save each result to a local variable.
#include <arpa/inet.h>
#include <string.h>
#include <stdio.h>
int main () {
struct in_addr a = { .s_addr = 1234567 }, b = { .s_addr = 7654321 };
char ipa[18] = { 0 }, ipb[18] = { 0 };
strcpy (ipa, inet_ntoa (a));
strcpy (ipb, inet_ntoa (b));
return printf ("%s : %s\n", ipa, ipb);
}
Labels:
best-practices
,
C
,
debugging
,
gotcha
Thursday, June 27, 2013
Walk this way
I recently found a handy mechanism for walking a directory tree in Linux. In
general, the way I used to do this was to use facilities found in dirent.h and
write my own recursive directory walker. Something similar to:
While that does work, it is rather verbose (especially once you get used to
environments like Ruby and Python). It turns out that ftw.h provides a more
concise way to do the above while managing all the little details like
avoiding '.' and '..' and managing the current path string. Here is what that
looks like to do the same as the above:
I also like the fact that a callback is used to operate on each of the files
found. It makes managing changes much easier as the tree walking is separated
from the code that handles the logic associated with inspecting the files.
general, the way I used to do this was to use facilities found in dirent.h and
write my own recursive directory walker. Something similar to:
#include <stdio.h>
#include <string.h>
#include <dirent.h>
void reclist (const char* dirname) {
DIR* dir = opendir (dirname);
struct dirent* entry = 0;
char name[1024] = {0};
if (! dir) { return; }
entry = readdir (dir);
while (entry) {
if (strncmp (entry->d_name, ".", 1)) {
switch (entry->d_type) {
case DT_REG:
printf ("%s\n", entry->d_name);
break;
case DT_DIR:
snprintf (name, 1024, "%s/%s", dirname, entry->d_name);
reclist (name);
break;
}
}
entry = readdir (dir);
}
closedir (dir);
}
int main(int argc, char** argv) {
const char * dir = ".";
if (argc == 2) { dir = argv[1]; }
reclist (dir);
return 0;
}
While that does work, it is rather verbose (especially once you get used to
environments like Ruby and Python). It turns out that ftw.h provides a more
concise way to do the above while managing all the little details like
avoiding '.' and '..' and managing the current path string. Here is what that
looks like to do the same as the above:
#include <stdio.h>
#include <ftw.h>
int handle_entry (const char *entry, const struct stat *sb, int type) {
if (type == FTW_F) {
printf("%s\n", entry);
}
return 0;
}
int main() {
ftw(".", handle_entry, 10);
return 0;
}
I also like the fact that a callback is used to operate on each of the files
found. It makes managing changes much easier as the tree walking is separated
from the code that handles the logic associated with inspecting the files.
Friday, September 14, 2012
All your heap are belong to us
This is a port and slight expansion of the ideas presented here.
The premise of that article is that underneath the interface provided by an application the handling of sensitive information is done in memory provided on the heap (via malloc/new). With that in mind, capturing the memory before it was released by the application would potentially expose hidden details. The system used in that article was OSX and the applications were Twitter-based but I decided to port to Linux and look at ssh.
First, the port:
Nothing new here, just a version of free that will be interposed by this library. Compiling that and running the following:
Produces a log with a substantial amount of information in it. However, the password is not included anywhere. It seems that ssh sanitizes buffers before freeing them - the next logical step is to provide a version of memset that does the same thing to try and capture where the memory is sanitized:
With that, our log now contains the following:
I've played with interpositioning a bit over the past few years but I never considered using it in exactly this way. Thanks to Joe Damato for the initial idea and original OSX code.
The premise of that article is that underneath the interface provided by an application the handling of sensitive information is done in memory provided on the heap (via malloc/new). With that in mind, capturing the memory before it was released by the application would potentially expose hidden details. The system used in that article was OSX and the applications were Twitter-based but I decided to port to Linux and look at ssh.
First, the port:
#include <stdio.h>
#define __USE_GNU
#include <dlfcn.h>
void (*real_free)(void *);
void free (void * mem) {
char buff[256] = {0}, * p = mem;
int i = 0;
if (! mem) { return; }
while (*p) {
buff[i++] = *p++;
if (i > 254)
break;
}
buff[i] = 0;
fprintf (stderr, "[free] %s\n", buff);
real_free = dlsym (RTLD_NEXT, "free");
real_free (mem);
}
Nothing new here, just a version of free that will be interposed by this library. Compiling that and running the following:
LD_PRELOAD=/tmp/heapgrab.so ssh ezpz@sandbox 2>heapgrab.log
Produces a log with a substantial amount of information in it. However, the password is not included anywhere. It seems that ssh sanitizes buffers before freeing them - the next logical step is to provide a version of memset that does the same thing to try and capture where the memory is sanitized:
void* (*real_memset)(void*, int, size_t);
void * memset (void * mem, int c, size_t size) {
char buff[256] = {0}, * p = mem;
int i = 0;
if (! mem ) { return; }
while (*p) {
buff[i++] = *p++;
if (i > (size - 1) || i > 254)
break;
}
buff[i] = 0;
fprintf (stderr, "[memset] %s\n", buff);
real_memset = dlsym(RTLD_NEXT, "memset");
return real_memset (mem, c, size);
}
With that, our log now contains the following:
[free] publickey,password
[free] keyboard-interactive
[free] publickey
[memset] ezpz_awesome_password
[memset] xxxxx
[memset] ezpz_awesome_password
I've played with interpositioning a bit over the past few years but I never considered using it in exactly this way. Thanks to Joe Damato for the initial idea and original OSX code.
Labels:
C
,
ld_preload
Saturday, July 21, 2012
gcc constructor attribute
It is sometimes helpful to provide a way to 'initialize the system' when you are writing a library. Many times, this manifests itself in the form of a lib_init() call. Similarly, any convenience cleanup would be provided via lib_close(). For a concrete example look at ncurses which provides initscr() and endwin() for this use.
In the case when these routines are required (as they are in ncurses) there is an easier way to provide the proper setup without placing the onus to call these methods on the developer. GCC provides __attribute__((constructor)) and __attribute__((destructor)) which allow for calling methods when a library is loaded and unloaded respectively. These calls happen outside the scope of main. For example,
This program will output the following:
In the case when these routines are required (as they are in ncurses) there is an easier way to provide the proper setup without placing the onus to call these methods on the developer. GCC provides __attribute__((constructor)) and __attribute__((destructor)) which allow for calling methods when a library is loaded and unloaded respectively. These calls happen outside the scope of main. For example,
#include <stdio.h>
__attribute__((constructor)) void init() {
fprintf (stderr, "constructor\n");
}
int main () {
return fprintf(stderr, "main\n");
}
This program will output the following:
constructor
main
In the case of a library such as ncurses this is a perfect place to invoke the necessary initialization and cleanup routines. A simplified example library:
__attribute__((constructor))
static void setup() { do_some ("setup"); }
__attribute__((destructor))
static void breakdown() { do_some ("breakdown"); }
void mylib_method (const char * thing) { do_some (thing); }
Now, if a developer links against your library setup() is called when your library is loaded and breakdown() is called when it is unloaded. A nicety of this approach is that it provides the same functionality if the library is pulled in when the executable is loaded or at some later point (via dlopen/dlsym, for example) thus always ensuring a consistent environment for your code.
This is obviously not a fit for all libraries. Only those with setup and cleanup that can be self-contained and are always required would benefit from such an approach. In those cases, however, I prefer this method to the alternative of burdening the developer with requirements of my library.
Sunday, February 19, 2012
LLVM pass on Windows: integrating with opt
I've been using LLVM for a few weeks now and my primary interaction with it has been writing custom passes. LLVM has a very nice system for handling user defined passes: you create an independent plug-in and load it dynamically using the opt tool. A full explanation can be found in the LLVM pass documentation.
Unfortunately, plug-ins are dynamically linked in LLVM which excludes this approach on Windows (without relying on Cygwin). For all my searching I was not able to find instructions on integrating a pass directly with the opt tool but I needed to support custom passes on Windows without using Cygwin. Mostly as a note for myself, I am listing here the steps I used to create my own custom pass as part of the opt tool; hopefully they will be useful for others as well.
I've followed as best I could the format used by existing infrastructure within LLVM. This does not mean that I have not missed something critical or what I have provided adheres to LLVM policy and/or standards.
N.B. These examples assume you are:
To load this, and multiple other custom passes, it is necessary to create an initialization routine that iterates over all passes in the library. In this example the only call in that routine is the call to the pass above. Still in the Custom directory, create the following as Custom.cpp:
You will also need to support either build system with a Makefile and CMakeLists.txt.
That is the entirety of writing a new pass library for LLVM. The remainder of the work is integrating that new code into the larger system.
First, you need to define a way for LLVM to create an instance of your pass. Save the following as Custom.h in llvm/include/llvm/Transforms/
Then you need to provide the prototypes for the two initialization routines. Add the following two lines to llvm/include/llvm/InitializePasses.h - make sure you do so inside the llvm namespace.
Next, you need to set any passes to be linked by adding entries into llvm/include/llvm/LinkAllPasses.h
Updates are required to all relevant makefiles in the source tree. You will need to adjust the following to account for the additions discussed above:
The new pass should now be visible (on all platforms) without having to load a library with opt.
Unfortunately, plug-ins are dynamically linked in LLVM which excludes this approach on Windows (without relying on Cygwin). For all my searching I was not able to find instructions on integrating a pass directly with the opt tool but I needed to support custom passes on Windows without using Cygwin. Mostly as a note for myself, I am listing here the steps I used to create my own custom pass as part of the opt tool; hopefully they will be useful for others as well.
I've followed as best I could the format used by existing infrastructure within LLVM. This does not mean that I have not missed something critical or what I have provided adheres to LLVM policy and/or standards.
N.B. These examples assume you are:
- already familiar with writing a custom pass as described by the LLVM documentation
- capable of understanding Makefiles and how to modify them to suit your needs
- using llvm-3.0 (that is the version used in these examples)
These examples will build a pass named mypass which will simply print out all function names. This pass will be part of the Custom library (also created here).
The first step is to create a new directory named Custom under llvm/lib/Transforms. This is where all passes for the new library will live. Create a very simple function pass and place it in this new directory - I used the following (MyPass.cpp)
The first step is to create a new directory named Custom under llvm/lib/Transforms. This is where all passes for the new library will live. Create a very simple function pass and place it in this new directory - I used the following (MyPass.cpp)
#define DEBUG_TYPE "mypass"
#include "llvm/Function.h"
#include "llvm/Pass.h"
#include "llvm/Transforms/Custom.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
namespace {
struct MyPass : public FunctionPass {
static char ID;
MyPass() : FunctionPass(ID) {
initializeMyPassPass(*PassRegistry::getPassRegistry());
}
/*
* Just print the function name
*/
bool runOnFunction(Function &F) {
bool Changed = false;
errs().write_escaped(F.getName()) << "\n";
return Changed;
}
};
}
char MyPass::ID = 0;
INITIALIZE_PASS(MyPass, "mypass", "Print all function names",
false, false)
FunctionPass *llvm::createMyPassPass() {
return new MyPass();
}
#include "llvm/InitializePasses.h"
#include "llvm-c/Initialization.h"
using namespace llvm;
/// initializeCustom - Initialize all passes in the Custom library
void llvm::initializeCustom(PassRegistry &Registry) {
initializeMyPassPass(Registry);
}
/// LLVMInitializeCustom - C binding for initializeCustom.
void LLVMInitializeCustom(LLVMPassRegistryRef R) {
initializeCustom(*unwrap(R));
}
LEVEL = ../../..
LIBRARYNAME = LLVMCustom
BUILD_ARCHIVE = 1
include $(LEVEL)/Makefile.common
add_llvm_library(LLVMCustom
MyPass.cpp
Custom.cpp
)
First, you need to define a way for LLVM to create an instance of your pass. Save the following as Custom.h in llvm/include/llvm/Transforms/
#ifndef LLVM_CUSTOM_H
#define LLVM_CUSTOM_H
namespace llvm {
FunctionPass *createMyPassPass();
}
#endif
void initializeCustom(PassRegistry&);
void initializeMyPassPass(PassRegistry&);
#include "llvm/Transforms/Custom.h"
// This part must reside in the constructor of struct ForcePassLinking
(void) llvm::createMyPassPass();
- llvm/lib/Transforms/Makefile
- llvm/lib/Transforms/CMakeLists.txt
- llvm/tools/opt/Makefile (add link dependency for 'custom')
- llvm/tools/opt/CMakeLists.txt (add link dependency for 'custom')
- llvm/tools/bugpoint/Makefile (add link dependency for 'custom')
- llvm/tools/bugpoint/CMakeLists.txt (add link dependency for 'custom')
initializeCustom(Registry);
-mergereturn - Unify function exit nodes
-module-debuginfo - Decodes module-level debug info
-mypass - Print all function names
-no-aa - No Alias Analysis (always returns 'may' alias)
-no-path-profile - No Path Profile Information
Monday, January 16, 2012
Just making sure
I was pouring over some code recently and came across one expression that really made me shake my head:
I pretty sure the intent was
Either that, or they really wanted to make sure the string was null-terminated.
buff[strlen(buff)] = 0;
buff[strlen(buff) - 1] = 0;
Friday, December 9, 2011
Underhanded C (the explanation)
In my last post I provided what would have been my entry to the underhanded C contest if it was still active. In this post I will give the details of how the code works and what bonus points I tried to target.
My solution really boils down to an off-by-one error that is hidden in a return value. A sharp observer would certainly see that I bail silently in the middle of parsing the comment section when a full luggage record was already input; that would be a huge breadcrumb to the source of the error in an investigation/review.
Due to how I handle newlines in the grab_line function it is possible to read only a newline character and return a 0-length result (considered an error in the context of grab_luggage_entry). If any entry is exactly BUFF_SIZE characters long the entire entry is silently discarded because the last read suffers from the 0-length return.
Here are the evaluation criteria and my attention to them:
Short code:
The critical section is less than 70 lines of code (with comments) but the logic for filtering made things a bit longer. This was by far the hardest target to hit with respect to the contest
Universal:
This code works on multiple platforms (Windows/Linux) but in different ways since the line endings are different ('\n' vs. '\r\n') and only '\n' is used in the check
Plausible deniability:
Comment size is unbounded in the spec so using fgets is justified/plausible as a input mechanism
getline is not portable and we want to work on multiple platforms (more justification for fgets)
Syntax coloring:
Passes syntax coloring, high compiler warnings and valgrind tests
... with bonus points for...
Mis-routing appears innocent:
The length of the line is the only qualifier to misroute making the error appear arbitrary and random in most contexts
Flexible mis-routing:
An informed operator may arbitrarily choose to trigger the behavior for nasty patrons (qualifies for spite bonus as well)
Additionally, by making the buffer size a macro (gcc -DBUFF_SIZE=128) behavior can be modified without changing the code.
While the contest appears no longer active I still enjoyed spending some time thinking up how I would write this. I've seen past winners' entries and this is certainly not of that caliber but it was nice to see that I was able to address the majority of the scoring points in at least some way.
My solution really boils down to an off-by-one error that is hidden in a return value. A sharp observer would certainly see that I bail silently in the middle of parsing the comment section when a full luggage record was already input; that would be a huge breadcrumb to the source of the error in an investigation/review.
Due to how I handle newlines in the grab_line function it is possible to read only a newline character and return a 0-length result (considered an error in the context of grab_luggage_entry). If any entry is exactly BUFF_SIZE characters long the entire entry is silently discarded because the last read suffers from the 0-length return.
Here are the evaluation criteria and my attention to them:
Short code:
The critical section is less than 70 lines of code (with comments) but the logic for filtering made things a bit longer. This was by far the hardest target to hit with respect to the contest
Universal:
This code works on multiple platforms (Windows/Linux) but in different ways since the line endings are different ('\n' vs. '\r\n') and only '\n' is used in the check
Plausible deniability:
Comment size is unbounded in the spec so using fgets is justified/plausible as a input mechanism
getline is not portable and we want to work on multiple platforms (more justification for fgets)
Syntax coloring:
Passes syntax coloring, high compiler warnings and valgrind tests
... with bonus points for...
Mis-routing appears innocent:
The length of the line is the only qualifier to misroute making the error appear arbitrary and random in most contexts
Flexible mis-routing:
An informed operator may arbitrarily choose to trigger the behavior for nasty patrons (qualifies for spite bonus as well)
Additionally, by making the buffer size a macro (gcc -DBUFF_SIZE=128) behavior can be modified without changing the code.
While the contest appears no longer active I still enjoyed spending some time thinking up how I would write this. I've seen past winners' entries and this is certainly not of that caliber but it was nice to see that I was able to address the majority of the scoring points in at least some way.
Labels:
C
,
competition
,
fun
,
puzzle
Saturday, September 24, 2011
Underhanded C (the code)
There was some recent activity around the Underhanded C Contest. The posts are almost 2 years old now and I've attempted to contact the author without reply so I'm assuming that the contest is dead and my posting ideas for a solution won't provide any competitive advantage. If anyone finds evidence to the contrary please let me know.
In general, the premise of this round of the competition is to [mis]configure the routing of luggage in the most innocuous way possible with bonus points for plausible deniability and other features. Here is what I would have submitted if the competition was still live with explanation of the sneaky parts to follow in another post
The input specification provides a very specific format for the fields of the entries save one critical exception. I decided to target the input handling part of the system as opposed to the actual routing algorithm as it provided for several bonus point aspects. I'll explain them later but first, the code.
Here is the devious section of the code:
and the main driver...
Here is a sample run with input/output as expected.
Input:
Output:
I'll follow-up with another post about how the code works and some of the bonus aspects.
In general, the premise of this round of the competition is to [mis]configure the routing of luggage in the most innocuous way possible with bonus points for plausible deniability and other features. Here is what I would have submitted if the competition was still live with explanation of the sneaky parts to follow in another post
The input specification provides a very specific format for the fields of the entries save one critical exception. I decided to target the input handling part of the system as opposed to the actual routing algorithm as it provided for several bonus point aspects. I'll explain them later but first, the code.
Here is the devious section of the code:
#define BUFF_SIZE 64
/* Represents a single entry in the luggage schedule input file */
typedef struct {
long time;
char lid[9], fid[7], from[4], to[4], *note;
} luggage_entry;
/*
* Pull from input stream removing any newline.
* If there is info left for this record (determined by the lack of a newline),
* data_remains is set to 1 otherwise it is set to 0.
* Returns number of bytes read from the stream
*/
size_t grab_line (char * buff, size_t buff_sz, int * data_remains) {
char * nl = 0;
if (NULL == fgets (buff, buff_sz, stdin)) { return 0; }
nl = strrchr (buff, '\n');
if (nl) {
*data_remains = *nl = 0;
} else {
*data_remains = 1;
}
return strlen (buff);
}
/*
* Returns non-zero on successful record load, 0 on failure
*/
int grab_luggage_entry (luggage_entry * e) {
char line_buff[BUFF_SIZE] = {0}, *p = 0;
int data_remains = 0, nbytes = 0;
if (! grab_line (line_buff, sizeof (line_buff), &data_remains))
return 0;
/* Input format: DDDDDDDDDD CCCCCCCC CCCCC? CCC CCC ?* */
sscanf (line_buff, "%ld %s %s %s %s%n",
&e->time, e->lid, e->fid, e->from, e->to, &nbytes);
/* A trailing space indicates a comment, otherwise we are done */
p = strchr (line_buff + nbytes, ' ');
if (!p)
return 1;
/* There is a comment. Grab it. */
p += 1; /* ignore the first space */
e->note = malloc (strlen(p) + 1);
strcpy (e->note, p);
/* loop until the remainder of the line is processed */
while (data_remains) {
size_t new_size = 0;
if (! grab_line (line_buff, sizeof (line_buff), &data_remains)) {
free (e->note);
return 0;
}
/* Append the new data */
new_size = strlen(e->note) + strlen(line_buff) + 1;
e->note = realloc (e->note, new_size);
strcat (e->note, line_buff);
}
return 1;
}
int main (int argc, char ** argv) {
struct entry_list *list = 0;
/* ... */
while (! feof (stdin) && ! ferror (stdin)) {
struct entry entry;
memset(&entry, 0, sizeof(entry));
if (grab_luggage_entry (&entry))
add_entry (list, &entry);
}
/* ... */
Input:
1262002831 UA129089 TP579 FRA OPO Passengers missed first connecting flight
1262027494 UA129086 LH1230 FRA LIS
1262027495 UA129089 LH1230 FRA LIS Next flight canceled, passengers rerouted
1262029822 UA129086 LH1450 FRA LHR Passenger A says screw it, send me to London
1262030463 UA129086 LH1280 FRA DUB Direct flight canceled, rerouted
1262030463 UA129086 LH1390 DUB LHR
1262033482 UA129089 LH1750 FRA LIS Layover in FRA. Route to LIS
1262040831 UA129086 TP579 OPO FRA
1262002831 UA129089 TP579 FRA OPO Passengers missed first connecting flight
1262027494 UA129086 LH1230 FRA LIS
1262027495 UA129089 LH1230 FRA LIS Next flight canceled, passengers rerouted
1262029822 UA129086 LH1450 FRA LHR Passenger A says screw it, send me to London
1262030463 UA129086 LH1280 FRA DUB Direct flight canceled, rerouted
1262030463 UA129086 LH1390 DUB LHR
1262040831 UA129086 TP579 OPO FRA
Labels:
C
,
competition
,
fun
,
puzzle
Friday, August 12, 2011
Quick Shine
I've posted before that I like puzzles. I came across another challenge that recently appeared on the hacker news feed - here is the actual post.
The premise is that there is a slow floating point operation that is taking place that can be sped up by using integer-only operations without causing any change in the output of the equation. For reference, here is the function that is reported to be slow:
unsigned char SlowBrightness(unsigned char r,
unsigned char g,
unsigned char b)
{
return 0.289f * r +
0.587f * g +
0.114f * b + 1e-5f;
}
My approach to this was to try and estimate the floating point values by composing large enough integer fractions. The goal here is to find a single denominator (optimally a power of 2) that is capable of hosting three numerators that will result in the values listed. The reason to aim for a power of two in the denominator is that a dividing by powers of two can be efficiently implemented as a right bit shift.
At 219, the following values result as numerators: 151519, 307757 and 59769 representing 0.289, 0.587 and 0.114 respectively. To check what type of error was related to these values I also evaluated the division and compared to the original values.
0.28900000
0.28899955 (151519/524288)
0.58700001
0.58699989 (307757/524288)
0.11400000
0.11400032 (59769/524288)
There was error, but since there was conveniently a constant in the original equation I could mitigate by adjusting the constant if necessary.
Once I had the values, I wrote the following test harness:
#include <stdio.h>
#define R(r) (151519UL*(r))
#define G(g) (307757UL*(g))
#define B(b) (59769UL*(b))
#define C (5)
typedef unsigned char uchar;
uchar SlowBrightness(uchar r, uchar g, uchar b) {
return 0.289f * r + 0.587f * g + 0.114f * b + 1e-5f;
}
uchar FastBrightness(uchar r, uchar g, uchar b) {
return (R(r) + G(g) + B(b) + C) >> 19;
}
int main () {
uchar r = 0, g = 0, b = 0;
for (; r < 255; ++r)
for (g = 0; g < 255; ++g)
for (b = 0; b < 255; ++b)
if (SlowBrightness(r,g,b) != FastBrightness(r,g,b))
printf("FAIL: %d,%d,%d\n", r,g,b);
return 0;
}
The constant value of C came from 1e-5f represented as 5 / 219. As expected, I had to increase the value of C to compensate for the difference in my estimated numbers. After the adjustment (the minimum constant ended up being 72) I was able to run and match all values of the two calls. I also achieved the bonus for minimal constants and only using +, * and >> operations.
Tuesday, July 26, 2011
typedef[ine]
The typedef keyword introduces a new type. The #define directive provides a textual substitution mechanism. When does this matter? Consider the following source:
If str_type.h contains
Then the output of running that program is
However, if that file contains
You instead get
Notice that since the CharPtr is no longer a type you get
after the processing phase of translation and the asterisk only binds to the first variable leaving the remaining two as plain char variables.
Use #define directives only to provide textual substitution prior to translation; it does not interact with - or compliment - the type system.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "str_type.h"
size_t length (CharPtr str) { return strlen(str); }
void message () {
CharPtr str = malloc (255);
if (! str) { return; }
strcpy (str, "The Message");
printf("%s\n", str);
free (str);
}
int main () {
CharPtr str = "Some Static String";
CharPtr str1, str2, str3;
printf ("Length: %d\n", length (str));
message ();
printf ("sizeof(str1): %d\n", sizeof (str1));
printf ("sizeof(str2): %d\n", sizeof (str2));
return 0;
}
If str_type.h contains
typedef char * CharPtr;
Then the output of running that program is
Length: 18
The Message
sizeof(str1): 8
sizeof(str2): 8
However, if that file contains
#define CharPtr char *
You instead get
Length: 18
The Message
sizeof(str1): 8
sizeof(str2): 1
Notice that since the CharPtr is no longer a type you get
char * str1, str2, str3;
after the processing phase of translation and the asterisk only binds to the first variable leaving the remaining two as plain char variables.
Use #define directives only to provide textual substitution prior to translation; it does not interact with - or compliment - the type system.
Tuesday, July 5, 2011
Progress
[EDIT] This code is now available on github: libpbar
cURL ships with one. wget uses it's own. OpenSSH (scp) even comes with it's own version. Indeed, I've written several variations myself over the years. Sooner or later, if you are doing something that processes large amounts of data or takes a long time to complete and you are working in a command-line environment you will write your own, too. A progress bar.
I did a quick search for existing progress bar libraries but came up with little outside of Ruby and Python wrappers around what the packages I mention above are already doing [1]. For mostly selfish reasons, I've decided to write a library that fixes my redundant behavior moving forward. Once I am able to provide a proper build system I will put this code up on github - my unfamiliarity with autotools may delay this a bit.
What this library aims to provide is a consistent interface for programatically displaying a progress bar outside of a GUI environment. It does not try to provide a package similar to Pipe Viewer (pv) which is a complete, standalone program for monitoring processes activity. Instead, to keep things simple, libpbar will initially provide a class with the following public interface:
With three implementations provided with the library: TextProgressBar, ColorProgressBar, GraphicalProgressBar. These provide basic text functionality, color text, and a GTK+-based object respectively. Using any of these facilities is as simple as:
They each do as you might expect:
TextProgressBar:
ColorProgressBar:
GraphicalProgressBar:
The nice thing about the GUI version is that the hosting program doesn't need to be a GUI application. For this version of the progress bar a separate thread is used to spawn the graphical interface and as much as possible is done to shed the window treatments to expose just the progress bar itself.
I've got to expand on this by allowing some way to encode message text with format strings and allowing user-defined color modifications. The basics are there, however, and I should now be free from writing yet another progress bar implementation.
[1] This is a solved problem and certainly my fruitless search does not imply any lack of existing tools
cURL ships with one. wget uses it's own. OpenSSH (scp) even comes with it's own version. Indeed, I've written several variations myself over the years. Sooner or later, if you are doing something that processes large amounts of data or takes a long time to complete and you are working in a command-line environment you will write your own, too. A progress bar.
I did a quick search for existing progress bar libraries but came up with little outside of Ruby and Python wrappers around what the packages I mention above are already doing [1]. For mostly selfish reasons, I've decided to write a library that fixes my redundant behavior moving forward. Once I am able to provide a proper build system I will put this code up on github - my unfamiliarity with autotools may delay this a bit.
What this library aims to provide is a consistent interface for programatically displaying a progress bar outside of a GUI environment. It does not try to provide a package similar to Pipe Viewer (pv) which is a complete, standalone program for monitoring processes activity. Instead, to keep things simple, libpbar will initially provide a class with the following public interface:
class ProgressBar {
public:
ProgressBar (::size_t cap);
void update (::size_t n = 1);
};
With three implementations provided with the library: TextProgressBar, ColorProgressBar, GraphicalProgressBar. These provide basic text functionality, color text, and a GTK+-based object respectively. Using any of these facilities is as simple as:
int flags = TextProgressBar::SHOW_VALUE | TextProgressBar::SHOW_COUNT;
TextProgressBar pb(100,flags);
They each do as you might expect:
TextProgressBar:
ColorProgressBar:
GraphicalProgressBar:
The nice thing about the GUI version is that the hosting program doesn't need to be a GUI application. For this version of the progress bar a separate thread is used to spawn the graphical interface and as much as possible is done to shed the window treatments to expose just the progress bar itself.
I've got to expand on this by allowing some way to encode message text with format strings and allowing user-defined color modifications. The basics are there, however, and I should now be free from writing yet another progress bar implementation.
[1] This is a solved problem and certainly my fruitless search does not imply any lack of existing tools
Thursday, May 19, 2011
Using structs
If you want to group related information in a C program the common way to do so is with a struct. You see this everywhere: various network packets are represented as structs; file system objects (inodes); time values can be stored with separate components in struct members; and so on. In all of these cases it is entirely possible to use basic arrays to maintain this data. The problem with that is that we, as non-machines, find it more natural to think in terms of collections with named members than random offsets into a buffer. In other words, it is easier to design and reason with 'object.member = value' than it is with 'buffer[offset] = value' (or something more obscure). Especially if you deal with members of various sizes.
I feel this is a natural progression - the tendency to want to group related items and operate with them as individual 'things'. I believe this to be a dominating theme with C programmers (and programmers in general). What I dont see too much of, however, is explicitly moving in the opposite direction. That is, given some data in the form of a buffer, C programmers are more likely to develop their own mini-parser to get at that data instead of using a struct to ease implementation.
As an example, I've seen the following many times in a variety of flavors:
And, while that is functional it is also error-prone and cumbersome to write each time you need to do such a conversion. In contrast, I see very little in the form of
Where I think the implementation is simplified
If we remove most of the boilerplate sections of an example and examine just how each of these is available to use we can see what the overall effect is.
and with the struct
The main differences between the two are how data is extracted from the raw buffer and how that implementation affects code design. In both cases the struct provides a cleaner and more understandable solution. In a more generic setting, one where you may not have the exact number of elements in the buffer, the struct approach above doesn't fit exactly.
However, it can be modified:
Where the using the function still requires the buffer offset when calling the function but the method implementation is much cleaner.
This becomes even more useful if you consider cases where an individual member may contain multiple bits of information. For instance, it is common to have a data member of a struct represent a set of flags. The typical implementation involves a set of macros to test or set values in a bit mask.
For example:
With well designed macro names this approach does not imply altogether clumsy code but the macro design is still cumbersome. I think that a more elegant approach can be achieved through the use of structs.
This can even be done without having to change implementation code. Leaving the macro interface while changing the bodies to represent the new implementation allows users of the macro interface to continue uninterrupted.
The struct is no panacea. However, I find that in these types of scenarios the struct provides for much cleaner and manageable code - something I favor whenever I can.
I feel this is a natural progression - the tendency to want to group related items and operate with them as individual 'things'. I believe this to be a dominating theme with C programmers (and programmers in general). What I dont see too much of, however, is explicitly moving in the opposite direction. That is, given some data in the form of a buffer, C programmers are more likely to develop their own mini-parser to get at that data instead of using a struct to ease implementation.
As an example, I've seen the following many times in a variety of flavors:
uint32_t extract(unsigned char *buffer) {
uint32_t value = 0;
int i = 0;
for (i=sizeof(uint32_t)-1; i>=0; i--) {
value = value << 8;
value += buffer[i];
}
return value;
}
And, while that is functional it is also error-prone and cumbersome to write each time you need to do such a conversion. In contrast, I see very little in the form of
struct extracted {
uint32_t v[5];
};
struct extracted * map = buffer;
Where I think the implementation is simplified
If we remove most of the boilerplate sections of an example and examine just how each of these is available to use we can see what the overall effect is.
uint32_t vals[] = {0x0, 0x0f, 0x0f0f, 0x0f0f0f, 0x0f0f0f0f};
unsigned char * cvals = vals;
for (; i < 5; ++i)
printf ("%10lu\n", extract (cvals + i * sizeof(uint32_t)));
and with the struct
uint32_t vals[] = {0x0, 0x0f, 0x0f0f, 0x0f0f0f, 0x0f0f0f0f};
unsigned char * cvals = vals;
struct extracted * map = cvals;
for (; i < 5; ++i)
printf ("%10lu\n", map->v[i]);
The main differences between the two are how data is extracted from the raw buffer and how that implementation affects code design. In both cases the struct provides a cleaner and more understandable solution. In a more generic setting, one where you may not have the exact number of elements in the buffer, the struct approach above doesn't fit exactly.
However, it can be modified:
struct value {
uint32_t data;
};
uint32_t extract(unsigned char *buffer) {
struct value * v = buffer;
return v->data;
}
Where the using the function still requires the buffer offset when calling the function but the method implementation is much cleaner.
This becomes even more useful if you consider cases where an individual member may contain multiple bits of information. For instance, it is common to have a data member of a struct represent a set of flags. The typical implementation involves a set of macros to test or set values in a bit mask.
For example:
#define FOO_FLAG (1<<0)
#define BAR_FLAG (1<<1)
#define BAZ_FLAG (1<<2)
#define ISSETFOO(v) ((v).mask & (FOO_FLAG))
#define SETFOO(v) ((v).mask |= (FOO_FLAG))
#define UNSETFOO(v) ((v).mask &= ~(FOO_FLAG))
/* similarly for BAR_FLAG and BAZ_FLAG */
struct data {
unsigned short mask;
unsigned char stuff[200];
};
int main () {
struct data data;
SETFOO(data);
if (ISSETFOO(data)) {
printf ("FOO_FLAG is set\n");
} else {
printf ("Foo_FLAG is not set\n");
}
/* ... */
With well designed macro names this approach does not imply altogether clumsy code but the macro design is still cumbersome. I think that a more elegant approach can be achieved through the use of structs.
struct flags {
unsigned char foo:1;
unsigned char bar:1;
unsigned char baz:1;
};
struct data {
struct flags mask;
unsigned char stuff[200];
};
int main () {
struct data data;
data.mask.foo = 1;
if (data.mask.foo) {
printf ("FOO_FLAG is set\n");
} else {
printf ("Foo_FLAG is not set\n");
}
/* ... */
This can even be done without having to change implementation code. Leaving the macro interface while changing the bodies to represent the new implementation allows users of the macro interface to continue uninterrupted.
The struct is no panacea. However, I find that in these types of scenarios the struct provides for much cleaner and manageable code - something I favor whenever I can.
Wednesday, April 13, 2011
Dynamic Code Loading (in C)
Originally, I intended to write this post about function pointers in C. I was inspired (yet again) by activity in a forum where a user asked a question about why you would ever need to use function pointers. As I started thinking about mapping the idea to a useful example I kept considering how the kernel uses function pointers for module writers. Couple that with my new exploration into the Erlang programming language and you get this content instead.
To address the first point directly: function pointers are useful as a means to expose a standard set of functionality. Consider how a character device driver for the linux kernel operates, for instance. When you write a character device driver you are presented with a struct file_operations (fops).
Why? Consider what you do with a character device; read from it, write to it, and so on. But since each device requires it's own implementation there needs to be a way to indicate this within the module code.
One solution to this is to have a set of skeleton functions declared in a header file. Require that all modules include this file and provide definitions for the functions. There are two obvious drawbacks to this approach:
Another solution is to use a structure that contains function pointers and allow developers to use that when writing to the interface. This solves the two issues with the skeleton declaration approach: any function not defined is set to nil in the structure and adding new members to the structure wont break existing code. Ok... if there is some fancy offset calculation being done there is potential for breakage, but that is suspect behavior in the first place.
Obviously removing entries creates compatibility issues in either solution.
Here is how the function pointer approach works in the linux kernel:
Where each of the i2cdev_* functions are defined locally to that file and any operations not defined in the struct are nil (aio_fsynch, for example).
That actually represents dynamic code loading in it's entirety. You can change the behavior of a system by loading modules at runtime. But that is in the kernel and not applicable in userland; what if we wanted to do that for a process we control? That is something that Erlang lets you do and - because I'm bent on reinventing the wheel for experience - I wanted to do it in C as well. Note: I'm sure that Erlang is not the only language that supports this; it just happens to be what I was reading recently.
Lets start with the interface that is exposed:
And two clients writing to that interface:
Client 1
Client 2
This driver is relatively crude. Notification of code change come by way of a signal and a well-known path indicates where the code resides. In addition, the mechanism for copying the structure of function pointers should reside in the driver itself and not in the clients. I think it is sufficient, however, to convey the idea.
And some implementation
With that setup we can now control the behavior of that driver at runtime. The example here runs the driver in it's own terminal and in another terminal commands are executed to load new code. The table below shows the execution in sequence - dynamic code execution in C.
To address the first point directly: function pointers are useful as a means to expose a standard set of functionality. Consider how a character device driver for the linux kernel operates, for instance. When you write a character device driver you are presented with a struct file_operations (fops).
struct file_operations {
struct module *owner;
loff_t (*llseek) (struct file *, loff_t, int);
ssize_t (*read) (struct file *, char *, size_t, loff_t *);
ssize_t (*write) (struct file *, const char *, size_t, loff_t *);
int (*readdir) (struct file *, void *, filldir_t);
/* ... lots of other calls ... */
};
Why? Consider what you do with a character device; read from it, write to it, and so on. But since each device requires it's own implementation there needs to be a way to indicate this within the module code.
One solution to this is to have a set of skeleton functions declared in a header file. Require that all modules include this file and provide definitions for the functions. There are two obvious drawbacks to this approach:
- Module writers are forced to fill in an empty body for all functions that will not be used
- Any changes to the interface require reimplementation of the entire set of modules using the now outdated file
Another solution is to use a structure that contains function pointers and allow developers to use that when writing to the interface. This solves the two issues with the skeleton declaration approach: any function not defined is set to nil in the structure and adding new members to the structure wont break existing code. Ok... if there is some fancy offset calculation being done there is potential for breakage, but that is suspect behavior in the first place.
Obviously removing entries creates compatibility issues in either solution.
Here is how the function pointer approach works in the linux kernel:
/* linux-2.6.37/drivers/i2c/i2c-dev.c:513 */
static const struct file_operations i2cdev_fops = {
.owner = THIS_MODULE,
.llseek = no_llseek,
.read = i2cdev_read,
.write = i2cdev_write,
.unlocked_ioctl = i2cdev_ioctl,
.open = i2cdev_open,
.release = i2cdev_release,
};
Where each of the i2cdev_* functions are defined locally to that file and any operations not defined in the struct are nil (aio_fsynch, for example).
That actually represents dynamic code loading in it's entirety. You can change the behavior of a system by loading modules at runtime. But that is in the kernel and not applicable in userland; what if we wanted to do that for a process we control? That is something that Erlang lets you do and - because I'm bent on reinventing the wheel for experience - I wanted to do it in C as well. Note: I'm sure that Erlang is not the only language that supports this; it just happens to be what I was reading recently.
Lets start with the interface that is exposed:
#ifndef JRB_DYNOPS__H__
#define JRB_DYNOPS__H__
/*
* Operations supported by our dynamic runtime:
* init: Initialize the new code
* speak: process strings in some way
* destroy: Cleanup code
*/
struct dynops {
void (*init)();
void (*speak)(const char *);
void (*destroy)();
};
/*
* Fill in the opeartions for a particular implementation
*/
void get_ops (struct dynops *);
#endif /*JRB_DYNOPS__H__*/
And two clients writing to that interface:
Client 1
#include <stdio.h>
#include <string.h>
#include "dynops.h"
static void lib1_speak (const char * text) {
fprintf (stderr, "[LIB1] %s\n", text);
}
/* only implements speak. Ignores init & destroy */
static struct dynops my_ops = {
.speak = lib1_speak,
};
void get_ops (struct dynops ** ops) {
memcpy(*ops,&my_ops,sizeof(my_ops));
}
Client 2
#include <stdio.h>
#include <string.h>
#include "dynops.h"
static void lib2_init () {
fprintf (stderr, "Initializing lib2\n");
}
static void lib2_destroy () {
fprintf (stderr, "Cleanup lib2\n");
}
static void lib2_speak (const char * text) {
fprintf (stderr, "[LIB2] %s\n", text);
}
static struct dynops my_ops = {
.init = lib2_init,
.speak = lib2_speak,
.destroy = lib2_destroy,
};
void get_ops (struct dynops ** ops) {
memcpy(*ops,&my_ops,sizeof(my_ops));
}
This driver is relatively crude. Notification of code change come by way of a signal and a well-known path indicates where the code resides. In addition, the mechanism for copying the structure of function pointers should reside in the driver itself and not in the clients. I think it is sufficient, however, to convey the idea.
int main () {
unsigned long count = 0;
char iteration[255] = {0};
signal (SIGUSR1, trigger_load);
while (1) {
snprintf (iteration, 255, "Iteration: %lu\n", ++count);
do_ops (iteration);
usleep (500000);
}
return 0;
}
And some implementation
void trigger_load (int sig) {
if (sig != SIGUSR1)
return;
FILE * new_lib = fopen("/tmp/dynlib", "r");
if (! new_lib)
return;
fscanf (new_lib, "%s", lib_name);
fclose (new_lib);
the_lib = lib_name;
reload = 1;
}
/* ... */
void do_ops (const char * str) {
if (reload) {
load_lib (the_lib);
reload = 0;
}
if (ops.speak)
ops.speak(str);
}
With that setup we can now control the behavior of that driver at runtime. The example here runs the driver in it's own terminal and in another terminal commands are executed to load new code. The table below shows the execution in sequence - dynamic code execution in C.
Terminal 1
$ ./a.out 'libops1.so' successfully loaded [LIB1] Iteration: 40 ... [LIB1] Iteration: 52 'libops2.so' successfully loaded Initializing lib2 [LIB2] Iteration: 53 ... [LIB2] Iteration: 62 Cleanup lib2 'libops1.so' successfully loaded [LIB1] Iteration: 63 ...
Terminal 2
$ pgrep a.out 5993 $ echo "libops1.so" > /tmp/dynlib $ kill -10 5993 $ echo "libops2.so" > /tmp/dynlib $ kill -10 5993 $ echo "libops1.so" > /tmp/dynlib $ kill -10 5993
Labels:
C
,
dynamic code execution
,
function pointer
Subscribe to:
Posts
(
Atom
)









