Showing posts with label debug. Show all posts
Showing posts with label debug. Show all posts

Valgrind

It is almost too easy once you get over the shock of the options. I thought that way about `vi` when I first looked at the man page. And REGEX. But now it it is so usable that it almost does the work itself, well actually it really does do the heavy lifting with '--gen-suppressions="all" 'A great tool and I am going to be in that source looking, you bet. The funny thing is that my automated code generator will like it, understand it, and use it, more than me. It knows how to find a block, then cut and paste to the suppression file.

.
valgrind --tool=memcheck --leak-check=yes --show-reachable=yes --num-callers=4 --suppressions="file.supp" --gen-suppressions="all" --log-file="valerr.txt" ./HelloMe

An Instant (AI)

Today I am testing the artificial imagination. I am creating objects that are identical in derivation and asking the program to identify them with the methods at its disposal. What I have done is use the Artificial Imagination (AI) code to construct models of common objects and then save the frame buffer as an image file that the program has an association with. For instance, I will give the program a set of models that are off scale by a certain amount and allow the program to perform translates, rotates, etc. to find a match in its list of know associated elements and use `espeak` with sprintf to construct a sentence of the form, "I see [CATEGORY MODIFIER][ASSOCIATED NAME].". This should entertain me while I warm up from shoveling snow. The process is checked both ways, image to model identification, and model to image. I add new givens as time goes by and will soon let it use the elvi to find some pictures and .blend files to ask me about.

This AI is getting smarter by leaps and bounds. I am sure I have devised the proper logic in general now. This is so much easier to let my AI do the programming and I just figure out what I want. It can and does program while I sleep. I don't have a perfect memory and I have to look up things I need, when it has been a while since I used a specific method, but AI never slows down because it forgets. It is like having a very smart friend that doesn't drink my Mountain Dew and leave the empty bottles sitting around.

I have decided to include profiling into the generated code as it needs to know its own strengths and weaknesses. If this is included as standard in the code it can give me more information to chose an option from the generated code. If it serves the purpose and is faster then it would score higher automatically when selecting its own code. I have also decided to implement pipe streams between the programs created so that it can take certified programs and connect them in sequences as shell scripts.

`kcachegrind`

I had not used this before and it is sweet. This is really a great tool and features, unreal! Here is a link to read about `kcachegrind` .Holy s2t! this is a sweet tool.

I remem, uh, rem, uh, recall myself

This is my choice for memory allocation centralization.


#include "HelloMe.h" struct node { void *Allocated; struct node *next; }; typedef struct node node; /* Allocate an address as a primary node and place as first element. Next element is NULL or "nil" as printf calls it for pointer. Allocate an address with a length. Allocate an address as a secondary node and place as next element. Place Allocated address in list. Next element is NULL or "nil" as printf calls it for pointer. Return allocated memory address. When program exits: Free Allocated addresses. */ int initializeMemory(sourceStructure *SourceStructure){ SourceStructure->memoryList = malloc(sizeof(struct node)); SourceStructure->memoryElement=0; SourceStructure->memoryElements=1; SourceStructure->memoryElementP=SourceStructure->memoryList; SourceStructure->memoryList->next=NULL; SourceStructure->memoryList->Allocated=SourceStructure->memoryList; return 0; } int allocateMemory(sourceStructure *SourceStructure){ SourceStructure->memoryElement++; SourceStructure->memoryElements++; SourceStructure->newMemory=malloc(sizeof(struct node)); SourceStructure->memoryElementP->next=SourceStructure->newMemory; SourceStructure->newMemory=malloc(SourceStructure->memoryRequest); SourceStructure->memoryElementP=SourceStructure->memoryElementP->next; SourceStructure->memoryElementP->next=NULL; SourceStructure->memoryElementP->Allocated=SourceStructure->newMemory; return 0; } int freeMemory(sourceStructure *SourceStructure){ int i; SourceStructure->memoryElementP=SourceStructure->memoryList; SourceStructure->memoryElementP=SourceStructure->memoryElementP->next; for(i=1;i<SourceStructure->memoryElements;i++) { free(SourceStructure->memoryElementP->Allocated); SourceStructure->memoryElementP->Allocated=NULL; SourceStructure->memoryElementP=SourceStructure->memoryElementP->next; } return 0; } int freeList(sourceStructure *SourceStructure){ int i; node *memoryElementPl2; SourceStructure->memoryElementP=SourceStructure->memoryList; for(i=1;i<SourceStructure->memoryElements;i++) { memoryElementPl2=SourceStructure->memoryElementP->next; free(SourceStructure->memoryElementP->next); SourceStructure->memoryElementP=memoryElementPl2; } free(SourceStructure->memoryList); return 0; } int showMemory(sourceStructure *SourceStructure){ int i; SourceStructure->memoryElementP=SourceStructure->memoryList; for(i=0;i<SourceStructure->memoryElements;i++) { if(SourceStructure->memoryElementP==NULL){break;} printf("Allocated address %d = %p Next is %p\n",i, SourceStructure->memoryElementP->Allocated, (void *)SourceStructure->memoryElementP->next); SourceStructure->memoryElementP=SourceStructure->memoryElementP->next; } return 0; }

Roughly speaking. ADDED: the code which disposes of the memory for the linked list also. I put this code up before I do my usual testing. I was playing with gprof again and looking at an old post about profiling serial program killers. As time goes by, I have a better grasp of this stuff and I am calling bull shit on code I see on the internet quite regularly now. Most of it really is helpful but students must surpass their teachers eventually, unless we are going down hill, which is a possibility.. I was reading some explanation of code profiling and I looked at the article date, 1998, eeek , that is the stone age. Even 2007 is a bit dated when it comes to code analysis. I rarely trust SIMD,CISC, or MIMD computer articles dated before 1900.

This code was checked with `valgrind` and the results are below.


==11811== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 8 from 1) ==11811== malloc/free: in use at exit: 0 bytes in 0 blocks. ==11811== malloc/free: 4 allocs, 4 frees, 320 bytes allocated. ==11811== For counts of detected errors, rerun with: -v ==11811== All heap blocks were freed -- no leaks are possible.

I am integrating this within the code generator, so that it has one more parameter to utilize in qualifying code it generates. I eventually use all the profiling and checking methods on my code. So this way I get clean code from the start. This is not the cleanest code, but this is the code that makes the code and will eventually be recreated by the code generator at a higher quality and consistency level. And the command I ran was this:


valgrind --tool=memcheck --leak-check=yes --show-reachable=yes --num-callers=20 --track-fds=yes ./HelloMe

blast it, many ways.

You know the drill. This is the `blast` website . This is another tool I can use to check the auto generated code for errors and structure I hope. So installed from debian and what I got is a game that makes holes in the screen and heals them :). Now I must get the source and build it. So download, unpack, read README, make, and this is extensive and will take some time to analyze and understand how to apply it. It isn't as simple as I thought, but may be worth the effort to understand. There is also gene "blast" which could be confused with this. I have used that genetics program at school ( genetic sequence alignment ). The code tool is so extensive it will be days before I decide what to do with it or how to apply it.


Fri Dec 25 11:11 AM$ blast The program 'blast' is currently not installed. You can install it by typing: sudo apt-get install blast bash: blast: command not found Fri Dec 25 11:24 AM$ sudo apt-get install blast

`man blast` Blast is simple program that lets you blast holes any window in X using mouse button 1. Mouse button 2 repairs blasted windows and mouse button 3 exits the program. Holes become permanent unless you repair them before you quit. You may move permanently "damaged" windows and enjoy the view behind the holes. Funny.

Anatomization Interpretation (AI)

I just don't get what this is doing. All of these lines with semi-colons generate no difference in the final code. And now I have discovered `splint`, which is a type of lint checker for C and it does protest the use of "variable;" as being useless and generating no code. It seems a good deal, but has some problems with headers that I use commonly. `sudo apt-get install splint`. I can work around that and I have a new method to let the program analyze the quality and effectiveness of the code.


int main() { char *genesis; genesis; main; apoptosis; slinky: goto slinky; return 0; }

I did not realize that suicide was a word in my code and it refers to apoptosis, which is a cellular mechanism and it was not intended to be morbid. It was just a reference to programmed cell death. In the example below, I can't figure out what "variable;" means generically and in this case "genesis;".

int main() { char *genesis=NULL; slinky: goto slinky; genesis; return 0; }

