multilevel Debug using c preprocessor macros - c

I have excerpts of code for a multi-level debug implementation, which I don't know how to make it work.
I have tried some of the suggestions posted here about using the do {...} while (0), and I also tried to declare a global variable called Debug, but none of them seem to work.
What should I do?
#include <stdio.h>
#include <stdlib.h>
//#define DEBUG(fmt, ...) fprintf (stderr, fmt, __VA_ARGS__ )
#ifdef DEBON
#define DEBUG(level, fmt, ...) \
if (Debug >= level) \
fprintf (stderr, fmt, __VA_ARGS__)
#else
#define DEBUG(level, fmt, ...)
#endif
int process ( int i1, int i2)
{
int val;
DEBUG (1, "process (%i, %i)\n", i1, i2);
val = i1 * i2;
DEBUG (3, "return %i\n", val);
return val;
}
int main ( int argc, char *argv[])
{
int arg1 = 0, arg2 = 0;
if (argc > 1)
arg1 = atoi (argv[1]);
if ( argc == 3)
arg2 = atoi (argv[2]);
DEBUG (1, "processed %i arguments\n", argc -1 );
DEBUG (3, "arg1 = %i, arg2 = %i\n" , arg1, arg2);
printf ("%d\n", process (arg1, arg2));
return 0;
}
Below is a simpler file I put together to see if I can get this working. No luck yet.
#define DEBUG(level, fmt, ...) if (Debug >= level ) fprintf (stderr, fmt, __VA_ARGS__)
#include <stdio.h>
int Debug;
int main()
{
int i1 = 1;
int i2 = 2;
DEBUG(3, "process (%i, %i)\n", i1, i2);
}

You last example works after minor tweaks. The idea in the book is to have your program parse the command line options and set the value of a global variable named Debug.
#include <stdio.h>
#include <stdlib.h>
#define DEBUG(level, fmt, ...) do if (Debug >= level) fprintf(stderr, fmt, __VA_ARGS__); while (0)
int Debug = 1; // default debug level == 1
int main(int argc, char *argv[])
{
int i1 = 1;
int i2 = 2;
size_t i;
for(i = 1; i < argc; ++i)
if ((argv[i][0] == '-') && (argv[i][1] == 'd'))
Debug = strtol(argv[i] + 2, 0, 10);
DEBUG(3, "process (%i, %i)\n", i1, i2);
return 0;
}

Related

How to execute a terminal command in C?

I'm writing a program in C. I want to get the current hour,minute, second, and nanosecond in the form of H:M:S:3N. Basically. echo "$(date +' %H:%M:%S:%3N')" command does what I want. How can I execute it in my C code and print the result?
Any help is appreciated!
You are looking for strftime. eg:
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
int
main(int argc, char **argv)
{
int rv = EXIT_SUCCESS;
struct timeval tv;
struct tm *tm;
char *default_args[] = { "%H:%M:%S %B %d, %Y", NULL };
if( gettimeofday(&tv, NULL) == -1 ){
perror("gettimeofday");
exit(1);
}
argv = argc < 2 ? default_args : argv + 1;
tm = gmtime(&tv.tv_sec);
for( ; *argv; argv += 1 ){
char buf[1024];
const char *fmt = *argv;
if( strftime(buf, sizeof buf, fmt, tm) ){
printf("%s\n", buf);
} else {
fprintf(stderr, "Error formatting %s\n", fmt);
rv = EXIT_FAILURE;
}
}
return rv;
}
Note that %N is not generally supported by strftime, so you'll have to parse nano seconds manually.

using memfd_create and fexecve to run ELF from memory

I know other people have done it in different languages but I cannot find a C code example at all, the most common was in Perl and it was really confusing because I don't know Perl
and I just want to load a binary file (from disk) into memory and then execute it
https://magisterquis.github.io/2018/03/31/in-memory-only-elf-execution.html
Here you go, an example writen in C (compiled on linux 5.4 and run as expected):
#define _GNU_SOURCE
#define _POSIX_C_SOURCE 200809L
#include <sys/types.h>
#include <sys/mman.h>
#include <unistd.h>
#include <err.h>
#include <errno.h>
size_t min(size_t x, size_t y)
{
return x > y ? y : x;
}
/**
* #param len != 0
*/
void fdput(int fd, const char *str, size_t len)
{
size_t cnt = 0;
do {
ssize_t result = write(fd, str + cnt, min(len - cnt, 0x7ffff000));
if (result == -1) {
if (errno == EINTR)
continue;
err(1, "%s failed", "write");
}
cnt += result;
} while (cnt != len);
}
#define fdputc(fd, constant_str) fdput((fd), (constant_str), sizeof(constant_str) - 1)
int main(int argc, char* argv[])
{
int fd = memfd_create("script", 0);
if (fd == -1)
err(1, "%s failed", "memfd_create");
fdputc(fd, "#!/bin/bash\necho Hello, world!");
{
const char * const argv[] = {"script", NULL};
const char * const envp[] = {NULL};
fexecve(fd, (char * const *) argv, (char * const *) envp);
}
err(1, "%s failed", "fexecve");
}
I also tested with calling fork() just before fexecve, and it also works as expected.
Here's the code (mostly identical to the one provides above):
#define _GNU_SOURCE
#define _POSIX_C_SOURCE 200809L
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <unistd.h>
#include <err.h>
#include <errno.h>
size_t min(size_t x, size_t y)
{
return x > y ? y : x;
}
/**
* #param len != 0
*/
void fdput(int fd, const char *str, size_t len)
{
size_t cnt = 0;
do {
ssize_t result = write(fd, str + cnt, min(len - cnt, 0x7ffff000));
if (result == -1) {
if (errno == EINTR)
continue;
err(1, "%s failed", "write");
}
cnt += result;
} while (cnt != len);
}
#define fdputc(fd, constant_str) fdput((fd), (constant_str), sizeof(constant_str) - 1)
int main(int argc, char* argv[])
{
int fd = memfd_create("script", 0);
if (fd == -1)
err(1, "%s failed", "memfd_create");
fdputc(fd, "#!/bin/bash\necho Hello, world!");
pid_t pid = fork();
if (pid == 0) {
const char * const argv[] = {"script", NULL};
const char * const envp[] = {NULL};
fexecve(fd, (char * const *) argv, (char * const *) envp);
err(1, "%s failed", "fexecve");
} else if (pid == -1)
err(1, "%s failed", "fork");
wait(NULL);
return 0;
}

