Tuesday, December 8, 2015

Configure Coverity using Jenkins on MAC

Skip to end of metadata
I recently took up a task to configure the Coverity on a MAC running from a Jenkins server.

Getting started

  • Install Coverity software on the MAC mini where Jenkins is installed.
  • Install the plugin using the Plugin Manager, and restart Jenkins
  • Go to the global configuration page ( Manage Jenkins > Configure System)
  • If the Coverity Static Analysis tools are not on the PATH, configure the location for the master.
  • Add connection details for any number of Coverity Connect instances you want to use. Click ‘check’ to validate your settings.
Since our Coverity connect implementation was using a self signed certificate, the certificate had to be entered in to the JRE certsore. As we are using El Capitan, the server did not allow allow any changes to /System directory tree due to  "System Integrity Protection” feature. To disable it temporarily we had to reboot the box in recovery mode, disable it, reboot again without SIP, add the cert and then reboot in recovery mode again to re-enable SIP and then reboot once more.
There were multiple JVM on the system. Had to do a trail and error method to add the certificates to the correct cacert stores
  1. /Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/lib/security/cacerts
  2. /Users/Shared/Jenkins/Home/tools/hudson.model.JDK/Oracle_Account/jre/lib/security/cacerts
  3. /Applications/Xcode.app/Contents/Applications/Application Loader.app/Contents/itms/java/lib/security/cacerts
  4. /Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/lib/security/cacerts
  5. /Library/Java/JavaVirtualMachines/jdk1.8.0_40.jdk/Contents/Home/jre/lib/security/cacerts  <- strong=""> Adding the cert to this cacert file fixed the issue
Mac-mini:security root# keytool -list -v -keystore ./cacerts | grep coverity
Enter keystore password:  changeit
Mac-mini:security root# keytool -import -trustcacerts -alias CACoverity -file ./signature.crt -keystore ./cacerts
Enter keystore password:

Trust this certificate? [no]:  yes
Certificate was added to keystore
Mac-mini:security root# keytool -list -v -keystore ./cacerts | grep coverity
Enter keystore password:  changeit
Alias name: cacoverity
  • For any node where Coverity Static Analysis is not on the PATH (and is on a different location than on the master), configure the location on the node configuration page.

Job Setup
  • Create the job, by creating it from scratch or copying from an existing job
  • Under Post-build actions, check ‘Coverity’
  • Select the Coverity Connect instance, project and stream relevant for this job


OS Not Supported Error
If you run cov-configure on Mac OSX 10.6 you will get an error be: Platform info:Sysname = DarwinRelease = 10.4.0Machine = i386 [ERROR] This platform is not supported by Coverity. There is potential for confusion as the release number 10.4.0 refers to Darwin (the kernel version) and not to Mac OSX (the OS version). The supported Mac OS 10.5 uses Darwin 9.x and Mac OSX 10.2 actually used Darwin version 6!  Darwin 10.2, 10.3, 10.4 are all versions of Snow Leopard which Coverity SA does not yet support.
Exporting the variable COVERITY_UNSUPPORTED with a value of 1, and cov-configure helped to trick the executable to be supported on the latest OS.

Wednesday, August 12, 2015

Flight Of Dreams - First Quadcopter

After seeing a bunch of videos and races and going through multiple blogs, I got hooked up in to Quad copters and FPV.

This is the video that got me hooked in to this -

 Run Boy Run

Run boy run! This world is not made for you
Run boy run! They’re trying to catch you
Run boy run! Running is a victory
Run boy run! Beauty lays behind the hills

Run boy run! The sun will be guiding you
Run boy run! They’re dying to stop you
Run boy run! This race is a prophecy
Run boy run! Break out from society

Tomorrow is another day
And you won’t have to hide away
You’ll be a man, boy!
But for now it’s time to run, it’s time to run!

Run boy run! This ride is a journey to
Run boy run! The secret inside of you
Run boy run! This race is a prophecy
Run boy run! And disappear in the trees

Tomorrow is another day
And you won’t have to hide away
You’ll be a man, boy!
But for now it’s time to run, it’s time to run!

Tomorrow is another day
And when the night fades away
You’ll be a man, boy!
But for now it’s time to run, it’s time to run!  



So here is my adventure with Quadcopter. I am a complete NOOB in this field and just learning the basics of flight.

 1. Parts List