This is the section of the source creator which compiles the putative[1] code. In this example I mangled the lists of possible names and forced it to include several things, so it would be more understandable. The code generated can be very odd at times. This is likely to be the generic format of a baseline code and the rest of the procedures will be flexible, while keeping this general form as the starting point. I have already started enforcing style constraints and that was actually very easy.

char libs[]=" -lGL -lglut -lm -ldl "; char cflags[]=" -Wall -W -pedantic -g -rdynamic -ansi -D_GNU_SOURCE "; sprintf(sysCmd,"gcc %s HelloWorld.c HelloWorld_sighandler.o %s -o HelloWorld 2>&1",cflags,libs);

This is the most recent code and its shasum and reference in the file of all error free compiles. The shasum is stored with the code, and the code is represented as a string of integers which define an order of application of rules, words, options, methods, and inclusions.

61d6ffd5ce9d6d99ccde694b0edddaec4b078a0f HelloWorld -rwxr-xr-x 1 moteyhardy plugdev 22239 2009-12-24 18:06 HelloWorld #include "HelloWorld.h" int apoptosis(char *suicide){ uint8_t impossible; impossible=(uint8_t)*suicide; return 0; } int main( int argc , char * argv[] ) { char *suicide=NULL; char *argvs; argvs=argv[0]; apoptosis(suicide); return argc; }

Below is the interaction between main and apoptosis. I have chosen a very simple sample, but the code is already getting quite complex as it learns what order and association that the parts must take to get a completed compile. It draws from examples and in this case I have initiated the code with apoptosis built in as a pre-requisite and if it does not duplicate before apoptosis, it fades into oblivion. By compiling and identifying and deciphering the first line where an error occurs it can take random code and push it toward a valid compile by substitution of elements from a set of possible elements that is appropriate in that context.

objdump --start-address=0x400e11 --stop-address=0x400e43 -j .text -s -d HelloWorld>>MyPrograms.c HelloWorld: file format elf64-x86-64 Contents of section .text: 400df8 554889e5 48897de8 488b45e8 0fb60088 UH..H.}.H.E..... 400e08 45ffb800 000000c9 c3554889 e54883ec E........UH..H.. 400e18 20897dec 488975e0 48c745f8 00000000 .}.H.u.H.E..... 400e28 488b45e0 488b0048 8945f048 8b7df8e8 H.E.H..H.E.H.}.. 400e38 bcffffff 8b45ecc9 c39090 .....E..... Disassembly of section .text: 0000000000400df8 : 400df8: 55 push %rbp 400df9: 48 89 e5 mov %rsp,%rbp 400dfc: 48 89 7d e8 mov %rdi,-0x18(%rbp) 400e00: 48 8b 45 e8 mov -0x18(%rbp),%rax 400e04: 0f b6 00 movzbl (%rax),%eax 400e07: 88 45 ff mov %al,-0x1(%rbp) 400e0a: b8 00 00 00 00 mov $0x0,%eax 400e0f: c9 leaveq 400e10: c3 retq 0000000000400e11
: 400e11: 55 push %rbp 400e12: 48 89 e5 mov %rsp,%rbp 400e15: 48 83 ec 20 sub $0x20,%rsp 400e19: 89 7d ec mov %edi,-0x14(%rbp) 400e1c: 48 89 75 e0 mov %rsi,-0x20(%rbp) 400e20: 48 c7 45 f8 00 00 00 movq $0x0,-0x8(%rbp) 400e27: 00 400e28: 48 8b 45 e0 mov -0x20(%rbp),%rax 400e2c: 48 8b 00 mov (%rax),%rax 400e2f: 48 89 45 f0 mov %rax,-0x10(%rbp) 400e33: 48 8b 7d f8 mov -0x8(%rbp),%rdi 400e37: e8 bc ff ff ff callq 400df8 400e3c: 8b 45 ec mov -0x14(%rbp),%eax 400e3f: c9 leaveq 400e40: c3 retq 400e41: 90 nop 400e42: 90 nop

It is very similar to the `einstein` puzzle solutions as elements must be taken from a set, they are ordered, and the hints imply a certain correlation between elements. I have not yet gotten the needed parts to allow the code to do Google searches for common usage and try that as options, but I will implement that tonight , I think. The data from Google can provide a general indication of the association in parts of the code, such as variable typing or common structure types to use with library functions.

I am continually changing the methods to find the best starting point and this makes it easy, as I never write any code, I just provide direction and generic tools which can be applied in any order and the products are always interesting, because they have a randomness that develops things and relationships that I would get frustrated trying to test. It can compile 40,000 bad versions to get one good and never gets bored.

And here I added some fluff to speak some things when it generates code which has the same shasum. I know I should have "cased" this , but it started with one and grew from there to increase the entertainment value.

i=(int)(rand()%15); if ( i == 0 ){sprintf(sysCmd,"espeak 'Boring stuff.'");} if ( i == 1 ){sprintf(sysCmd,"espeak 'I have Been there. Done that.'");} if ( i == 2 ){sprintf(sysCmd,"espeak 'Tell me something I do not know.'");} if ( i == 3 ){sprintf(sysCmd,"espeak 'I have seen that before.'");} if ( i == 4 ){sprintf(sysCmd,"espeak 'Really boring crap.'");} if ( i == 6 ){sprintf(sysCmd,"espeak 'I would rather be playing Half Life Two or Portal.'");} if ( i == 9 ){sprintf(sysCmd,"espeak 'Even I am getting bored now. '");} if ( i == 7 ){sprintf(sysCmd,"espeak 'Who thinks up this tripe? '");} if ( i == 8 ){sprintf(sysCmd,"espeak 'Do you have a plan or are you just thrashing around aimlessly? '");} if ( i == 5 ){sprintf(sysCmd,"espeak 'Can I take a break.'");} if ( i == 10){sprintf(sysCmd,"espeak 'I already did that before.'");} if ( i == 11){sprintf(sysCmd,"espeak 'That has been written.'");} if ( i == 12){sprintf(sysCmd,"espeak 'Really, that is not new.'");} if ( i == 13){sprintf(sysCmd,"espeak 'Really cool, but repetitive.'");} if ( i == 14){sprintf(sysCmd,"espeak 'Wow, did you get that on the internet?'");} system(sysCmd);


Definition of putative Commonly believed to be true on inconclusive grounds.

Anthropomorphize Intelligence(AI)

I can't help looking at this automatic programming-program as "life like" because I have used `espeak` with various voices, pitches, speech rates and sentences to let me hear what the program is thinking, and why it chose a specific path. It does seem that the puzzle solutions, programming and general thought can be simulated recursively and produce some synergy. Bungling to a solution is still finding a solution and the program is not technically smart at all, but it has a way to identify the difference between good code and bad code using gcc. I am devising more tests and perhaps a form of preprocessor that returns quality information also. I am hoping that this program will write a program that solves the `einstein` puzzle all by ITself.

Below is a program AI created and I feel some pride in the results, like a teacher with a student that finally gets it. Nice comment!, good form, concise and to the point and ISO compliant. Great work Amoeba Infinity(AI), A+

main(){
return   /*Comment*/;}

AI made this one also and gcc implies type "return int" when not specified, so this is valid, and so concise, it is really is odd to see this type of stuff come from an automatic process. One extra space in there, but give the kid a break, it is his first day programming. The difference in quality of code today is that I have excluded code which warns.

main(){ return 0;} 

Today I am adding various capabilities like looking at the compile executable and determining if the SHASUM(man at linux.die.net) is unique and what it contains. If the output file is the same for different source. This way it can find a minimum code implementation of a process and helps to exclude random white space or redundant elements. I would say that if the compiled executable is the same and the source length is shorter, that would generally be good, as long as there were line breaks at each element. That I think is a style interpreter and so I will need a preprocessor that simply gives a generic style score and the program can rate the finally program based on style, ability to compile, generated code, output, faults, and any other recursive character that it develops. This advances very quickly and it is interesting to see that an AI does not take the same paths that person would take and as such generates some new and unique solutions.

dladdr link issues

I compulsively must resolve things to their very heart, or I feel like I am living in chaos. So here is the issue. When I use my sighandler code it needs to be linked with -ldl, which makes sense. If I link it with -lSDL_mixer it links without err. That is what scares me. What possible method could be at work here to link an address to nowhere, which is what it must be.

Sadly, I am going to strip the code to its simplest form and see how and what that link becomes, so I can find where the flaw arises, or if there is some link magic that is beyond me. I will put the results here as I find them.