Copy block device with multiple Threads

I am trying to figure out what am i doing wrong when trying to compare and copy device block with pthreads in parallel. it looks like i am getting out of SYNC and the compare phase is not working properly. any help will be appreciated
#ifndef __dbg_h__
#define __dbg_h__
#define _LARGEFILE64_SOURCE
#define _GNU_SOURCE
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <linux/fs.h>
#include <pthread.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdint.h>
#ifdef NDEBUG
#define debug(M, ...)
#else
#define debug(M, ...) fprintf(stderr, "DEBUG %s %s %s:%d: " M "\n", __DATE__, __TIME__, __FILE__, __LINE__, ##__VA_ARGS__)
#endif
#define clean_errno() (errno == 0 ? "None" : strerror(errno))
#define log_err(M, ...) fprintf(stderr, "[ERROR] %s %s (%s:%d: errno: %s) " M "\n", __DATE__, __TIME__, __FILE__, __LINE__, clean_errno(), ##__VA_ARGS__)
#define log_warn(M, ...) fprintf(stderr, "[WARN] %s %s (%s:%d: errno: %s) " M "\n", __DATE__, __TIME__, __FILE__, __LINE__, clean_errno(), ##__VA_ARGS__)
#define log_info(M, ...) fprintf(stderr, "[INFO] %s %s (%s:%d) " M "\n", __DATE__, __TIME__, __FILE__, __LINE__, ##__VA_ARGS__)
#endif
#define blksize 8192
void *compare_devices(void *arguments);
struct arg_struct {
char device_name_a[1024];
char device_name_b[1024];
off_t start_offset;
off_t end_offset;
int thread_number;
int sub_total;
};
int main(int argc, char **argv)
{
int fd;
long numblocks=0;
int i;
int err;
long total_different_size=0;
int number_of_threads=16;
struct arg_struct compare_devices_args[number_of_threads];
fd = open(argv[1], O_RDONLY);
ioctl(fd, BLKGETSIZE, &numblocks);
close(fd);
log_info("Number of blocks: %lu, this makes %.3f GB\n",
numblocks,
(double)numblocks * 512.0 / (1024 * 1024 * 1024));
//read_whole_device(argv[1]);
long number_of_bytes_per_thread;
number_of_bytes_per_thread=numblocks*512/(long)number_of_threads;
pthread_t tid[number_of_threads];
for (i=0; i<number_of_threads; i++) {
strcpy(compare_devices_args[i].device_name_a, argv[1]);
strcpy(compare_devices_args[i].device_name_b, argv[2]);
compare_devices_args[i].start_offset=(long)(i*number_of_bytes_per_thread);
compare_devices_args[i].end_offset=(long)((i+1)*number_of_bytes_per_thread-1);
compare_devices_args[i].thread_number=i+1;
err = pthread_create(&(tid[i]), NULL, &compare_devices,(void*)&compare_devices_args[i]);
if (err != 0) {
printf("\ncan't create thread :[%s]", strerror(err));
return -1;
}
}
for (i=0; i<number_of_threads; i++) {
pthread_join(tid[i], NULL);
total_different_size+=(long)compare_devices_args[i].sub_total;
}
printf ("Total of Different size between devices - %ld\n",total_different_size);
};
int read_n_bytes_from(int fd, off_t pos, char *buf, int n)
{
if (lseek(fd, pos, SEEK_SET) >= 0)
return read(fd, buf, n);
else
return -1;
}
void read_whole_device(char* device_name)
{
int fd;
char buf[1024*1024];
size_t size;
int counter=0;
log_info("reading device %s\n",device_name);
fd = open(device_name, O_RDONLY|O_NONBLOCK);
//ssize_t size = read(fd, &buf, 1024);
lseek(fd, 0, SEEK_SET);
while ( (size=read(fd, buf, 1024*1024)) > 0 ) {
printf("Read buffer %d - %d\n", size, counter);
counter++;
}
close(fd);
}
void write_block_to_device(int fd,off_t pos,char* buf, int n)
{
if (lseek(fd, pos, SEEK_SET) >= 0) {
//write
}
}
void compare_buffer(char* buf_first,char* buf_second,int length, int blk_size, int* result)
{
int i;
char buf_cpy[blk_size];
for (i=0; i<=(length/blk_size);i++)
{
if ( memcmp(buf_first+(blk_size*i), buf_second+(blk_size*i), blk_size) != 0) {
//printf ("Block %d is different\n",i);
result[i]=1;
}
else {
result[i]=0;
}
}
}
void *compare_devices(void *arguments)
{
struct arg_struct *args = arguments;
int fd_first,fd_second;
char buf_first[1024*1024];
char buf_second[1024*104];
int size_first,size_second;
int counter=0;
int result[128];
int memcmp_result;
int i;
off_t pos,pos_first,pos_second;
int total_number_of_different_blocks,difference_in_mb;
long number_of_mb_to_scan=0;
total_number_of_different_blocks=0;
log_info("Thread %d - compare devices %s,%s - start %ld end %ld\n",args->thread_number,args->device_name_a,args->device_name_b,args->start_offset,args->end_offset);
fd_first = open(args->device_name_a, O_RDONLY);
fd_second = open(args->device_name_b, O_RDONLY);
log_info("Thread %d - %d %d\n",args->thread_number,fd_first,fd_second);
log_info("Thread %d - before lseek - %ld %ld\n",args->thread_number,lseek(fd_first, 0, SEEK_CUR),lseek(fd_second, 0, SEEK_CUR));
lseek(fd_first, (off_t)args->start_offset, SEEK_SET);
lseek(fd_second, (off_t)args->start_offset, SEEK_SET);
log_info("Thread %d - after lseek - %ld %ld\n",args->thread_number,lseek(fd_first, 0, SEEK_CUR),lseek(fd_second, 0, SEEK_CUR));
log_info("Thread %d - start %ld , %ld\n",args->thread_number,lseek(fd_first, 0, SEEK_CUR),lseek(fd_second, 0, SEEK_CUR));
number_of_mb_to_scan=(args->end_offset-args->start_offset)/1024/1024;
log_info("Thread %d - Number of MB to scan %ld - start offset %ld\n",args->thread_number,number_of_mb_to_scan,lseek(fd_second, 0, SEEK_CUR));
memset(buf_first, 0, sizeof(buf_first));
memset(buf_second, 0, sizeof(buf_second));
while ( (size_first=read(fd_first, buf_first, 1024*1024)) > 0 ) {
size_second=read(fd_second,buf_second, 1024*1024);
pos_first=lseek(fd_first, 0, SEEK_CUR);
pos_second=lseek(fd_second, 0, SEEK_CUR);
log_info("Thread %d - fd (%d,%d) pos_first %lld, pos_second %lld (%d - %d) - read %d,%d\n",args->thread_number,fd_first,fd_second,(unsigned long long)pos_first-1024*1024,(unsigned long long)pos_second-1024*1024,sizeof(off_t),sizeof(pos),size_first,size_second);
//log_info("Thread %s - Hash Buf A - %ld Hash Buf B - %ld",args->thread_number,adler32(buf_first,size_first),adler32(buf_second,size_second));
if ( (memcmp_result=memcmp(buf_first, buf_second, sizeof(buf_second))) != 0 ) {
log_info("Thread %d - Found 1MB chunck which is different at pos %lld - %d (%d)\n",args->thread_number,(unsigned long long)pos_first-1024*1024, memcmp_result,sizeof(buf_first));
compare_buffer(buf_first,buf_second,1024*1024,blksize,result);
for (i=0; i<=128; i++) {
if ( result[i] == 1 ) {
//printf ("%d,",result[i]);
total_number_of_different_blocks++;
}
}
}
if ( pos_first > args->end_offset ) {
break;
}
memset(buf_first, 0, sizeof(buf_first));
memset(buf_second, 0, sizeof(buf_second));
counter++;
}
log_info("Thread %d - Number of MB to scan %ld - end offset %ld\n",args->thread_number,number_of_mb_to_scan,lseek(fd_first, 0, SEEK_CUR));
log_info("Thread %d - Completed - Scanning %d of 1MB chuncks\n",args->thread_number,counter);
log_info("Thread %d - Diffence of size between %s to %s starting at %ld and ending at %ld- %d different blocks of 8k - %dMB\n",args->thread_number,args->device_name_a,args->device_name_b,args->start_offset,args->end_offset,total_number_of_different_blocks,total_number_of_different_blocks*8192/1024/1024);
args->sub_total=total_number_of_different_blocks/8/1024;
close(fd_first);
close(fd_second);
pthread_exit(arguments);
}
Updated version:
#ifndef __dbg_h__
#define __dbg_h__
#define _LARGEFILE64_SOURCE
#define _GNU_SOURCE
#define _FILE_OFFSET_BITS 64
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <linux/fs.h>
#include <pthread.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdint.h>
#include <getopt.h>
#include <openssl/sha.h>
#include <sched.h>
#ifdef NDEBUG
#define debug(M, ...)
#else
#define debug(M, ...) fprintf(stderr, "DEBUG %s %s %s:%d: " M "\n", __DATE__, __TIME__, __FILE__, __LINE__, ##__VA_ARGS__)
#endif
#define clean_errno() (errno == 0 ? "None" : strerror(errno))
#define log_err(M, ...) fprintf(stderr, "[ERROR] %s %s (%s:%d: errno: %s) " M "\n", __DATE__, __TIME__, __FILE__, __LINE__, clean_er
rno(), ##__VA_ARGS__)
#define log_warn(M, ...) fprintf(stderr, "[WARN] %s %s (%s:%d: errno: %s) " M "\n", __DATE__, __TIME__, __FILE__, __LINE__, clean_er
rno(), ##__VA_ARGS__)
#define log_info(M, ...) fprintf(stderr, "[INFO] %s %s (%s:%d) " M "\n", __DATE__, __TIME__, __FILE__, __LINE__, ##__VA_ARGS__)
#endif
#ifndef _TRY_THROW_CATCH_H_
#define _TRY_THROW_CATCH_H_
#include <setjmp.h>
#define TRY do { jmp_buf ex_buf__; switch( setjmp(ex_buf__) ) { case 0: while(1) {
#define CATCH(x) break; case x:
#define FINALLY break; } default: {
#define ETRY break; } } }while(0)
#define THROW(x) longjmp(ex_buf__, x)
#endif /*!_TRY_THROW_CATCH_H_*/
unsigned long long chunck_size=1024*1024;
int blksize=16384;
int cb=0;
void *compare_devices(void *arguments);
struct arg_struct {
char device_name_a[1024];
char device_name_b[1024];
off64_t start_offset;
off64_t end_offset;
int thread_number;
int sub_total;
};
int main(int argc, char **argv)
{
int fd,s_is_set=0,d_is_set=0,copy_blocks=0,num_cpus;
int opt;
char *source_device,*dest_device,*blksize_string,*number_of_threads_string;
long numblocks_src=0,numblocks_dst=0;
int i;
int err,policy;
long total_different_size=0;
int number_of_threads=16;
int newprio, set_thread_priority=0;
pthread_attr_t tattr;
struct sched_param param;
while ((opt = getopt(argc, argv, "s:d:b:p:t:c")) != -1) {
switch (opt) {
case 's':
source_device = optarg;
log_info("source device is %s\n",source_device);
s_is_set=1;
if( access( source_device, F_OK ) != -1 ) {
log_info("source device is accessible\n");
}
else {
log_err("cannot access source device\n");
return -1;
}
break;
case 'd':
dest_device = optarg;
log_info("dest device is %s\n",dest_device);
d_is_set=1;
if( access( dest_device, F_OK ) != -1 ) {
log_info("dest device is accessible\n");
}
else {
log_err("cannot access dest device\n");
return -1;
}
break;
case 'b':
blksize = atoi(optarg);
if (blksize%4096 != 0) {
log_err("Block Size is not multiple of 4k\n");
return -1;
}
else
log_info("block size is %d\n",blksize);
break;
case 't':
number_of_threads = atoi(optarg);
num_cpus = sysconf( _SC_NPROCESSORS_ONLN );
if ( number_of_threads%2 != 0 ) {
log_err("Number of threads are not multiple of 2\n");
return -1;
}
else
log_info("number of threads is %d - number of cores %d\n",number_of_threads,num_cpus);
if ( number_of_threads > num_cpus ) {
number_of_threads=num_cpus;
}
break;
case 'c':
copy_blocks=1;
cb=1;
break;
case 'p':
if ( optarg != NULL ) {
newprio=atoi(optarg);
set_thread_priority=1;
}
break;
case ':':
log_info("%s: option '-%c' requires an argument\n",argv[0], optopt);
break;
case '?':
default:
log_info("%s: option '-%c' is invalid: ignored\n",argv[0], optopt);
break;
}
}
if ( s_is_set != 1 || d_is_set !=1 ) {
log_err("Source device and Destination device must be specified\n");
return -1;
}
struct arg_struct compare_devices_args[number_of_threads];
fd = open(source_device, O_RDONLY);
ioctl(fd, BLKGETSIZE, &numblocks_src);
close(fd);
log_info("Number of blocks in source device: %lu, this makes %.3f GB\n", numblocks_src, (double)numblocks_src * 512.0 / (1024 * 102
4 * 1024));
fd = open(dest_device, O_RDONLY);
ioctl(fd, BLKGETSIZE, &numblocks_dst);
close(fd);
log_info("Number of blocks in destination is device: %lu, this makes %.3f GB\n", numblocks_dst, (double)numblocks_dst * 512.0 / (10
24 * 1024 * 1024));
if ( numblocks_src > numblocks_dst ) {
log_info("Number of blocks in source device is larger then number of blocks in destination device");
return -1;
}
long number_of_bytes_per_thread;
number_of_bytes_per_thread=numblocks_src*512/(long)number_of_threads;
pthread_t tid[number_of_threads];
for (i=0; i<number_of_threads; i++) {
strcpy(compare_devices_args[i].device_name_a, source_device);
strcpy(compare_devices_args[i].device_name_b, dest_device);
compare_devices_args[i].start_offset=(long)(i*number_of_bytes_per_thread);
compare_devices_args[i].end_offset=(long)((i+1)*number_of_bytes_per_thread-1);
compare_devices_args[i].thread_number=i+1;
if ( set_thread_priority == 1 ) {
err = pthread_attr_init (&tattr);
policy = SCHED_RR;
err = pthread_attr_setschedpolicy(&tattr, policy);
if (err != 0) {
log_err("\nThread %d - Unable to set scheduler policy attributes :[%s]", i+1, strerror(err));
}
err = pthread_attr_getschedparam (&tattr, &param);
if (err != 0) {
log_err("\nThread %d - Unable to get scheduler priority attributes :[%s]", i+1, strerror(err));
}
log_info("\nThread %d - Old thread priority is %d",i+1,param.sched_priority);
param.sched_priority = newprio;
log_info("\nThread %d - Setting pthread priority to %d",i+1,newprio);
err = pthread_attr_setschedparam (&tattr, &param);
if (err != 0) {
log_err("\nThread %d - Unable to set scheduler attributes :[%s]", i+1, strerror(err));
}
err = pthread_create(&(tid[i]), &tattr, &compare_devices,(void*)&compare_devices_args[i]);
}
else
{
err = pthread_create(&(tid[i]), NULL, &compare_devices,(void*)&compare_devices_args[i]);
}
if (err != 0) {
log_err("\nThread %d - can't create thread :[%s]", i+1, strerror(err));
return -1;
}
}
for (i=0; i<number_of_threads; i++) {
pthread_join(tid[i], NULL);
total_different_size+=(long)compare_devices_args[i].sub_total;
}
log_info ("Total of Different size between devices - %ld\n",total_different_size);
};
void compare_buffer(char* buf_first,char* buf_second,int length, int blk_size, int* result)
{
int i;
char buf_cpy[blk_size];
for (i=0; i<=(length/blk_size);i++)
{
if ( memcmp(buf_first+(blk_size*i), buf_second+(blk_size*i), blk_size) != 0) {
result[i]=1;
}
else {
result[i]=0;
}
}
}
void *compare_devices(void *arguments)
{
struct arg_struct *args = arguments;
int fd_first,fd_second;
char buf_first[chunck_size];
char buf_second[chunck_size];
int size_first,size_second;
unsigned int counter=0;
int result[chunck_size/blksize];
int memcmp_result;
unsigned long long i;
off64_t pos,pos_first,pos_second;
unsigned long long total_number_of_different_blocks,difference_in_mb;
long number_of_mb_to_scan=0;
total_number_of_different_blocks=0;
log_info("Thread %d - compare devices %s,%s - start %llu end %llu\n",args->thread_number,args->device_name_a,args->device_nam
e_b,args->start_offset,args->end_offset);
fd_first = open(args->device_name_a, O_RDONLY);
if ( cb == 0 ) {
fd_second = open(args->device_name_b, O_RDONLY);
}
else
fd_second = open(args->device_name_b, O_RDWR);
lseek64(fd_first, (off64_t)args->start_offset, SEEK_SET);
lseek64(fd_second, (off64_t)args->start_offset, SEEK_SET);
number_of_mb_to_scan=(args->end_offset-args->start_offset)/chunck_size;
debug("Thread %d - Number of MB to scan %ld - start offset %ld\n",args->thread_number,number_of_mb_to_scan,lseek64(fd_second,
0, SEEK_CUR));
memset(buf_first, 0, sizeof(buf_first));
memset(buf_second, 0, sizeof(buf_second));
while ( (size_first=read(fd_first, buf_first, chunck_size)) > 0 && counter <= number_of_mb_to_scan ) {
size_second=read(fd_second,buf_second, chunck_size);
pos_first=lseek64(fd_first, 0, SEEK_CUR);
pos_second=lseek64(fd_second, 0, SEEK_CUR);
if ( (memcmp_result=memcmp(buf_first, buf_second, sizeof(buf_second))) != 0 ) {
debug("Thread %d - Found 1MB chunck which is different at pos %llu - %d (%d)\n",args->thread_number,(unsigned
long long)pos_first-chunck_size, memcmp_result,sizeof(buf_first));
compare_buffer(buf_first,buf_second,chunck_size,blksize,result);
for (i=0; i<=chunck_size/blksize; i++) {
if ( result[i] == 1 ) {
if ( cb == 1 ) {
debug("Thread %d - chunck %d - copying block %d - location of block in device file %llu",
args->thread_number, counter+1, i, args->start_offset+(unsigned long long)(chunck_size*counter)+(unsigned long long)(i*blksize));
lseek64(fd_first,args->start_offset+(off64_t)(chunck_size*counter)+(off64_t)(i*blksize),S
EEK_SET);
lseek64(fd_second,args->start_offset+(off64_t)(chunck_size*counter)+(off64_t)(i*blksize),
SEEK_SET);
size_first=read(fd_first, buf_first, blksize);
size_second=write(fd_second,buf_first,size_first);
if ( size_second != blksize ) {
log_err("Thread %d - Houston we have a problem in copying block number %llu",args->th
read_number, (unsigned long long)args->start_offset+(unsigned long long)(chunck_size*counter)+(unsigned long long)(i*blksize));
}
}
total_number_of_different_blocks++;
}
}
}
if ( cb == 1) {
lseek64(fd_second,(off64_t)args->start_offset+(off64_t)(chunck_size*(counter+1)),SEEK_SET);
lseek64(fd_first,(off64_t)args->start_offset+(off64_t)(chunck_size*(counter+1)),SEEK_SET);
}
if ( pos_first > args->end_offset ) {
break;
}
memset(buf_first, 0, sizeof(buf_first));
memset(buf_second, 0, sizeof(buf_second));
debug("Thread %d - chunck %d out of %d done - %llu %llu", args->thread_number, counter+1, number_of_mb_to_scan,pos_fi
rst,args->end_offset);
counter++;
}
log_info("Thread %d - Number of MB to scan %ld - end offset %llu\n",args->thread_number,number_of_mb_to_scan,lseek64(fd_first
, 0, SEEK_CUR));
log_info("Thread %d - Completed - Scanning %d of 1MB chuncks\n",args->thread_number,counter);
log_info("Thread %d - Difference of size between %s to %s starting at %llu and ending at %llu- %d different blocks of %d - %d
MB\n",args->thread_number,args->device_name_a,args->device_name_b,args->start_offset,args->end_offset,total_number_of_different_block
s,blksize,total_number_of_different_blocks*blksize/chunck_size);
args->sub_total=total_number_of_different_blocks*blksize/1024;
close(fd_first);
close(fd_second);
pthread_exit(arguments);
}
#ifndef __dbg_h__
#define __dbg_h__
#define _LARGEFILE64_SOURCE
#define _GNU_SOURCE
#define _FILE_OFFSET_BITS 64
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <linux/fs.h>
#include <pthread.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdint.h>
#include <getopt.h>
#include <openssl/sha.h>
#include <sched.h>
#ifdef NDEBUG
#define debug(M, ...)
#else
#define debug(M, ...) fprintf(stderr, "DEBUG %s %s %s:%d: " M "\n", __DATE__, __TIME__, __FILE__, __LINE__, ##__VA_ARGS__)
#endif
#define clean_errno() (errno == 0 ? "None" : strerror(errno))
#define log_err(M, ...) fprintf(stderr, "[ERROR] %s %s (%s:%d: errno: %s) " M "\n", __DATE__, __TIME__, __FILE__, __LINE__, clean_er
rno(), ##__VA_ARGS__)
#define log_warn(M, ...) fprintf(stderr, "[WARN] %s %s (%s:%d: errno: %s) " M "\n", __DATE__, __TIME__, __FILE__, __LINE__, clean_er
rno(), ##__VA_ARGS__)
#define log_info(M, ...) fprintf(stderr, "[INFO] %s %s (%s:%d) " M "\n", __DATE__, __TIME__, __FILE__, __LINE__, ##__VA_ARGS__)
#endif
#ifndef _TRY_THROW_CATCH_H_
#define _TRY_THROW_CATCH_H_
#include <setjmp.h>
#define TRY do { jmp_buf ex_buf__; switch( setjmp(ex_buf__) ) { case 0: while(1) {
#define CATCH(x) break; case x:
#define FINALLY break; } default: {
#define ETRY break; } } }while(0)
#define THROW(x) longjmp(ex_buf__, x)
#endif /*!_TRY_THROW_CATCH_H_*/
unsigned long long chunck_size=1024*1024;
int blksize=16384;
int cb=0;
void *compare_devices(void *arguments);
struct arg_struct {
char device_name_a[1024];
char device_name_b[1024];
off64_t start_offset;
off64_t end_offset;
int thread_number;
int sub_total;
};
int main(int argc, char **argv)
{
int fd,s_is_set=0,d_is_set=0,copy_blocks=0,num_cpus;
int opt;
char *source_device,*dest_device,*blksize_string,*number_of_threads_string;
long numblocks_src=0,numblocks_dst=0;
int i;
int err,policy;
long total_different_size=0;
int number_of_threads=16;
int newprio, set_thread_priority=0;
pthread_attr_t tattr;
struct sched_param param;
while ((opt = getopt(argc, argv, "s:d:b:p:t:c")) != -1) {
switch (opt) {
case 's':
source_device = optarg;
log_info("source device is %s\n",source_device);
s_is_set=1;
if( access( source_device, F_OK ) != -1 ) {
log_info("source device is accessible\n");
}
else {
log_err("cannot access source device\n");
return -1;
}
break;
case 'd':
dest_device = optarg;
log_info("dest device is %s\n",dest_device);
d_is_set=1;
if( access( dest_device, F_OK ) != -1 ) {
log_info("dest device is accessible\n");
}
else {
log_err("cannot access dest device\n");
return -1;
}
break;
case 'b':
blksize = atoi(optarg);
if (blksize%4096 != 0) {
log_err("Block Size is not multiple of 4k\n");
return -1;
}
else
log_info("block size is %d\n",blksize);
break;
case 't':
number_of_threads = atoi(optarg);
num_cpus = sysconf( _SC_NPROCESSORS_ONLN );
if ( number_of_threads%2 != 0 ) {
log_err("Number of threads are not multiple of 2\n");
return -1;
}
else
log_info("number of threads is %d - number of cores %d\n",number_of_threads,num_cpus);
if ( number_of_threads > num_cpus ) {
number_of_threads=num_cpus;
}
break;
case 'c':
copy_blocks=1;
cb=1;
break;
case 'p':
if ( optarg != NULL ) {
newprio=atoi(optarg);
set_thread_priority=1;
}
break;
case ':':
log_info("%s: option '-%c' requires an argument\n",argv[0], optopt);
break;
case '?':
default:
log_info("%s: option '-%c' is invalid: ignored\n",argv[0], optopt);
break;
}
}
if ( s_is_set != 1 || d_is_set !=1 ) {
log_err("Source device and Destination device must be specified\n");
return -1;
}
struct arg_struct compare_devices_args[number_of_threads];
fd = open(source_device, O_RDONLY);
ioctl(fd, BLKGETSIZE, &numblocks_src);
close(fd);
log_info("Number of blocks in source device: %lu, this makes %.3f GB\n", numblocks_src, (double)numblocks_src * 512.0 / (1024 * 102
4 * 1024));
fd = open(dest_device, O_RDONLY);
ioctl(fd, BLKGETSIZE, &numblocks_dst);
close(fd);
log_info("Number of blocks in destination is device: %lu, this makes %.3f GB\n", numblocks_dst, (double)numblocks_dst * 512.0 / (10
24 * 1024 * 1024));
if ( numblocks_src > numblocks_dst ) {
log_info("Number of blocks in source device is larger then number of blocks in destination device");
return -1;
}
long number_of_bytes_per_thread;
number_of_bytes_per_thread=numblocks_src*512/(long)number_of_threads;
pthread_t tid[number_of_threads];
for (i=0; i<number_of_threads; i++) {
strcpy(compare_devices_args[i].device_name_a, source_device);
strcpy(compare_devices_args[i].device_name_b, dest_device);
compare_devices_args[i].start_offset=(long)(i*number_of_bytes_per_thread);
compare_devices_args[i].end_offset=(long)((i+1)*number_of_bytes_per_thread-1);
compare_devices_args[i].thread_number=i+1;
if ( set_thread_priority == 1 ) {
err = pthread_attr_init (&tattr);
policy = SCHED_RR;
err = pthread_attr_setschedpolicy(&tattr, policy);
if (err != 0) {
log_err("\nThread %d - Unable to set scheduler policy attributes :[%s]", i+1, strerror(err));
}
err = pthread_attr_getschedparam (&tattr, &param);
if (err != 0) {
log_err("\nThread %d - Unable to get scheduler priority attributes :[%s]", i+1, strerror(err));
}
log_info("\nThread %d - Old thread priority is %d",i+1,param.sched_priority);
param.sched_priority = newprio;
log_info("\nThread %d - Setting pthread priority to %d",i+1,newprio);
err = pthread_attr_setschedparam (&tattr, &param);
if (err != 0) {
log_err("\nThread %d - Unable to set scheduler attributes :[%s]", i+1, strerror(err));
}
err = pthread_create(&(tid[i]), &tattr, &compare_devices,(void*)&compare_devices_args[i]);
}
else
{
err = pthread_create(&(tid[i]), NULL, &compare_devices,(void*)&compare_devices_args[i]);
}
if (err != 0) {
log_err("\nThread %d - can't create thread :[%s]", i+1, strerror(err));
return -1;
}
}
for (i=0; i<number_of_threads; i++) {
pthread_join(tid[i], NULL);
total_different_size+=(long)compare_devices_args[i].sub_total;
}
log_info ("Total of Different size between devices - %ld\n",total_different_size);
};
void compare_buffer(char* buf_first,char* buf_second,int length, int blk_size, int* result)
{
int i;
char buf_cpy[blk_size];
for (i=0; i<=(length/blk_size);i++)
{
if ( memcmp(buf_first+(blk_size*i), buf_second+(blk_size*i), blk_size) != 0) {
result[i]=1;
}
else {
result[i]=0;
}
}
}
void *compare_devices(void *arguments)
{
struct arg_struct *args = arguments;
int fd_first,fd_second;
char buf_first[chunck_size];
char buf_second[chunck_size];
int size_first,size_second;
unsigned int counter=0;
int result[chunck_size/blksize];
int memcmp_result;
unsigned long long i;
off64_t pos,pos_first,pos_second;
unsigned long long total_number_of_different_blocks,difference_in_mb;
long number_of_mb_to_scan=0;
total_number_of_different_blocks=0;
log_info("Thread %d - compare devices %s,%s - start %llu end %llu\n",args->thread_number,args->device_name_a,args->device_nam
e_b,args->start_offset,args->end_offset);
fd_first = open(args->device_name_a, O_RDONLY);
if ( cb == 0 ) {
fd_second = open(args->device_name_b, O_RDONLY);
}
else
fd_second = open(args->device_name_b, O_RDWR);
lseek64(fd_first, (off64_t)args->start_offset, SEEK_SET);
lseek64(fd_second, (off64_t)args->start_offset, SEEK_SET);
number_of_mb_to_scan=(args->end_offset-args->start_offset)/chunck_size;
debug("Thread %d - Number of MB to scan %ld - start offset %ld\n",args->thread_number,number_of_mb_to_scan,lseek64(fd_second,
0, SEEK_CUR));
memset(buf_first, 0, sizeof(buf_first));
memset(buf_second, 0, sizeof(buf_second));
while ( (size_first=read(fd_first, buf_first, chunck_size)) > 0 && counter <= number_of_mb_to_scan ) {
size_second=read(fd_second,buf_second, chunck_size);
pos_first=lseek64(fd_first, 0, SEEK_CUR);
pos_second=lseek64(fd_second, 0, SEEK_CUR);
if ( (memcmp_result=memcmp(buf_first, buf_second, sizeof(buf_second))) != 0 ) {
debug("Thread %d - Found 1MB chunck which is different at pos %llu - %d (%d)\n",args->thread_number,(unsigned
long long)pos_first-chunck_size, memcmp_result,sizeof(buf_first));
compare_buffer(buf_first,buf_second,chunck_size,blksize,result);
for (i=0; i<=chunck_size/blksize; i++) {
if ( result[i] == 1 ) {
if ( cb == 1 ) {
debug("Thread %d - chunck %d - copying block %d - location of block in device file %llu",
args->thread_number, counter+1, i, args->start_offset+(unsigned long long)(chunck_size*counter)+(unsigned long long)(i*blksize));
lseek64(fd_first,args->start_offset+(off64_t)(chunck_size*counter)+(off64_t)(i*blksize),S
EEK_SET);
lseek64(fd_second,args->start_offset+(off64_t)(chunck_size*counter)+(off64_t)(i*blksize),
SEEK_SET);
size_first=read(fd_first, buf_first, blksize);
size_second=write(fd_second,buf_first,size_first);
if ( size_second != blksize ) {
log_err("Thread %d - Houston we have a problem in copying block number %llu",args->th
read_number, (unsigned long long)args->start_offset+(unsigned long long)(chunck_size*counter)+(unsigned long long)(i*blksize));
}
}
total_number_of_different_blocks++;
}
}
}
if ( cb == 1) {
lseek64(fd_second,(off64_t)args->start_offset+(off64_t)(chunck_size*(counter+1)),SEEK_SET);
lseek64(fd_first,(off64_t)args->start_offset+(off64_t)(chunck_size*(counter+1)),SEEK_SET);
}
if ( pos_first > args->end_offset ) {
break;
}
memset(buf_first, 0, sizeof(buf_first));
memset(buf_second, 0, sizeof(buf_second));
debug("Thread %d - chunck %d out of %d done - %llu %llu", args->thread_number, counter+1, number_of_mb_to_scan,pos_fi
rst,args->end_offset);
counter++;
}
log_info("Thread %d - Number of MB to scan %ld - end offset %llu\n",args->thread_number,number_of_mb_to_scan,lseek64(fd_first
, 0, SEEK_CUR));
log_info("Thread %d - Completed - Scanning %d of 1MB chuncks\n",args->thread_number,counter);
log_info("Thread %d - Difference of size between %s to %s starting at %llu and ending at %llu- %d different blocks of %d - %d
MB\n",args->thread_number,args->device_name_a,args->device_name_b,args->start_offset,args->end_offset,total_number_of_different_block
s,blksize,total_number_of_different_blocks*blksize/chunck_size);
args->sub_total=total_number_of_different_blocks*blksize/1024;
close(fd_first);
close(fd_second);
pthread_exit(arguments);
}

