Basic Ragel parser - ragel

With a machine like this:
main := (any+);
When I feed it a chunk of data, more than 1 byte, it seems to consume only 1 byte before coming out (normally) of %%write exec block. I expect it to be greedy and consume all of the provided input.
I can always check p < pe and goto to before %%write exec, but it seems to be hackish.
How do I make it "greedy" ?

Maybe your question is missing some critical data, but the default behaviour is to consume everything up to pe if possible. Obviously with your machine it is possible and given Ragel 6.9 and this simple program:
#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
%%{
machine main;
alphtype char;
main := (any+);
}%%
int main()
{
static char data[] = "Some string!";
int cs;
char *p, *pe, *eof;
%% write data;
%% write init;
p = data;
pe = data + sizeof(data);
eof = pe;
printf("p: 0x%"PRIxPTR", pe: 0x%"PRIxPTR", eof: 0x%"PRIxPTR"\n",
(uintptr_t) p, (uintptr_t) pe, (uintptr_t) eof);
%% write exec;
printf("p: 0x%"PRIxPTR", pe: 0x%"PRIxPTR", eof: 0x%"PRIxPTR"\n",
(uintptr_t) p, (uintptr_t) pe, (uintptr_t) eof);
return 0;
}
You should get something like this in the output:
p: 0x601038, pe: 0x601045, eof: 0x601045
p: 0x601045, pe: 0x601045, eof: 0x601045

Related

Find CPU times and system times of process in linux

I have a main program that creates two children and each children calls execlv. At the end of the program how do I calculate the CPU times and system times of the parent and two process?
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <signal.h>
int main()
{
pid_t pid1,pid2,wid; // variable for parent and two children
char *my_args[3]; // strign array for containing the arguments for executing sigShooter1
// int aInt = 368; //
char str[15]; // strign to contain the pids of children when passing as command line arguments
pid1 = fork();
if (pid1 < 0)
{
fprintf(stderr, ": fork failed: %s\n", strerror(errno));
exit(1);
}
if(pid1 == 0)
{
my_args[0] = "sigperf1";
my_args[1] = "0";
my_args[2] = NULL;
execv("sigshooter1",my_args);
fprintf(stderr,"sigshooter1 cannot be executed by first child...");
exit(-1);
}
pid2 = fork();
if(pid2 < 0)
{
fprintf(stderr, ": fork failed: %s\n", strerror(errno));
exit(1);
}
if(pid2 == 0)
{
sprintf(str, "%d", pid1);
my_args[0] = "sigperf1";
my_args[1] = str;
my_args[2] = NULL;
// printf("this is converted = %s\n",my_args[1]);
//sleep(1);
execv("sigshooter1",my_args);
fprintf(stderr,"sigshooter1 cannot be executed by second child...");
exit(-1);
}
wid = wait(NULL);
}
You'll need a profiler for that. For starters, you can run perf stat ./a.out to get the total CPU time of all three processes, and perf stat -i ./a.out to get the CPU time of parent process only.
If you need something more detailed, take a look at more serious tools like valgrind or gprof.

Read status of FT245RL pins

Sorry for my ignorance but I am very new in FTDI chip Linux software development.
I have module based on FT245RL chip, programmed to be 4 port output (relays) and 4 port opto isolated input unit.
I found out in Internet program in C to turn on/off relays connected to outputs D0 to D3. After compiling it works properly. Below draft of this working program:
/* switch4.c
* # gcc -o switch4 switch4.c -L. -lftd2xx -Wl,-rpath,/usr/local/lib
* Usage
* # switch4 [0-15], for example # switch4 1
* */
#include <stdio.h>
#include <stdlib.h>
#include "./ftd2xx.h"
int main(int argc, char *argv[])
{
FT_STATUS ftStatus;
FT_HANDLE ftHandle0;
int parametr;
LPVOID pkod;
DWORD nBufferSize = 0x0001;
DWORD dwBytesWritten;
if(argc > 1) {
sscanf(argv[1], "%d", ¶metr);
}
else {
parametr = 0;
}
FT_SetVIDPID(0x5555,0x0001); // id from lsusb
FT_Open(0,&ftHandle0);
FT_SetBitMode(ftHandle0,15,1);
pkod=&parametr;
ftStatus = FT_Write(ftHandle0,pkod,nBufferSize,&dwBytesWritten);
ftStatus = FT_Close(ftHandle0);
}
My question is. How can I read in the same program, status of D4 to D7 pins, programmed as inputs? I mean about "printf" to stdout the number representing status (zero or one) of input pins (or all input/output pins).
Can anybody help newbie ?
UPDATE-1
This is my program with FT_GetBitMode
// # gcc -o read5 read5.c -L. -lftd2xx -Wl,-rpath,/usr/local/lib
#include <stdio.h>
#include <stdlib.h>
#include "./ftd2xx.h"
int main(int argc, char *argv[])
{
FT_STATUS ftStatus;
FT_HANDLE ftHandle0;
UCHAR BitMode;
FT_SetVIDPID(0x5555,0x0001); // id from lsusb
ftStatus = FT_Open(0,&ftHandle0);
if(ftStatus != FT_OK) {
printf("FT_Open failed");
return;
}
FT_SetBitMode(ftHandle0,15,1);
ftStatus = FT_GetBitMode(ftHandle0, &BitMode);
if (ftStatus == FT_OK) {
printf("BitMode contains - %d",BitMode);
}
else {
printf("FT_GetBitMode FAILED!");
}
ftStatus = FT_Close(ftHandle0);
}
But it returns "FT_GetBitMode FAILED!" instead value of BitMode
FT_GetBitMode returns the instantaneous value of the pins. A single byte will be
returned containing the current values of the pins, both those which are inputs and
those which are outputs.
Source.
Finally I found out whats going wrong. I used incorrect version of ftdi library. The correct version dedicated for x86_64 platform is located here:
Link to FTDI library