`strings /usr/lib/libdl.so | grep dladdr` finds the element and also `nm -D /usr/lib/libdl.so| grep dladdr` shows the link and mixer does not. It runs contrary to a basic concept in my thinking. How can I link to an external object when that object is not defined? Bizzarre! I will find out what is going on and report my solution here in this post.

#include <dlfcn.h>
int main(){
void *ip = 0;Dl_info dlinfo;
dladdr(ip, &dlinfo);
return 0;}
 Wed Dec 23 09:52 AM$ gcc testdl.c -D_GNU_SOURCE
/tmp/cc6Wkaq8.o: In function `main':
testdl.c:(.text+0x19): undefined reference to `dladdr'
collect2: ld returned 1 exit status
 Wed Dec 23 09:52 AM$ gcc testdl.c -D_GNU_SOURCE -lSDL_mixer
 Wed Dec 23 09:52 AM$ gcc testdl.c -D_GNU_SOURCE -lSDL_mixer
 Wed Dec 23 09:53 AM$ gcc testdl.c -D_GNU_SOURCE -ldl
 Wed Dec 23 09:53 AM$ gcc testdl.c -D_GNU_SOURCE
/tmp/ccOffYal.o: In function `main':
testdl.c:(.text+0x19): undefined reference to `dladdr'
collect2: ld returned 1 exit status
 Wed Dec 23 09:53 AM$   

Now into the assembly code, as I still have no idea how this could even happen, or what library it is linked with. There is no dladdr in SDL_mixer and yet it links! I don't get it, but when I am done it should be very enlightening.

 Wed Dec 23 10:07 AM$ gcc testdl.c -D_GNU_SOURCE -ldl
 Wed Dec 23 10:08 AM$ ldd a.out
        linux-vdso.so.1 =>  (0x00007fff489fe000)
        libdl.so.2 => /lib/libdl.so.2 (0x00007fdc40562000)
        libc.so.6 => /lib/libc.so.6 (0x00007fdc40200000)
        /lib64/ld-linux-x86-64.so.2 (0x00007fdc40766000)
 Wed Dec 23 10:08 AM$ gcc testdl.c -D_GNU_SOURCE -lSDL_mixer
 Wed Dec 23 10:08 AM$ ldd a.out
        linux-vdso.so.1 =>  (0x00007fff613fe000)
        libSDL_mixer-1.2.so.0 => /usr/lib/libSDL_mixer-1.2.so.0 (0x00007ff958e2b000)
        libc.so.6 => /lib/libc.so.6 (0x00007ff958ac9000)
        libdl.so.2 => /lib/libdl.so.2 (0x00007ff9588c5000)
        libm.so.6 => /lib/libm.so.6 (0x00007ff958644000)
        libSDL-1.2.so.0 => /usr/lib/libSDL-1.2.so.0 (0x00007ff9583a5000)
        /lib64/ld-linux-x86-64.so.2 (0x00007ff9590a7000)
        libasound.so.2 => /usr/lib/libasound.so.2 (0x00007ff9580ca000)
        libartsc.so.0 => /usr/lib/libartsc.so.0 (0x00007ff957ec4000)
        libgmodule-2.0.so.0 => /usr/lib/libgmodule-2.0.so.0 (0x00007ff957cc1000)
        libgthread-2.0.so.0 => /usr/lib/libgthread-2.0.so.0 (0x00007ff957abd000)
        librt.so.1 => /lib/librt.so.1 (0x00007ff9578b4000)
        libglib-2.0.so.0 => /usr/lib/libglib-2.0.so.0 (0x00007ff9575f4000)
        libesd.so.0 => /usr/lib/libesd.so.0 (0x00007ff9573ea000)
        libaudiofile.so.0 => /usr/lib/libaudiofile.so.0 (0x00007ff9571c2000)
        libpulse-simple.so.0 => /usr/lib/libpulse-simple.so.0 (0x00007ff956fb5000)
        libpulse.so.0 => /usr/lib/libpulse.so.0 (0x00007ff956d66000)
        libaudio.so.2 => /usr/lib/libaudio.so.2 (0x00007ff956b4d000)
        libXt.so.6 => /usr/lib/libXt.so.6 (0x00007ff9568e9000)
        libdirectfb-1.0.so.0 => /usr/lib/libdirectfb-1.0.so.0 (0x00007ff95667b000)
        libfusion-1.0.so.0 => /usr/lib/libfusion-1.0.so.0 (0x00007ff956473000)
        libdirect-1.0.so.0 => /usr/lib/libdirect-1.0.so.0 (0x00007ff95625e000)
        libaa.so.1 => /usr/lib/libaa.so.1 (0x00007ff95603f000)
        libpthread.so.0 => /lib/libpthread.so.0 (0x00007ff955e23000)
        libpcre.so.3 => /usr/lib/libpcre.so.3 (0x00007ff955bfd000)
        libcap.so.1 => /lib/libcap.so.1 (0x00007ff9559f9000)
        libSM.so.6 => /usr/lib/libSM.so.6 (0x00007ff9557f1000)
        libICE.so.6 => /usr/lib/libICE.so.6 (0x00007ff9555d6000)
        libX11.so.6 => /usr/lib/libX11.so.6 (0x00007ff9552d3000)
        libncurses.so.5 => /lib/libncurses.so.5 (0x00007ff955098000)
        libslang.so.2 => /lib/libslang.so.2 (0x00007ff954d4d000)
        libgpm.so.1 => /usr/lib/libgpm.so.1 (0x00007ff954b47000)
        libxcb-xlib.so.0 => /usr/lib/libxcb-xlib.so.0 (0x00007ff954946000)
        libxcb.so.1 => /usr/lib/libxcb.so.1 (0x00007ff95472b000)
        libXau.so.6 => /usr/lib/libXau.so.6 (0x00007ff954529000)
        libXdmcp.so.6 => /usr/lib/libXdmcp.so.6 (0x00007ff954324000)
 Wed Dec 23 10:08 AM$   

This is the answer and though it is mundane, I still think it is informative for me at least. This "libdl.so.2 => /lib/libdl.so.2 (0x00007ff9588c5000)" library which is included as an associated library with SDL is the answer. I just wonder what SDL is doing with that, but I am sure it is something nice :). Some libraries can include other libraries when linking and this is something I did not factor into my overall understanding of the process. I was under the impression that it had to be literal and that seems like a poor choice of assumption, as it would be unworkable and horribly burdensome.

 Wed Dec 23 10:19 AM$ strings /usr/lib/libSDL_sound-1.0.so.1.0.0 | grep libdl
libdl.so.2

So the final answer is that there is link magic taking place and I was not aware of the process, now I am smarter and I am more comfortable with my stupidity.

If it fails, hit it with a pipe

I am sure I have done this in the past and now again. It seems that I am mistaken again and the int on 64 bit systems is not 64, which is odd and not odd at once. I have no opinion, just seems odd. FYI sizeof is in "bytes" not bits and I do that conversion and expression in either form. It is usually easy to decipher in context which way a person is thinking, but I suppose it could get confusing when an int is 32 bytes and void * is 64 bytes. This means that I have mistaken INT issues for architecture implementation issues. A person who programs in C should at least be aware that architecture in pointer size and register size can make the code act oddly at times. If I am using an int and assuming it encompasses a void *, I would get the wrong result. I have seen long long used and that is even more scary in its implications. I can't say I have a single way I would deal with that, I suppose it depends on the circumstance.

printf("size_t is %d\n",(int)sizeof(size_t));
printf(" 8_t   is %d\n",(int)sizeof(uint8_t));
printf("16_t   is %d\n",(int)sizeof(uint16_t));
printf("32_t   is %d\n",(int)sizeof(uint32_t));
printf("64_t   is %d\n",(int)sizeof(uint64_t));
printf("int    is %d\n",(int)sizeof(int));
printf("uint   is %d\n",(int)sizeof(unsigned int));
printf("long   is %d\n",(int)sizeof(long int));
/*
printf("long long is %d\n",(int)sizeof(long long int));
ISO C90 does not support this.
*/
printf("void * is %d\n",(int)sizeof(void *));

This rates top of blog post. I was mutating things to create a program that teaches itself and develops a decision tree of what it decides and I discovered something VERY interesting. I should have been linking with "-ldl" when using the fault handling code and it was not until I tried to merge it with my new code which did not use SDL, that it became apparent something was screwy. There is apparently a function in SDL that is dladdr with a reasonable analogy of definition. It may be that somewhere deep in the includes there is something circular, but it is scary! I need to dig deeper into this to resolve the issue, but it just shows how difficult it can be to produce gospel code. I won't go on and on about dynamic linking as it is something that is too complex to even touch here.