Component Seller Price
OpenPilot CC3D EVO Flight Controller STM32 32-bit Flexiport Banggood $12.79
Gemfan 5x3 Inch Plastic 5030 Propeller CW/CCW For 240 250 Frame Banggood $2.22
4x Emax SimonK Brushless 12A ESC Speed Controller eBay $19
Emax Mini 250 FPV Frame Carbon Fiber Quadcopter eBay $20
DYS BE1806 2300KV Brushless Motor Black Edition Banggood $37.56
Turnigy 9X 9Ch Transmitter w/ Module & 8ch Receiver (Mode 2) HobbyKing $69.90
5M Nylon Lock Nut Lowes $0.68
ZIPPY Compact 1300mAh 3s 40c Lipo Pack HobbyKing $9.88
Turnigy Accucell-6 50W 6A Balancer/Charger LiHV Capable HobbyKing $25.99


2. Build Log:


Difference between CW and CCW Motors

I got 4 CW( Clock Wise) motor for my build. As far as brush less motors are concerned, the direction that they spin is completely determined by how you connect them to the ESC. Brushless motor is not designed specifically to run in a particular direction. You literally hook the three wires up to the ESC in any order, and if it spins the way you want, then you are good. If it spins the wrong direction, then you only need to choose two of the three and reverse the connection and it will spin the other direction.

The difference in the CW and CCW motors are in the threads for the props. CCW motors have right hand threads and CW have left hand threads. This is because when the motors rotate, it will tighten up the nut. Since two motors spin "backwards", they are constantly trying to unscrew the prop. In case if you are using all CW motors, make sure to use the nylon lock nuts otherwise TWO prop nuts will come from your newly-built quadcopter during flight. Weight wise also 4 M5 locknuts are less than 5 grams where as a single spinner is approximately 5 grams. When fixing the locknuts, make sure that the nylon ring is on the top section.

 Connecting the receiver to CC3D EVO

First step is to make sure that the receiver is bound to the transmitter. The Rx in the box is by default bound to the transmitter. 



There are a number of ways in which the actual (main port) wires can be connected to the Rx. You can plug in each of the single signal wires in no particular order into your Rx. Then go to the transmitter wizard in GCS. Open pilot ground control station will automatically assign Aileron , throttle, elev etc through the wizard.

 http://media1.bengtolsson.se/2014/10/CC3D-Connection.png

The Rx channels that comes with the 9X has the following configuration:
Channel 1: Aileron 1 (fins)
Channel 2: Depth (elevator)
Channel 3: Throttle
Channel 4: Management (Rudd)
Channel 5: Train returning (Gear)
Channel 6: Shutters (Flaps)
Channel 7: Auxiliary 1 and fins 2 (for differential)
Channel 8: Auxiliary 2
Channel 9: Battery


I have connected the wires from the CC3D to the reciever in below configuration
Plug the 3 pin connector in to channel 3 such that the black wire is in the lowest plug on channel 3, the red into the middle plug on channel 3, and the third wire from left into the top plug on channel 3

Plug the next wire from left in to the top plug on channel 1.
Plug next wire from left into the top plug (signal plug) of channel 2.
Plug the last control surface wire into the top plug of channel 4.

For the control mode changing plug the the top plug on channel 5 of your receiver.

How do you attach a propeller?

 Make sure your props are aligned with spin (leading edge in direction of motion). The writing on the Gemfan 5030 or the 5030R faces up.

  http://newspaces.org/sites/default/files/styles/large/public/200px-Swept-propeller7.svg_.png

 

 Transmitter

You start off with a Acro model (normal plane) - no glider or heli.
That should give you the basic flight controls.

Partial Build



First Flight

My first flight failed miserably. The copter was flipping as soon as I launched. Lost 3 propellers in the first crash. Better order lot of props.

If the Copter is flipping on take off, make sure that

1. The Props are attached properly.
2. Make sure your ESCs are plugged into the appropriate pins.
3. Check if the ESCs are calibrated properly. 

  










But for now it’s time to run, it’s time to run! 

 

 





Monday, December 13, 2010

How to handle a constructor and destructor that fail

Constructors don't have a return type, so it's not possible to use return codes. The best way to signal constructor failure is to throw an exception.

In any constructor that initializes member objects, it is always better to use an initialization list. There can be special scenarios that require one to use the initialization list (to initialize a constants or references in the class). There are other advantages to set the objects using an initialization list rather than within the constructor itself. What happens if one of the one of the members fails at initialization and throw an exception?