Unable to display everything in C using fprintf and fflush

I am having trouble understanding why I can see some output but cannot see the output for certain other lines of the code below. I am using PAPI and C.
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <memory.h>
#include <malloc.h>
#include "papi.h"
#define INDEX 100
static void test_fail(char *file, int line, char *call, int retval);
int main(int argc, char **argv) {
extern void dummy(void *);
float matrixa[INDEX][INDEX], matrixb[INDEX][INDEX], mresult[INDEX] [INDEX];
float real_time, proc_time, mflops;
long long flpins;
int retval, status = 0;
int i,j,k;
long_long values[1];
FILE *file;
file = fopen("output.txt","w");
retval = PAPI_library_init(PAPI_VER_CURRENT);
int EventSet = PAPI_NULL;
PAPI_create_eventset(&EventSet);
if(PAPI_add_event(EventSet, PAPI_L1_DCM) != PAPI_OK)
{
fprintf(file,"PAPI failed to add Load/Store instructions\n");
}
if (PAPI_state(EventSet, &status) != PAPI_OK)
fprintf(file,"PAPI fail\n");
fprintf(file, "State is now %d\n", status);
if (PAPI_start(EventSet) != PAPI_OK)
fprintf(file,"PAPI fail\n");
if (PAPI_state(EventSet, &status) != PAPI_OK)
fprintf(file,"PAPI fail\n");
fprintf(file, "State is now %d\n", status);
/* Initialize the Matrix arrays */
for ( i=0; i<INDEX; i++ ){
mresult[0][i] = 0.0;
matrixa[0][i] = matrixb[0][i] = rand()*(float)1.1; }
if((retval=PAPI_flops( &real_time, &proc_time, &flpins, &mflops))<PAPI_OK)
test_fail(__FILE__, __LINE__, "PAPI_flops", retval);
for (i=0;i<INDEX;i++)
{
for(j=0;j<INDEX;j++)
{
for(k=0;k<INDEX;k++)
{
mresult[i][j]=mresult[i][j] + matrixa[i][k]*matrixb[k][j];
}
}
}
if((retval=PAPI_flops( &real_time, &proc_time, &flpins, &mflops)) <PAPI_OK)
{
test_fail(__FILE__, __LINE__, "PAPI_flops", retval);
}
fprintf(file,"Real_time:\t%f\nProc_time:\t%f\nTotal flpins:\t%lld \nMFLOPS:\t\t%f\n",
real_time, proc_time, flpins, mflops); //cannot see this output in the `output.txt` file
fflush(file);
fprintf(file,"%s\tPASSED\n", __FILE__);
fflush(file);
fclose(file);
PAPI_shutdown();
exit(0);
}
static void test_fail(char *file, int line, char *call, int retval){
}
In the output file, I only see the lines for "State is now". I don't see the outputs for "Real_time:\t%f\nProc_time:\t%f\nTotal flpins:\t%lld \nMFLOPS and the other outputs. I tried to use fflush, but that didn't help either. Anyone know what is going on?