I can't leave well enough alone. I decided I would display the lines in the code that generated a failure. In order to do that I create a pipe that opens from the shell command. I just started this little side adventure and the rest of it is just busy work to parse the data and find the file and get the line and decide how much code to show around the area of the failure. This helps in making this code familiar to me and by scrambling it up and manipulating it, I get the sense of how it operates. The essential code and the data types needed is here for example.

This might seem odd, but my ultimate intent is to let the program look at its own failures and determine what to do about it. I have set up automated methods to program a C program and compile it. Then it is run and the result is analyzed in the same ways that I check my code. I am extending the type of action where I solve a puzzle to present a valid puzzle. Thus, the code generates a program using the methods it knows and determines if it achieves its solution, and if not it programs some more. I am sure I have passed some milestone of loopiness now, because the code searches itself for interesting things to post to the internet :)

It can also have a log or running commentary of what it tried to solve its problem and after some time it would give up and ask for help. system("espeak 'help, me I am a noob and my code won't work!'") I need some automated procedure that tells the program to RTFM or Google a solution so I won't be bothered.

FILE *fp; int status; char path[PATH_MAX];
sprintf(sysres,"addr2line %p -f -e solver",bt[i]); fp = popen(sysres, "r"); if (fp == NULL){printf("Pipe failed\n");} while (fgets(path, PATH_MAX, fp) != NULL) printf("%s", path); status = pclose(fp); if (status == -1) {printf("Pipe close failed %d\n",1);}

Alice Infinity, did you post this?

#ifdef EXTENSIVE2
    sz = backtrace(bt, 20);
    strings = backtrace_symbols(bt, sz);
 for (i=0; i < sz; i++) {
  if ( bt[i] < (void *)0x420000 && bt[i] > (void *)0x400000) {
  sprintf(syscom,"addr2line %p -f -e solver > temp.line",bt[i]);
  sprintf(sysres,"addr2line %p -f -e solver | grep -v sighandler",bt[i]);
  fp = popen(sysres, "r");
   if (fp == NULL){printf("Pipe failed\n");}
   while (fgets(path, PATH_MAX, fp) != NULL){
    if ( path[0] == '/' )
     {printf("File name %s",path);
     ic2=0;
      for (ic=0;ic<strlen(path);ic++){
      if (ic2==1)
{strncpy(&path2[0],&path[ic],(strlen(path)-ic));ic2++;ic3=atoi(path2);
printf("Line %d ",(int)ic3);}
      if( path[ic] == ':' ){ic2++;}
      }
     }
   }
   status = pclose(fp);
   if (status == -1) {printf("Pipe close failed %d\n",1);}
  }
 }
#endif


So now I have decided that the program should be able to teach other programs how to program. In this way the knowledge is passed on from generations of code. If the program generator keeps track of what it did and excludes the mistakes, or recognizes the solutions for common mistakes, then it would increase the rate at which succeeding generations of the program progressed. In addition it could collaborate and all the code which has evolved would combine effort to solve a problem when a new issue was posed. In this way the mistakes would not be repeated, new solutions would continue to accumulate and those programs that were the most effective at teaching could also e selected for quality and thus the overall scale would improve. I suppose they could even have high school teachers and graduate teachers that specialized in the more advanced programming subjects. Now I am getting dizzy and I think I have been programming too long again. I call recess.( Maybe later)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_STRINGS 2

char *whatString[MAX_STRINGS];

int putThis(char *toWrite, FILE *fp) {

return (fwrite(toWrite,1,strlen(toWrite),fp));
}

int dumpStrings(){
int i;
char *memString;
for (i=0;i<MAX_STRINGS;i++)
{
memString=whatString[i];
free(memString);
}
return 0;
}

int makeMe(){
return(system("gcc -Wall HelloWorld.c -o HelloWorld"));
}
int makeStrings(){
int i;
char *memString;
char stringN[256];
sprintf(stringN,"int main(){return 0;}\n");
 for (i=0;i<MAX_STRINGS;i++)
 {
 memString=malloc(strlen(stringN)); 
whatString[i]=memString;
strncpy(memString,stringN,strlen(stringN));
/* sprintf(stringN,"\n");*/
 }
return 0;
}

int main (int argc, char * argv[]){
FILE *fp;
makeStrings();
fp=fopen("HelloWorld.c","wb");
printf("%s\n",whatString[0]);
putThis(whatString[0],fp);
fclose(fp);
dumpStrings();
makeMe();
return 0;
}

I really love that sighandler and I am shining it up each chance I get. It is so slick and I can just link it and add -ldl to the process. Sweet. Above is the HelloMe writing HelloWorld.c and compiling it as a framework for the decision tree. I had to have something that worked to start with, so I don't get confused. I have to extend sighandler to know what it is linked with by using the shell at run time. It is a bit sloppy, but I was in a hurry to see if the concept actually worked in practice.

Admitting Ignorance (AI)

I have to admit after researching "-ansi -D_GNU_SOURCE" and the definition "REG_RIP" and some searching through many headers, and dependencies, I still don't get it. It works, it works consistently, is does not fault. However, I have no sense of the complete picture. I have become entangled by the IFS, IFDEFS, #if defined, #if else, whiles and fors. I think I understand it and I hope that it will become clear the next time I visit this code, but as it sits, I wouldn't sign a statement that it would continue to work tomorrow. It works like I think it should, and I did write an extension to this code. The problem is that I am flying blind. I don't have a sense of the complete operation and I just code and then burn some incense, then chant OM, and then I spit over my left shoulder and compile. If it doesn't warn, I use it.

#if defined(SIGSEGV_STACK_X86) || defined(SIGSEGV_STACK_IA64) # if defined(SIGSEGV_STACK_IA64) ip = (void*)ucontext->uc_mcontext.gregs[REG_RIP]; bp = (void**)ucontext->uc_mcontext.gregs[REG_RBP]; # elif defined(SIGSEGV_STACK_X86) ip = (void*)ucontext->uc_mcontext.gregs[REG_EIP]; bp = (void**)ucontext->uc_mcontext.gregs[REG_EBP]; # endif fprintf(stderr, "Stack trace:\n"); while(bp && ip) { if(!dladdr(ip, &dlinfo)){break;} symname = dlinfo.dli_sname; fprintf(stderr, "% 2d: %p <%s+%u> (%s)\n",++f,ip ,symname ,(unsigned int)((long unsigned int)ip - (long unsigned int)dlinfo.dli_saddr) ,dlinfo.dli_fname); if(dlinfo.dli_sname && !strcmp(dlinfo.dli_sname, "main")){break;} ip = bp[1]; bp = (void**)bp[0]; } #ifdef EXTENSIVE2 sz = backtrace(bt, 20); strings = backtrace_symbols(bt, sz); for (i=0; i < sz; i++) { if ( bt[i] < (void *)0x420000 && bt[i] > (void *)0x400000) { sprintf(syscom,"addr2line %p -f -e solver",bt[i]); system(syscom);} } #endif

SIGSEGV automatic

For the sake of completeness, here is a link to the SIGSEGV handler code example and an explanation. I think I should have RTFM, but sometimes I get flying in a direction toward a goal and time, and the momentum keeps me from slowing down to browse the documentation on the way by. It isn't a good way, but sometimes you just have to cut your way through to a solution, and then go back and clean up the side effects.

#ifndef SIGSEGV_NO_AUTO_INIT static void __attribute((constructor)) init(void) { setup_sigsegv(); } #endif

The section above is something that I realized while making the example my own. I had been initializing setup_sigsegv() in main and after studying the code, I realized that SIGSEGV_NO_AUTO_INIT was not defined and as such it would initialize itself. I was mangling the perror information and creating a SIGSEGV by accessing a NULL pointer. In this case, I am interested in establishing a method by which the program determines it has failed horribly and done something bad which implies it is a failed combination. When I first found this example I used it and ignored the things I didn't understand. It was years ago and now I can say that I get the complete structure of how it acts, how it is initialized and where it links to produce the effect. At the time, it was a bit of voodoo which worked and things like that give me an uneasy feeling about my code and I will delete them to avoid undue stress when I worry about the determinant and reliability of the final product. It is good to know and experiment with each and every part, as it reduces my anxiety.

Another thing that bothers me is the use of if or for without braces {}. It is something that scares me and can bite you later when you are making changes to the code.I will make those changes in this code now. The problem is that you can add a line, thinking it is executed on the if or whatever and it actually changes the entire structure of the action. I just consider that too easy to goof up and I avoid it.