failed to parse number by yacc and lex

i have finished my lex file and start to learn about yacc
but i have some question about part of my code of lex:
%{
#include "y.tab.h"
int num_lines = 1;
int comment_mode=0;
int stack =0;
%}
digit ([0-9])
integer ({digit}+)
float_num ({digit}+\.{digit}+)
%%
{integer} { //deal with integer
printf("#%d: NUM:",num_lines); ECHO;printf("\n");
yylval.Integer = atoi(yytext);
return INT;
}
{float_num} {// deal with float
printf("#%d: NUM:",num_lines);ECHO;printf("\n");
yylval.Float = atof(yytext);
return FLOAT;
}
\n { ++num_lines; }
. if(strcmp(yytext," "))ECHO;
%%
int yywrap() {
return 1;
}
every time i got an integer or a float i return the token and save it into yylval
and here is my code in parser.y:
%{
#include <stdio.h>
#define YYDEBUG 1
void yyerror (char const *s) {
fprintf (stderr, "%s\n", s);
}
%}
%union{
int Integer;
float Float;
}
%token <int>INT;
%token <float>FLOAT;
%%
statement :
INT {printf("int yacc\n");}
| FLOAT {printf("float yacc\n");}
|
;
%%
int main(int argc, char** argv)
{
yyparse();
return 0;
}
which compiled by
byacc –d parser.y
lex lex.l
gcc lex.yy.c y.tab.c –ll
since i just want to try something easy to get started, i want to see if i can parse
only int and float number first, i print them in both .l and .y file after i input an
integer or a float.int the begining i input fisrt random number, for example 123
, then my program print :
1: NUM: 123
in yylex() and
"int yacc\n"
in parser.y
but if i input the second else number, it shows syntax error and the program shutdown
i dont know where is the problem.
is there any solution?
Your grammar only accepts a single token, either an INT or a FLOAT. So it will only accept a single number, which is why it produces a syntax error when it reads the second number; it is expecting an end-of-file.
The solution is to change the grammar so that it accepts any number of "statements":
program: /* EMPTY */
| program statement
;
Two notes:
1) You don't need an (expensive) strcmp in your lexer. Just do this:
" " /* Do nothing */;
. { return yytext[0]; }
It's better to return the unknown character to the parser, which will produce a syntax error if the character doesn't correspond to any token type (as in your simple grammar) than to just echo the character to stdout, which will prove confusing. Some people would prefer to produce an error message in the lexer for invalid input, but while you are developing a grammar I think it is easier to just pass through the characters, because that lets you add operators to your parser without regenerating the lexer.
2) When you specify %types in bison, you use the tagname from the union, not the C type. Some (but not all) versions of bison let you get away with using the C type if it is a simple type, but you can't count on it; it's not posix standard and it may well break if you use an older or newer version of bison. (For example, it won't work with bison 3.0.) So you should write, for example:
%union{
int Integer;
float Float;
}
%token <Integer>INT;
%token <Float>FLOAT;

programatic way to find ELF aux header (or envp) in shared library code?

I'm looking for a programatic way to find the powerpc cpu type on Linux. Performing some google searches associated an answer suggesting the mfpvr instruction I found that this is available in the ELF AUX header, and sure enough I can obtain the POWER5 string for the machine I'm running on with the following:
#include <stdio.h>
#include <elf.h>
int main( int argc, char **argv, char **envp )
{
/* walk past all env pointers */
while ( *envp++ != NULL )
;
/* and find ELF auxiliary vectors (if this was an ELF binary) */
#if 0
Elf32_auxv_t * auxv = (Elf32_auxv_t *) envp ;
#else
Elf64_auxv_t * auxv = (Elf64_auxv_t *) envp ;
#endif
char * platform = NULL ;
for ( ; auxv->a_type != AT_NULL ; auxv++ )
{
if ( auxv->a_type == AT_PLATFORM )
{
platform = (char *)auxv->a_un.a_val ;
break;
}
}
if ( platform )
{
printf( "%s\n", platform ) ;
}
return 0 ;
}
In the shared library context where I want to use this info I have no access to envp. Is there an alternate programatic method to find the beginning of the ELF AUX header?
You can get if from /proc/self/auxv file
According to man proc /proc/self/auxv is available since kernel level 2.6.0-test7.
Another option - get some (existing) environment variable - let say HOME,
or PATH, or whatever. Please note that you'll get it's ADDRESS. From here you can go back and find previous env variable, then one before it, etc. After that you can likewise skip all argv arguments. And then you get to the last AUXV entry. Some steps back - and you should be able find your AT_PLATFORM.
EDIT: It looks like glibc now provides a programatic method to get at this info:
glibc-headers-2.17-106: /usr/include/sys/auxv.h : getauxinfo()
Example:
#include <sys/auxv.h>
#include <stdio.h>
int main()
{
unsigned long v = getauxval( AT_PLATFORM ) ;
printf( "%s\n", (char *)v ) ;
return 0 ;
}

Why does lseek return 0?

lseek() is supposed to return the position of the file descriptor.
The documentation says:
Upon successful completion, lseek()
returns the resulting offset location
as measured in bytes from the
beginning of the file. Otherwise, a value of -1 is returned
and errno is set to indicate the
error.
Trouble is, not even this works:
#include <fcntl.h>
#include <stdio.h>
#include <errno.h>
printf("size off_t: %i\n", sizeof(off_t));
off_t pos;
pos = lseek(file, (off_t)0, SEEK_CUR);
printf("pos: %lli\n", pos);
// same result for SEEK_SET and SEEK_END
pos = lseek(file, (off_t)2352, SEEK_CUR);
printf("pos: %lli\n", pos);
This gives me:
size off_t: 8
pos: 0
pos: 0
Why is this? Is there an alternative to find the current offset, using the raw I/O functions? (read, open, lseek, …)
Edit 1:
I tried to make the example simpler.
Try adding #include <unistd.h> to the top.
See: http://forums.macosxhints.com/archive/index.php/t-35508.html
Basically, since you didn't #include <unistd.h>, the compiler is "guessing" that lseek() returns an int.
Probably an int is 4-bytes long, and since PPC is "big-endian" byte order, you're getting the "top" 4 bytes, which are all zero.
Include unistd.h lets the compiler realize that lseek() is returning an off_t, so you don't lose half the bytes.
Something else is up, probably something silly. I tried your code, as here:
#include <fcntl.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
off_t pos;
int file ;
if((file = open("/Users/chasrmartin/.bash_history",O_RDONLY)) == -1){
perror(argv[0]);
exit(1);
}
printf("size off_t: %i\n", sizeof(off_t));
pos = lseek(file, (off_t)0, SEEK_CUR);
printf("pos: %lli\n", pos);
// same result for SEEK_SET and SEEK_END
pos = lseek(file, (off_t)2352, SEEK_CUR);
printf("pos: %lli\n", pos);
exit(0);
}
and get this result:
bash $ gcc foo.c
bash $ ./a.out
size off_t: 8
pos: 0
pos: 2352
(Just to be definite, this is on Mac OS/X 10.5.6 on Intel.)
Update.
Or maybe it's not silly. I just tried it on a PPC G5, and get the results you do.
Update 2
Okay, here's the result on a PPC:
$ gcc foo.c
$ ./a.out
size off_t: 8
pos: 0
pos: 0
What kind of file is it? Is it a pipe by any chance? Because if it's anything but a regular file, chances are it doesn't support seeking:
The behavior of lseek() on devices which are incapable of seeking is implementation-defined. The value of the file offset associated with such a device is undefined.
I'm not sure I understand your question, but here are a few thoughts which might help.
Offset 0 is valid; it means you are at the beginning of the file
Depending on your platform, off_t may well be limited to 32 bits unsigned.
Are you intending to seek relative to your current position?
-- MarkusQ
You might want to change the test to:
if ( (pos = lseek(file, (off_t)i, SEEK_CUR)) != -1 ) {
You are probably hitting a -1 somewhere, but you're testing for 0 here.