pcre C API only return first match

#include <stdio.h>
#include <string.h>
#include <pcre.h>
#define OVECCOUNT 30
#define SRCBUFFER 1024*1024
int main(int argc, char **argv){
pcre *re;
const char *error;
int erroffset;
int ovector[OVECCOUNT];
int rc, i;
if (argc != 2){
fprintf(stderr, "Usage : %s PATTERN\n", argv[0]);
return 1;
}
char *src=malloc(SRCBUFFER);
int srclen = fread(src, sizeof(char), SRCBUFFER, stdin);
re = pcre_compile(argv[1], 0, &error, &erroffset, NULL);
if (re == NULL){
fprintf(stderr, "PCRE compilation failed at offset %d: %s\n", erroffset, error);
return 1;
}
rc = pcre_exec(re, NULL, src, srclen, 0, 0, ovector, OVECCOUNT);
if (rc < 0){
if (rc == PCRE_ERROR_NOMATCH) fprintf(stderr, "Sorry, no match...\n");
else fprintf(stderr, "Matching error %d\n", rc);
return 1;
}
for (i = 0; i < rc; i++){
char *substring_start = src + ovector[2 * i];
int substring_length = ovector[2 * i + 1] - ovector[2 * i];
fprintf(stdout, "%2d: %.*s\n", i, substring_length, substring_start);
}
return 0;
}
run it
echo "apple banana africa" | ./program '\ba\w+\b'
and it print
0: apple
I've tried to use the PCRE_MULTILINE option,but no use.How to make it print all matchs?
It sounds like what you're looking for is the equivalent of the Perl /g regex flag to repeat the match as many times as possible and return the results of all the matches. I don't believe PCRE has anything like that.
Instead, you will need to add a loop around pcre_exec. Each time you call it, it will return the byte offset of the start and end of the match. You want to then run pcre_exec again on the string starting at the end of the match. Repeat until pcre_exec doesn't match.

Resources