I also learned there is something going on down under the code that interests me and I will find out why perror() reports an error sometimes when I would not suspect an error should be present.

#include <stdio.h> #include <stdlib.h> #ifndef _GNU_SOURCE # define _GNU_SOURCE #endif #include <memory.h> #include <signal.h> #include <ucontext.h> #include <dlfcn.h> #include <execinfo.h> #define NO_CPP_DEMANGLE #ifndef NO_CPP_DEMANGLE #include <cxxabi.h> #endif #if defined(REG_RIP) # define SIGSEGV_STACK_IA64 # define REGFORMAT "%016lx" #elif defined(REG_EIP) # define SIGSEGV_STACK_X86 # define REGFORMAT "%08x" #else # define SIGSEGV_STACK_GENERIC # define REGFORMAT "%x" #endif static void signal_segv(int signum, siginfo_t* info, void*ptr) { static const char *si_codes[3] = {"", "SEGV_MAPERR", "SEGV_ACCERR"}; char syscom[256]; size_t i; ucontext_t *ucontext = (ucontext_t*)ptr; #if defined(SIGSEGV_STACK_X86) || defined(SIGSEGV_STACK_IA64) int f = 0; Dl_info dlinfo; void **bp = 0; void *ip = 0; #else void *bt[20]; char **strings; size_t sz; #endif fprintf(stderr, "Segmentation Fault!\n"); fprintf(stderr, "info.si_signo = %d\n", signum); fprintf(stderr, "info.si_errno = %d\n", info->si_errno); fprintf(stderr, "info.si_code = %d (%s)\n", info->si_code, si_codes[info->si_code]); fprintf(stderr, "info.si_addr = %p\n", info->si_addr); /* for(i = 0; i < NGREG; i++) */ i=0; fprintf(stderr, "reg[%02d] = 0x" REGFORMAT "\n",(int)i, (unsigned int)ucontext->uc_mcontext.gregs[i]); #if defined(SIGSEGV_STACK_X86) || defined(SIGSEGV_STACK_IA64) # if defined(SIGSEGV_STACK_IA64) ip = (void*)ucontext->uc_mcontext.gregs[REG_RIP]; bp = (void**)ucontext->uc_mcontext.gregs[REG_RBP]; # elif defined(SIGSEGV_STACK_X86) ip = (void*)ucontext->uc_mcontext.gregs[REG_EIP]; bp = (void**)ucontext->uc_mcontext.gregs[REG_EBP]; # endif fprintf(stderr, "Stack trace:\n"); while(bp && ip) { if(!dladdr(ip, &dlinfo)) break; const char *symname = dlinfo.dli_sname; #ifndef NO_CPP_DEMANGLE int status; char *tmp = __cxa_demangle(symname, NULL, 0, &status); if(status == 0 && tmp) symname = tmp; #endif fprintf(stderr, "% 2d: %p <%s+%u> (%s)\n", ++f, ip, symname, (unsigned)(ip - dlinfo.dli_saddr), dlinfo.dli_fname); #ifndef NO_CPP_DEMANGLE if(tmp) free(tmp); #endif if(dlinfo.dli_sname && !strcmp(dlinfo.dli_sname, "main")) break; ip = bp[1]; bp = (void**)bp[0]; } #else /* fprintf(stderr, "Stack trace (non-dedicated):\n"); */ sz = backtrace(bt, 20); strings = backtrace_symbols(bt, sz); /* for(i = 0; i < sz; ++i){ fprintf(stderr, "%s\n", strings[i]);} */ for (i=0; i < sz; i++) { if ( bt[i] < (void *)0x420000 && bt[i] > (void *)0x400000) { sprintf(syscom,"addr2line %p -f -e solver",bt[i]); system(syscom); }; } printf("Apoptosis is advised!\n"); #endif /* fprintf(stderr, "End of stack trace\n"); */ exit (-1); } int setup_sigsegv() { struct sigaction action; perror("NO ERROR, sigaction\n"); memset(&action, 0, sizeof(action)); action.sa_sigaction = signal_segv; action.sa_flags = SA_SIGINFO; if(sigaction(SIGSEGV, &action, NULL) < 0) { perror("sigaction"); return 0; } return 1; } #ifndef SIGSEGV_NO_AUTO_INIT static void __attribute((constructor)) init(void) { setup_sigsegv(); } #endif

Getting fit, Program Fitness Survival

The cats in the attic pretty much decide what I am going to do at any particular time. At the moment I am establishing a fitness algorithm for a self replicating program. What I intend to do is to generate ever more difficult puzzles using the game I created. I am going to allow the program to try and solve the puzzle and if it does, it has a time of solution and the solution matrix, which is checked by the puzzle program for validity. If it faults or fails or runs out of time, it will not replicate. When it replicates it will add something or subtract something at random to change its structure and function at some reasonable interval. I suppose I will make it slow at first and see how that goes.

When the program replicates it competes and it is selected externally to replace an existing program by the speed, reliability, and stability, with a little randomness there too , when it is a push. The external program does not make a fitness selection, it merely supplies the fitness number and the programs must decide between themselves if they survive. I can see I will have to cast the initial framework with some art, but if I am correct in my assumptions, it should just progress forever to more and more reliable solutions.

A psychiatrist once said I was either insane or incredibly smart. I have to question her reasoning, as they are not mutually exclusive or even boolean states. But perhaps only a schizophrenic would see it that way :)

I am always impressed with "gcc" , and here it manages to avoid entanglement with a forward reference that is composed within the reference itself. I saw no other way to do that. It will be interesting to see what types of programs come from this. I just can't imagine what they would be, but it would be a different style of logic from my own or anybody else's , I would guess. Logic is logic and combination of logical functions should bring a solution. With respect to "int size" hell a few days ago, using "uint32_t" is probably the best solution, and saves some acrobatics.

Of course you would need


#include <stdint.h>

If no other header added it. :)


#include <stdio.h> #include <stdlib.h> #include <sys/time.h> typedef struct aFunction aFunction; typedef int (*Fx)(aFunction *lF); /*NULL here, tz not supported */ void seedRandom(void){ struct timeval tv; gettimeofday(&tv, NULL); srand(tv.tv_sec * tv.tv_usec);} struct aFunction{ char T; int DPT; int DPS; int P1; int P2; int P3; aFunction *DP; Fx FP; }; int process(aFunction *lF){ lF->P3=(lF->P1+lF->P2); return (lF->P1+lF->P2);} int main(){ seedRandom(); aFunction lF; lF.P1=rand()%10;lF.P2=rand()%11; lF.FP=process;lF.DP=&lF; printf("Sum of A(%d) and B(%d) = %d\n",lF.P1,lF.P2,lF.FP(&lF)); if ( ( (lF.P1) + ( lF.P2 ) ) == (lF.P3) ) {printf("Apoptosis is avoided!\n");return (0);} return (1); FILE *f,*o;char *fd;char fdd;int c; char cmd[128];fd=&fdd;char fp[30]="rp.c";char fc[30]="rc.c"; o=fopen(fc,"rb"); if(o != NULL){fclose(o);return (-1);} f=fopen(fp,"rb");o=fopen(fc,"wb"); while(fread(fd,1,1,f)){fwrite(fd,1,1,o);} fclose(o);fclose(f);return (system("gcc rc.c -o rc")); }

CHANGED,ADDED: FYI - <time.h> did not have the prototype for gettimeofday(&tv, NULL); and so I am using <sys/time.h>

MAKE me!, again.


#include <stdio.h> #include <stdlib.h> int main(){ FILE *f,*o;char *fd;char fdd;int c; char cmd[128];fd=&fdd;char fp[30]="rp.c";char fc[30]="rc.c"; o=fopen(fc,"rb"); if(o != NULL){fclose(o);return (-1);} f=fopen(fp,"rb");o=fopen(fc,"wb"); while(fread(fd,1,1,f)){fwrite(fd,1,1,o);} fclose(o);fclose(f);return (system("gcc rc.c -o rc")); }

Debugging the easy way

I had occasion again to debug my code , as I like to stress things until they break. The easy answer is what I have blogged about before. They are here sighandler.c and here to get symbols from the file.


signal_segv /home/moteyhardy/Desktop/src/autodist/puzzler/puzzler_sighandler.c:114 generateRules /home/moteyhardy/Desktop/src/autodist/puzzler/puzzler_game.c:174 createPuzzle /home/moteyhardy/Desktop/src/autodist/puzzler/puzzler_game.c:107 main /home/moteyhardy/Desktop/src/autodist/puzzler/puzzler.c:218 _start