How will you handle such a situation? It’s not quite hard.

Constructor function-try-block


class Myclass
{

Myclass ()
try
: m_member1(value1),
m_member2(value2)
{
// Rest of constructor code
}
catch (...)
{
// Got here if one of the members in initilization list throws.
}

private:

type m_member1;
type m_member2
};


How ever one of the drawbacks is that you should throw an exception from the catch block. You cannot simple ignore and continue with the object creation!!!

Destructors on the other hand should be exception free. Destructors should be written in a way in which they cannot fail. Resource Acquisition Is Initialization is built upon the lines that resources are acquired during initialization, when there is no chance of them being used before they are available, and released with the destruction of the same objects, throwing from a destructor will open the possibility of RAII failing on you. If they can, it is a sign for a very bad design.

Some of the morals and further discussions from http://www.gotw.ca/gotw/066.htm

Moral #1: Constructor function-try-block handlers have only one purpose -- to translate an exception. (Or for logging) They are not useful for any other purpose.

Moral #2: Since destructors should never emit an exception, destructor function-try-blocks have no practical use at all. It is of not much use as it can not suppress the exception.

Moral #3: Always perform unmanaged resource acquisition in the constructor body, never in initializer lists. In other words, either use "resource acquisition is initialization" (thereby avoiding unmanaged resources entirely) or else perform the resource acquisition in the constructor body.

Moral #4: Always clean up unmanaged resource acquisition in local try-block handlers within the constructor or destructor body, never in constructor or destructor function-try-block handlers.

Moral #5: If a constructor has an exception specification, that exception specification must allow for the union of all possible exceptions that could be thrown by base and member subobjects.

Moral #6: If a constructor of a member object can throw but you can get along without said member, hold it by pointer and use the pointer's nullness to remember whether you've got one or not, as usual. Use the Pimpl idiom to group such "optional" members so you only have to allocate once.

Moral #7: Prefer using "resource acquisition is initialization" to manage resources.

Monday, December 6, 2010

Small is beautiful

How small can a web server be.



The smallest I could find in term of physical size is http://d116.com/ace/webACE: A Fairchild ACE1101MT8 microcontroller programmed as a Web server and containing two tiny web pages in its on-chip memory.

Going to the code side. There is the heavy weight Apache and the light weight Nginx and Lighttpd. Need a still smaller solution. Saw this implementation in IBM developers work. http://www.ibm.com/developerworks/systems/library/es-nweb/index.html


#include < stdio.h >
#include < stdlib.h >
#include < unistd.h >
#include < errno.h >
#include < string.h >
#include < fcntl.h >
#include < signal.h >
#include < sys/types.h >
#include < sys/socket.h >
#include < netinet/in.h >
#include < arpa/inet.h >

#define BUFSIZE 8096
#define ERROR 42
#define SORRY 43
#define LOG 44

struct {
char *ext;
char *filetype;
} extensions [] = {
{"gif", "image/gif" },
{"jpg", "image/jpeg"},
{"jpeg","image/jpeg"},
{"png", "image/png" },
{"zip", "image/zip" },
{"gz", "image/gz" },
{"tar", "image/tar" },
{"htm", "text/html" },
{"html","text/html" },
{0,0} };