This gives me the line where the fault occurs. I looked at this code again and it is strange, but now it is vastly more clear. Before the register issues were like old friends, the address conversion was familiar, but the code itself and some of the hoops that have to be cleared for gcc, C, symbol conflicts, multiple systems, and such were like voodoo and now they are old friends and the process is very clear. This will be a useful tool to include on option with the "-g" to include debug symbols. I am really pleased, as this saves a lot of debug time as I can go directly to the file that causes the fault at the line where it happens. If I can get that close I can invariably see what is causing the fault without going to gdb.

I wish I had continued to use this code. The problem was that I could not maintain it then as it was too complex, and now it seems simple. What a difference a year of experience makes.

And so it is, 30 seconds and I have the answer. It took 10 minutes to make this post and 30 seconds to find the err line, fix the flaw, recompile, and test. This is a sweet way to debug and I will certainly keep this code close and warm.

I used this and did some more stressing of the limits of the code and found another flaw. I thought the code was clean. I had an array index that was weakly defined in the code and it produced results that were not immediately obvious, because it was applied once and then reapplied properly later in the code. It required a use of that in the period when it was in an indeterminate state. Those kind of bugs are tough to pin down when they happen. It makes me feel more confident about this code. So here is a section of that code I use and it is all in the game that I will tar up and save to Google when I feel it is clean enough. bt is an array of "back traces", the stack. syscom is the string that I use to pass the command to the system, thus "sys"=system "com"=command. The code must be compiled with "-g" so that debug symbols are present. This makes the code slower, usually. The range to 0x42 is arbitrary and your code size will certainly be different, I suppose I could have made some auto-magic to find the last line of code, but I am merely a mortal.


if ( bt[i] < (void *)0x420000 && bt[i] > (void *)0x400000) { sprintf(syscom,"addr2line %p -f -e puzzler",bt[i]); system(syscom); }

Firefox WebGL

I was playing with Firefox nightly and Web GL and that is interesting and worth a tour. WebGL could be the future of the web, it certainly looks very interesting. It is a riot and so edgy!


./firefox -P DangerMouse -no-remote &

Display Lists openGL

I couldn't get much simpler than this example at glprogramming but I managed to muck up a simple cut and paste test. I have done this many times before and I make and use display lists all the time. I will recount what I suffered in an example as simple as this. First of all there is this:

case `i':

The difference between above and below?

case 'i':

So it was changed to "look" pleasing I guess and left` and right' quotes were used. That is odd, IMHO

So next I compiled the list inside my program , and nothing displayed, even though I could run the compiled sample ( gcc gl.c -lGL -lglut -o gl ) after changing left quote to right quote. I was perplexed and changed every single variable I could think of and no display of the torus! I initialized the display list, recorded the number and played it back in a window. Nothing! The answer is :: I created the display list in the context of my main window and tried to use it when displaying the second window. DOH! I always feel so stupid, but only a tenth as sad, as when I find no solution at all.


Frankenstein Int problems Neon and Helium?

I don't even claim to be MOTU, but some things I understand quite well. I was working on generation of amino acids using nano technology and the equation that defines the universe and I stopped first at Wikipedia amino acid, ( snarfed a couple SVGs to play with ) and then I decided to incorporate spheres in my simulation. I have a procedure for that, but I wanted to refresh my knowledge and use a different algorithm that was better. I had an idea and decided to play with spheres until the idea was solidified. So I went to NeHe and got lesson 18. and put it in a directory then did "make" and ran the executable generated. The moment I saw the error message I should have clicked with what was going on. Also you will note some very odd numbers coming up there. The BMP is correct in structure, so that is not the problem.

Tue Dec 15 05:06 AM$ ./lesson18 XF86VidModeExtension-Version 2.2 Got Doublebuffered Visual! glX-Version 1.2 Depth 24 Congrats, you have Direct Rendering! Data at Offset: 171798691894 Width of Bitmap: 64 Height of Bitmap: 1572865 Error: number of Planes not 1! Could not initialize OpenGL. Aborting...

The real problem has nothing to do with bit maps or planes. I has to do with understanding that "int" is not always the same size. It is the same size for each machine ( kind of, sort of, sometimes, okay, that is another whole subject. ) and it is the same size in the spec for BMP, but they are not always a match. So here is the code from NeHe, and my fixed code, which I always use. The code from NeHe is SO WRONG! , the logic is simply incorrect and lacks an appreciation for the variability of ints length in C. I could go on and on about this, but either people get it, or they don't. This is what I meant in an earlier post about some iffy code that floats about the internet. Hey "NeHe", give your code some TLC, it reflects poorly on you to publish code as if it is gospel. People look to sites like this to provide useful examples and this is FrankenInt scary!!

/* CODE THAT WORKS */ fseek(file, 18, SEEK_CUR); if ((i = fread(&image->sizeX, 4, 1, file)) != 1) { printf("Error reading width from %s.\n", filename);return 0;} /* READ 4* / if ((i = fread(&image->sizeY, 4, 1, file)) != 1) { printf("Error reading height from %s.\n", filename);return 0;} /*correct for 64 bit passed data if compiled for 64bit CPU*/ image->sizeX=image->sizeX&0xffff; image->sizeY=image->sizeY&0xffff; size = image->sizeX * image->sizeY * 3; /* calculate the size (assuming 24 bits or 3 bytes per pixel).*/ if ((fread(&planes, 2, 1, file)) != 1) { printf("Error reading planes from %s.\n", filename);return 0;} if (planes != 1) { printf("Planes from %s is not 1: %u\n", filename, planes);return 0;} if ((i = fread(&bpp, 2, 1, file)) != 1) { printf("Error reading bpp from %s.\n", filename);return 0;} if (bpp != 24) { printf("Bpp from %s is not 24: %u\n", filename, bpp);return 0;}

Oh the pain, that FrankenInt has imposed upon us all. The key in my code is that I read a specific number of bytes that matches the int size in the file, and compensate for the fact that it is short of the space. Now don't start talking about endedness, as I haven't had coffee yet and I could have a seizure. It isn't my real code as I modified it to highlight what is going on.

/* FUNKY FRANKENINT CODE */ /* get the file size */ /* skip file size and reserved fields of bitmap file header */ fseek(file, 8, SEEK_CUR); /* get the position of the actual bitmap data */ if (!fread(&bfOffBits, sizeof(long int), 1, file)) { printf("Error reading file!\n"); return 0; } printf("Data at Offset: %ld\n", bfOffBits); /* skip size of bitmap info header */ fseek(file, 4, SEEK_CUR); /* get the width of the bitmap */ fread(&texture->width, sizeof(int), 1, file); printf("Width of Bitmap: %d\n", texture->width); /* get the height of the bitmap */ fread(&texture->height, sizeof(int), 1, file); printf("Height of Bitmap: %d\n", texture->height); /* get the number of planes (must be set to 1) */ fread(&biPlanes, sizeof(short int), 1, file); if (biPlanes != 1) { printf("Error: number of Planes not 1!\n"); return 0; }

The error should read

printf("Error: knowledge incomplete, install C spec in my brain!\n");

I am bad today, and I will have breakfast and coffee, before I post next time. My code could be done a better way, and someday I will make it better. Later today I may get into the Franken(Ein)stein - Rosen - Podolsky problem.

Valgrind, Kdevelop, ISO C90, and Doxygen

This is bit of false déjà vu as I remember having these problems before when I get code from the web. In particular I am clearing bugs exposed by following C rules and looking for all warnings. This link about the gettimeofday explains something I hope I am fixing once and for all, as it relates to (struct timezone). Use of tz is obsolete due to complexities in Linux that make it imossible to effectively determine due to political boundary issues AFAIK. I will continue to research that until I can make gospel code that is safe to use.

Here is a link in Google groups about opengl and valgrind that I found discussing this topic and perhaps it will be of some enlightenment.

So I imported the project in Kdevelop so I could play with that again and it does all the cute things to make a real distribution and is another step above automake. It also has debug so I am playing with that in the Kdevelop context. What I am wondering about at the moment is this report from Valgrind that seems to imply some evil deep down in SDL. I can't say that is true, but I am going to find out. It could be evil that I created, but I used the code as it was represented.

Xevent mouse

This is just a reference if someone is going to do an Xwindows mouse. It needs to be enabled in attr.event.mask and then MotionNotify and other signals can be used.

In the window initialization.

attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask | PointerMotionMask | ButtonPressMask | ButtonReleaseMask;

In the event handler.

XEvent event;XNextEvent(passVarsA->dpy2, &event);switch (event.type) { case MotionNotify: printf("Mouse X %d Y %d\n",event.xmotion.x, event.xmotion.y);break;

And some more code for the handling of buttons.

// mouse movement case MotionNotify: x = event.xmotion.x; y = event.xmotion.y; break; case ButtonRelease: case ButtonPress: { switch (event.xbutton.button) { // mouse button presses case 1: // LeftMB case 2: // MiddleMB case 3: // RightMB } break; }
case 4: //This is the forward roll case 5: //This is the backward roll

These are the names that are used to identify the specific events.

Code and codes

Wandering about the internet at random, I happened upon this little tidbit about generating neutrinos to communicate through the Earth in UK. I didn't look any further, but it seems they have been at this for a while.

I thought I would comment on compiling and linking the code for the simple OpenGL window that I posted. Basically gcc uses the header files that are provided to find a match for external functions and at link time it looks in the libraries provided for those elements. You need the dev files for a specific library like OpenGL so that gcc knows the format of the call and the variable types to use. The following is the "nm GLwindow" output. It isn't difficult to see in a simple example that after compilation the code links to the specific libraries and then to the device. I think I will do a simple C program and see what the nm looks like when there are no external libraries and just a simple "int main(){return 0;}"

00000000004012d0 T DrawGLScene
                 U XCloseDisplay
                 U XCreateColormap
                 U XCreateWindow
                 U XDestroyWindow
                 U XFree
                 U XLookupKeysym
                 U XLookupString
                 U XMapWindow
                 U XNextEvent
                 U XOpenDisplay
                 U XPending
                 U XSetNormalHints
                 U XSetStandardProperties
0000000000602028 d _DYNAMIC
0000000000602210 d _GLOBAL_OFFSET_TABLE_
00000000004019c8 R _IO_stdin_used
                 w _Jv_RegisterClasses
0000000000602008 d __CTOR_END__
0000000000602000 d __CTOR_LIST__
0000000000602018 d __DTOR_END__
0000000000602010 d __DTOR_LIST__
0000000000401c90 r __FRAME_END__
0000000000602020 d __JCR_END__
0000000000602020 d __JCR_LIST__
0000000000602368 A __bss_start
0000000000602348 D __data_start
0000000000401980 t __do_global_ctors_aux
00000000004010f0 t __do_global_dtors_aux
0000000000602350 D __dso_handle
                 w __gmon_start__
0000000000602000 d __init_array_end
0000000000602000 d __init_array_start
00000000004018e0 T __libc_csu_fini
00000000004018f0 T __libc_csu_init
                 U __libc_start_main@@GLIBC_2.2.5
                 U __stack_chk_fail@@GLIBC_2.4
0000000000602368 A _edata
0000000000602370 A _end
00000000004019b4 T _fini
0000000000400e38 T _init
00000000004010a0 T _start
00000000004010cc t call_gmon_start
0000000000602368 b completed.6183
0000000000602348 W data_start
000000000040140c T draw
000000000040178e t event_loop
                 U exit@@GLIBC_2.2.5
0000000000401130 t frame_dummy
                 U gettimeofday@@GLIBC_2.2.5
                 U glBegin
                 U glClear
                 U glEnd
                 U glFlush
                 U glLoadIdentity
                 U glMatrixMode
                 U glTranslatef
                 U glVertex2f
                 U glViewport
                 U glXChooseVisual
                 U glXCreateContext
                 U glXDestroyContext
                 U glXMakeCurrent
                 U glXSwapBuffers
                 U gluPerspective
0000000000401421 t init
0000000000401158 T main
0000000000401503 t make_window
0000000000602358 d p.6181
                 U printf@@GLIBC_2.2.5
                 U puts@@GLIBC_2.2.5
                 U rand@@GLIBC_2.2.5
0000000000401431 t reshape
00000000004012a5 T seedRandom
                 U srand@@GLIBC_2.2.5
0000000000602360 d windowHeight.13688
0000000000602364 d windowWidth.13687

Also there is the "ldd GLwindow" output which shows what libraries are used at run time. This shows what libraries are used by the code and with such a simple example it is possible to identify how the entire process works. I call a library with a list of options and it uses the code there to perform the function I am interested in. It isn't much different than calling an internal function, but it is merely there to allow for some standard to be maintained. If the underlying system changes, the code is still valid if it conforms to a standard interface.

linux-vdso.so.1 => (0x00007fff2fdfe000) libGL.so.1 => /usr/lib/libGL.so.1 (0x00007f6227b2e000) libglut.so.3 => /usr/lib/libglut.so.3 (0x00007f6227891000) libc.so.6 => /lib/libc.so.6 (0x00007f622752f000) libGLU.so.1 => /usr/lib/libGLU.so.1 (0x00007f62272ab000) libX11.so.6 => /usr/lib/libX11.so.6 (0x00007f6226fa8000) libpthread.so.0 => /lib/libpthread.so.0 (0x00007f6226d8c000) libXext.so.6 => /usr/lib/libXext.so.6 (0x00007f6226b7b000) libm.so.6 => /lib/libm.so.6 (0x00007f62268fa000) /lib64/ld-linux-x86-64.so.2 (0x00007f6227ad5000) libstdc++.so.6 => /usr/lib/libstdc++.so.6 (0x00007f62265ef000) libgcc_s.so.1 => /lib/libgcc_s.so.1 (0x00007f62263e1000) libxcb-xlib.so.0 => /usr/lib/libxcb-xlib.so.0 (0x00007f62261e0000) libxcb.so.1 => /usr/lib/libxcb.so.1 (0x00007f6225fc5000) libdl.so.2 => /lib/libdl.so.2 (0x00007f6225dc1000) libXau.so.6 => /usr/lib/libXau.so.6 (0x00007f6225bbf000) libXdmcp.so.6 => /usr/lib/libXdmcp.so.6 (0x00007f62259ba000)

So here is the ldd and nm from the simplest program I can think of. That is a lot of stuff to do, just to accomplish nothing.

int main(){return 0;}

0000000000600640 d _DYNAMIC
00000000006007e8 d _GLOBAL_OFFSET_TABLE_
0000000000400544 R _IO_stdin_used
                 w _Jv_RegisterClasses
0000000000600620 d __CTOR_END__
0000000000600618 d __CTOR_LIST__
0000000000600630 d __DTOR_END__
0000000000600628 d __DTOR_LIST__
0000000000400610 r __FRAME_END__
0000000000600638 d __JCR_END__
0000000000600638 d __JCR_LIST__
0000000000600820 A __bss_start
0000000000600808 D __data_start
0000000000400500 t __do_global_ctors_aux
00000000004003e0 t __do_global_dtors_aux
0000000000600810 D __dso_handle
                 w __gmon_start__
0000000000600614 d __init_array_end
0000000000600614 d __init_array_start
0000000000400460 T __libc_csu_fini
0000000000400470 T __libc_csu_init
                 U __libc_start_main@@GLIBC_2.2.5
0000000000600820 A _edata
0000000000600828 A _end
0000000000400534 T _fini
0000000000400350 T _init
0000000000400390 T _start
00000000004003bc t call_gmon_start
0000000000600820 b completed.6183
0000000000600808 W data_start
0000000000400420 t frame_dummy
0000000000400448 T main
0000000000600818 d p.6181
 linux-vdso.so.1 =>  (0x00007fff207fe000)
 libc.so.6 => /lib/libc.so.6 (0x00007f8c1821b000)
 /lib64/ld-linux-x86-64.so.2 (0x00007f8c1857d000)

And just for the sake of being complete, here is the ".S" output for the simplest program in the world. As you can see it does an "enter" and saves eSP to eBP , sets Eax to 0 (return 0) and then does a "leave" which restores eSP from eBP and restores eBP from the stack and goes back to the OS. I have seen this a lot when debugging and looking at the stack frame. It is fairly easy to just look and see the progression of the process on the stack, because the return address is just after the eBP and so it is usually very obvious what the call tree looks like.

 .file "main.c"
 .text
.globl main
 .type main, @function
main:
.LFB2:
 pushq %rbp
.LCFI0:
 movq %rsp, %rbp
.LCFI1:
 movl $0, %eax
 leave
 ret
.LFE2:
 .size main, .-main
 .section .eh_frame,"a",@progbits
.Lframe1:
 .long .LECIE1-.LSCIE1
.LSCIE1:
 .long 0x0
 .byte 0x1
 .string "zR"
 .uleb128 0x1
 .sleb128 -8
 .byte 0x10
 .uleb128 0x1
 .byte 0x3
 .byte 0xc
 .uleb128 0x7
 .uleb128 0x8
 .byte 0x90
 .uleb128 0x1
 .align 8
.LECIE1:
.LSFDE1:
 .long .LEFDE1-.LASFDE1
.LASFDE1:
 .long .LASFDE1-.Lframe1
 .long .LFB2
 .long .LFE2-.LFB2
 .uleb128 0x0
 .byte 0x4
 .long .LCFI0-.LFB2
 .byte 0xe
 .uleb128 0x10
 .byte 0x86
 .uleb128 0x2
 .byte 0x4
 .long .LCFI1-.LCFI0
 .byte 0xd
 .uleb128 0x6
 .align 8
.LEFDE1:
 .ident "GCC: (GNU) 4.2.4 (Ubuntu 4.2.4-1ubuntu4)"
 .section .note.GNU-stack,"",@progbits

Quantum Certainty

To compile on Linux use this.

gcc GLwindow.c -o GLwindow -lGL -lglut

This is just some code I decided to do as a lark and it is usable code for a Linux X windows system. I am certain it will not function in another operating system, as it uses X keys. It implements an IFS Sierpinski using randoms. If you want to see how to do basic OpenGL in Linux, this is a good template. It includes key handling and window initialization and the initial GL context so that the rest is just filling in what you need to display. I was planning to do an implementation of the einstein game using a set of six rotating dice that contain the possible symbols for a particular location and uses a technique I developed for AI. When I get the code done , I will post it. The AI method is unique , I think, but I am not Google. I started to change the code for einstein to make it re-sizable, but it was just easier to just redo the whole thing in OpenGL using scaled images and relative positions. I also wanted to test a solving scheme that used an artificial imagination with randomness.


/**
@author Paul Mohr
@name GLwindow.c
@brief Simplest window implementation using openGL
I threw an IFS (Iterated Function System )
Serpinski in here for fun so something was
on the screen.
I don't think this is really elegant math,
but it looks interesting.
*/
#include <stdlib.h>
#include <stdio.h>
#include <X11/Xlib.h>
#include <X11/keysym.h>
#include <GL/gl.h>
#include <GL/glut.h>
#include <GL/glx.h>

/* This is just to make a truly pseudo ramdom. */
#include <sys/time.h>

/*Functions */
void seedRandom(void);
void DrawGLScene(GLvoid);
void draw(void);
static void init(void);
static void reshape(int width, int height,
                    Display *dpy,Window win, GLXContext ctx);

static void make_window( 
 Display *dpy,
 const char *name,
 int x, int y, int width, int height,
 Window *winRet, 
 GLXContext *ctxRet);

static void event_loop(Display *dpy,Window win, GLXContext ctx);

/* Now the code */
int main(int argc, char *argv[]){

/* unVariables */
static int windowWidth=640;
static int windowHeight=480;

/* Variables  within the scope of main */
int displays;
char *dpyName = ":0.0";
Display *dpy;
GLXContext ctx;
Window win;
char AppVersion[] ="Simple OpenGL window only. ";

 seedRandom();
 dpy = XOpenDisplay(dpyName);
 if (!dpy) {printf("Error: couldn't open display %s\n", dpyName);return -1;}
 make_window(dpy, AppVersion, 0, 0, 
                    windowWidth, windowHeight,
                    &win, &ctx);
 XMapWindow(dpy, win);
 glXMakeCurrent(dpy, win, ctx);
 init();

event_loop(dpy, win, ctx);

 glXMakeCurrent(dpy, win, ctx);
 glXDestroyContext(dpy, ctx);
 XDestroyWindow(dpy, win);
 XCloseDisplay(dpy);

return 0;
}


void seedRandom(void){
    struct timeval tv;
    gettimeofday(&tv, NULL);
    srand(tv.tv_sec * tv.tv_usec);}

void DrawGLScene(GLvoid) {
int i;float x=-3, y=2;float tx, ty;

glLoadIdentity();
glTranslatef(0,0,-6);

glBegin(GL_POINTS);
  for (i=0; i<1000; i++) { 
/* Pick 1 out of 3 end points at random */
    switch(rand()%3) { 
 case 0:
  tx = -3; ty = 2;
  break;
 case 1:
  tx = 3; ty = 2;
  break;
 case 2:
  tx = 0; ty = -2;
  break;
 }
    x = (x + tx) / 2;
    y = (y + ty) / 2;
    glVertex2f(x,y);
  }
glEnd();
glFlush();
}
    
void draw(void) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
DrawGLScene();
}