void log(int type, char *s1, char *s2, int num)
{
int fd ;
char logbuffer[BUFSIZE*2];

switch (type) {
case ERROR: (void)sprintf(logbuffer,"ERROR: %s:%s Errno=%d exiting pid=%d",s1, s2, errno,getpid()); break;
case SORRY:
sprintf(logbuffer, "
nweb Web Server Sorry: %s %s
\r\n", s1, s2);
write(num,logbuffer,strlen(logbuffer));
sprintf(logbuffer,"SORRY: %s:%s",s1, s2);
break;
case LOG: (void)sprintf(logbuffer," INFO: %s:%s:%d",s1, s2,num); break;
}
/* no checks here, nothing can be done a failure anyway */
if((fd = open("nweb.log", O_CREAT| O_WRONLY | O_APPEND,0644)) >= 0) {
(void)write(fd,logbuffer,strlen(logbuffer));
(void)write(fd,"\n",1);
(void)close(fd);
}
if(type == ERROR || type == SORRY) exit(3);
}

/* this is a child web server process, so we can exit on errors */
void web(int fd, int hit)
{
int j, file_fd, buflen, len;
long i, ret;
char * fstr;
static char buffer[BUFSIZE+1]; /* static so zero filled */

ret =read(fd, buffer, BUFSIZE); /* read Web request in one go */
if(ret == 0 || ret == -1) { /* read failure stop now */
log(SORRY,"failed to read browser request","",fd);
}
if(ret > 0 && ret < BUFSIZE) /* return code is valid chars */
buffer[ret]=0; /* terminate the buffer */
else buffer[0]=0;

for(i=0 ; i < ret ; i++) /* remove CF and LF characters */
if(buffer[i] == '\r' || buffer[i] == '\n')
buffer[i]='*';
log(LOG,"request",buffer,hit);

if( strncmp(buffer, "GET ",4) && strncmp(buffer,"get ",4) )
log(SORRY,"Only simple GET operation supported",buffer,fd);

for(i=4 ; i < BUFSIZE; i++) { /* null terminate after the second space to ignore extra stuff */
if(buffer[i] == ' ') { /* string is "GET URL " +lots of other stuff */
buffer[i] = 0;
break;
}
}

for(j=0; j < i-1 ; j++) /* check for illegal parent directory use .. */
if(buffer[j] == '.' && buffer[j+1] == '.')
log(SORRY,"Parent directory (..) path names not supported",buffer,fd);

if( !strncmp(&buffer[0],"GET /\0",6) || !strncmp(&buffer[0],"get /\0",6) ) /* convert no filename to index file */
(void)strcpy(buffer,"GET /index.html");

/* work out the file type and check we support it */
buflen=strlen(buffer);
fstr = (char *)0;
for(i=0;extensions[i].ext != 0;i++) {
len = strlen(extensions[i].ext);
if( !strncmp(&buffer[buflen-len], extensions[i].ext, len)) {
fstr =extensions[i].filetype;
break;
}
}
if(fstr == 0) log(SORRY,"file extension type not supported",buffer,fd);

if(( file_fd = open(&buffer[5] , O_RDONLY)) == -1) /* open the file for reading */
log(SORRY, "failed to open file",&buffer[5],fd);

log(LOG,"SEND",&buffer[5],hit);

(void)sprintf(buffer,"HTTP/1.0 200 OK\r\nContent-Type: %s\r\n\r\n", fstr);
(void)write(fd,buffer,strlen(buffer));

/* send file in 8KB block - last block may be smaller */
while ( (ret = read(file_fd, buffer, BUFSIZE)) > 0 ) {
(void)write(fd,buffer,ret);
}
#ifdef LINUX
sleep(1); /* to allow socket to drain */
#endif
exit(1);
}


int main(int argc, char **argv)
{
int i, port, pid, listenfd, socketfd, hit;
size_t length;
static struct sockaddr_in cli_addr; /* static = initialised to zeros */
static struct sockaddr_in serv_addr; /* static = initialised to zeros */

if( argc < 3 || argc > 3 || !strcmp(argv[1], "-?") ) {
(void)printf("hint: nweb Port-Number Top-Directory\n\n"
"\tnweb is a small and very safe mini web server\n"
"\tnweb only servers out file/web pages with extensions named below\n"
"\t and only from the named directory or its sub-directories.\n"
"\tThere is no fancy features = safe and secure.\n\n"
"\tExample: nweb 8181 /home/nwebdir &\n\n"
"\tOnly Supports:");
for(i=0;extensions[i].ext != 0;i++)
(void)printf(" %s",extensions[i].ext);

(void)printf("\n\tNot Supported: URLs including \"..\", Java, Javascript, CGI\n"
"\tNot Supported: directories / /etc /bin /lib /tmp /usr /dev /sbin \n"
"\tNo warranty given or implied\n\tNigel Griffiths nag@uk.ibm.com\n"
);
exit(0);
}
if( !strncmp(argv[2],"/" ,2 ) || !strncmp(argv[2],"/etc", 5 ) ||
!strncmp(argv[2],"/bin",5 ) || !strncmp(argv[2],"/lib", 5 ) ||
!strncmp(argv[2],"/tmp",5 ) || !strncmp(argv[2],"/usr", 5 ) ||
!strncmp(argv[2],"/dev",5 ) || !strncmp(argv[2],"/sbin",6) ){
(void)printf("ERROR: Bad top directory %s, see nweb -?\n",argv[2]);
exit(3);
}
if(chdir(argv[2]) == -1){
(void)printf("ERROR: Can't Change to directory %s\n",argv[2]);
exit(4);
}

/* Become deamon + unstopable and no zombies children (= no wait()) */
if(fork() != 0)
return 0; /* parent returns OK to shell */
(void)signal(SIGCLD, SIG_IGN); /* ignore child death */
(void)signal(SIGHUP, SIG_IGN); /* ignore terminal hangups */
for(i=0;i<32;i++)
(void)close(i); /* close open files */
(void)setpgrp(); /* break away from process group */

log(LOG,"nweb starting",argv[1],getpid());
/* setup the network socket */
if((listenfd = socket(AF_INET, SOCK_STREAM,0)) <0)
log(ERROR, "system call","socket",0);
port = atoi(argv[1]);
if(port < 0 || port >60000)
log(ERROR,"Invalid port number (try 1->60000)",argv[1],0);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(port);
if(bind(listenfd, (struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
log(ERROR,"system call","bind",0);
if( listen(listenfd,64) <0)
log(ERROR,"system call","listen",0);

for(hit=1; ;hit++) {
length = sizeof(cli_addr);
if((socketfd = accept(listenfd, (struct sockaddr *)&cli_addr, &length)) < 0)
log(ERROR,"system call","accept",0);

if((pid = fork()) < 0) {
log(ERROR,"system call","fork",0);
}
else {
if(pid == 0) { /* child */
(void)close(listenfd);
web(socketfd,hit); /* never returns */
} else { /* parent */
(void)close(socketfd);
}
}
}
}



A working server in 202 lines of pure C code. The compiled executable itself under 10kb size. Can it be reduced even smaller. not massive in terms of feature but still a good implementation for any one to learn from.

Wednesday, June 2, 2010

C++ Questions

  1. T *p =0; delete p;
  2. T *p =new T[10]; delete p;
  3. drawbacks of inheritance
  4. typedef and #define
  5. how to determine a little endian and big endian system
  6. structure padding
  7. function declaration of printf ( variable arrgs)
  8. static / extern
  9. find the nth node from last in a singly linked list
  10. delete current node in the list
  11. reverse a singly linked list
  12. check if list contains a loop
  13. operators that cannot be overloaded
  14. delete this
  15. virtual destructors /constructors
  16. implementation of virtual fns
  17. RTTI
  18. STL containers
  19. strstream
  20. stack unwinding
  21. one use of union
  22. *p+1 , *p++
  23. memory leak tools
  24. segmentation violation
  25. storage class specifications
  26. eg of function pointers, their uses
  27. bit fields
  28. declare an int pointer that points to an array of type int
  29. Are Null and 0 same?
  30. a= a+0; a= a+NULL;
  31. diff between memmove and memcpy
  32. garbage collection in c++
  33. dangling pointers
  34. priority queue
  35. static functions
  36. How to handle failures in constructor
  37. what happens when exception is thrown in c++
  38. exceptions in destructors
  39. explict constructors
  40. mutable keyword
  41. where initialisation list is used as opposed to assignment in constructor(non static const data members and reference data members)

Friday, March 19, 2010

Mastering C/C++ - My references



Some of the books that I refer are..
  • Scott Myers - Effective C++
  • Scott Myers - More Effective C++
  • Steve McConnell - Code Complete
  • Stephen C. Dewhurst - C++ Common Knowledge
  • Bjarne Stroustrup - The C++ Programming Language (Third Edition and Special Edition)

Other Highly Recommended Books:
  • Thinking in C++
  • Art of Computer Programming Series - Donald E. Knuth
  • C++ Templates: The Complete Guide - David Vandervoode and Nicolai Josuttis
  • C++ Primer - Stanley Lippman and Josee Lajoie
  • Exceptional C++ - Herb Sutter
  • More Exceptional C++ - Herb Sutter
  • C++ for Real Programmers - Jeff Alger
  • Standard Template Library - Nicolai M. Josuttis
  • Template Metaprogramming - Abrahams and Gurtovy
  • Generative Programming book - Eiseneker and Krysznewski
  • Introduction to Algorithms - Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein
  • The Pragmatic Programmer - Andrew Hunt and David Thomas

Tuesday, January 19, 2010

The tiniest C sort function

Came across this site and thought it was worth noting it down.

void s(int*a,int*b){for(int*c=b,t;c>a;)
if(t=*c--,*c>t)c[1]=*c,*c=t,c=b;}

http://www.cs.dartmouth.edu/~doug/tinysort.html