static void init(void){
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}


static void reshape(int width, int height,
                    Display *dpy,Window win, GLXContext ctx){
glXMakeCurrent(dpy, win, ctx);
GLdouble NearScale  = 90.0;
GLdouble FarScale  = 450.0;
GLdouble FrontScreen  = 0.001;
GLdouble BackScreen  = 1.0;
glXMakeCurrent(dpy, win, ctx);
glViewport(0, 0, (GLint) width, (GLint) height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(NearScale,BackScreen,FrontScreen,FarScale);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}

/* Create an RGB, double-buffered window.
 * Return the window and context handles. */
static void make_window( Display *dpy, const char *name,
                         int x, int y, int width,
                         int height,Window *winRet, 
GLXContext *ctxRet) {
int attrib[] = { GLX_RGBA,GLX_RED_SIZE,1,
  GLX_GREEN_SIZE,1,GLX_BLUE_SIZE,1,GLX_DOUBLEBUFFER,
  GLX_DEPTH_SIZE,1,None };

int scrnum; 
XSetWindowAttributes attr;
unsigned long mask;
Window root;
Window win;
GLXContext ctx;
XVisualInfo *visinfo;

scrnum = DefaultScreen( dpy );
root = RootWindow( dpy, scrnum );
visinfo = glXChooseVisual( dpy, scrnum, attrib );
if (!visinfo)
{printf("Error: couldn't get an RGB, Double-buffered visual\n");exit(1);}
/* window attributes */
attr.background_pixel = 0;
attr.border_pixel = 0;
attr.colormap = XCreateColormap( dpy, root, visinfo->visual, AllocNone);
attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask;
mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask;
win = XCreateWindow( 
  dpy, root, x, y, 
//  dpy, root, 0, 0, 
  width, height,0,
  visinfo->depth, InputOutput,visinfo->visual, mask, &attr );
/* set hints and properties */
   {
      XSizeHints sizehints;
      sizehints.x = x;
      sizehints.y = y;
      sizehints.width  = width;
      sizehints.height = height;
      sizehints.flags = USSize | USPosition;
      XSetNormalHints(dpy, win, &sizehints);
      XSetStandardProperties(dpy, win, name, name,None, (char **)NULL, 0, &sizehints);
   }

   ctx = glXCreateContext( dpy, visinfo, NULL, True );
   if (!ctx) {printf("Error: glXCreateContext failed\n");exit(1);}
   XFree(visinfo);
   *winRet = win;
   *ctxRet = ctx;
}



static void event_loop(Display *dpy,Window win, GLXContext ctx) {

char buffer[10];
int r, code;

 while (1) {
  glXMakeCurrent(dpy, win, ctx);
  while (XPending(dpy) > 0) {
   XEvent event;XNextEvent(dpy, &event);switch (event.type) {
 case Expose: break;

 case ConfigureNotify:
 reshape(event.xconfigure.width, event.xconfigure.height,dpy, win, ctx);break;

 case KeyPress: {
 code = XLookupKeysym(&event.xkey, 0);
 if (code == XK_Left ) {}
 if (code == XK_Right) {}
 if (code == XK_Up   ) {}
 else {
 r=XLookupString(&event.xkey, buffer, sizeof(buffer),NULL, NULL);
 if (buffer[0] == 27) {return;}}
 }
   }
  }
  draw();glXSwapBuffers(dpy, win);
 }
}

Quantum certainty is the title and it was just something I was considering and how it relates to the way the universe operates. The future is certainly going to bring some strange things and it seems that much I see as science fiction is really out of date. Even the oddest of it is tame compared to what is likely to happen in the not so distant infinite future.

ADDED: I changed the way create_window works as I goofed up the positioning :) substituted "dpy, root, x, y," for "dpy, root, 0, 0,"

Contributors

Automated Intelligence

Automated Intelligence
Auftrag der unendlichen LOL katzen