Ejemplo n.º 1
0
void test_CNamedPipeWrap_simple(IUnitTest* _ts)
{
	//TEST_SUITE(_ts,);
	TEST_SUITE(_ts,_T("Pipe"),_T("CNamedPipeWrap class tests"));

	CNamedPipeWrap serverpipe;
	CNamedPipeWrap clientpipe;

	const LPCTSTR szPipeName = _T("test_pipe");

	CEvent stopevnt(FALSE,TRUE);

	ok(serverpipe.create(szPipeName,stopevnt,PIPE_ACCESS_INBOUND,PIPE_READMODE_BYTE|PIPE_TYPE_BYTE,false),_T("server pipe create error"));
	ok(clientpipe.open(_T("."),szPipeName,GENERIC_WRITE,NMPWAIT_USE_DEFAULT_WAIT,PIPE_READMODE_BYTE,false),_T("client pipe open error"));

	bool bstoped = false;
	ok(serverpipe.connect(bstoped) && !bstoped,_T("server pipe connect error"));

	CString data(_T("0123456789"));

	string_converter<TCHAR,WCHAR> converted(data);
	DWORD dwMetaData = PDM_Data;
	ok(clientpipe.write_pipe((LPVOID)(LPCWSTR)converted,converted.get_length()*sizeof(WCHAR),dwMetaData),_T("client pipe write failed"));

	LPVOID pbuf = NULL;
	DWORD sz = 0;
	DWORD dwReadedMetaData = PDM_Null;
	ok(serverpipe.read_pipe(pbuf,sz,dwReadedMetaData,true),_T("server pipe read data failed"));
	ok(sz!=0,_T("server pipe read data failed (size == 0)"));
	ok(EQL(dwReadedMetaData,dwMetaData),_T("server pipe data differnt in meta type"));

	CString readed = string_converter<WCHAR,TCHAR>((WCHAR*)pbuf,sz/sizeof(WCHAR));
	ok(!readed.Compare(data),_T("readed by server pipe data not equal to written by client pipe data"));

	delete[] trace_free(pbuf);

	pbuf = NULL;
	ok(clientpipe.write_pipe(pbuf,0,PDM_Data),_T("client pipe write error"));

	pbuf = NULL;
	sz = 0;
	dwReadedMetaData = PDM_Null;
	ok(serverpipe.read_pipe(pbuf,sz,dwReadedMetaData,true),_T("server pipe read data failed"));

	delete[] trace_free(pbuf);

	ok(serverpipe.disconnect(),_T("service pipe disconnect error"));

	clientpipe.close();
	serverpipe.close();
}
Ejemplo n.º 2
0
int
trace_enter(int fd, char *line, int closed)
{
	struct trace *tmp;
	int res;

	assert(fd >= 0);

	if (trace_refs == NULL || fd >= trace_refsize) {
		res = trace_init(fd);
		if (res == -1)
			goto error;
	}

	if ((tmp = TAILQ_LAST(trace_refs[fd], traceq)) != NULL) {
		if (tmp->closed)
			trace_free(fd);
	}

	if ((tmp = malloc(sizeof(struct trace))) == NULL)
		goto error;

	tmp->line = line;
	tmp->closed = closed;
	TAILQ_INSERT_TAIL(trace_refs[fd], tmp, next);

	return (0);

 error:
	free(line);
	return (-1);
}
Ejemplo n.º 3
0
	void free()
	{
		m_dwMetaData = PDM_Null;
		if(NOT_NULL(m_pdata))
		{
			delete trace_free(m_pdata);
			m_pdata = NULL;
			m_size = 0;
		}
	}
Ejemplo n.º 4
0
void amqpalloc_free(void* ptr)
{
	if (!alloc_trace)
	{
		free(ptr);
	}
	else
	{
		trace_free(ptr);
	}
}
Ejemplo n.º 5
0
void test_ServerThread(IUnitTest* _ts)
{
	TEST_SUITE(_ts,_T("Pipe"),_T("Pipe Server thread"));
	
	//TRACE(_T("Test server thread ------------------------------------\n"));
	CServer1* pserver = trace_alloc(new CServer1(_T("test_pipe")));
	pserver->start();
	Sleep(100);
	CTime t1 = CTime::GetCurrentTime();
	delete trace_free(pserver);
	CTime t2 = CTime::GetCurrentTime();
	CTimeSpan dif = t2 - t1;
	ok(dif.GetSeconds()<5,_T("closing pipe server to long"));
}
Ejemplo n.º 6
0
Archivo: main.c Proyecto: 4n3w/dump
int main(int argc, char **argv) {
	if (argc < 2) {
		fprintf(stderr, "Usage: %s command [arguments ...]\n", argv[0]);
		exit(EXIT_FAILURE);
	}

	struct trace *trace = trace_new(process_new, NULL);

	int pid = trace_execvp(trace, &argv[1]);
	char buf[1024];
	argv_join(buf, sizeof(buf), &argv[1], " ");
	fprintf(stderr, "[+] pid=%i, running: %s\n", pid, buf);

	while (trace_process_count(trace) > 0) {
		trace_read(trace);
	}

	trace_free(trace);

	return 0;
}
Ejemplo n.º 7
0
// --- main --------------------------------------------------------------------
int 
mainloop (int argc, char *argv []) {
    FILE *fp = NULL;
    FILE *tempfp = NULL;
    sql_stmt_t *stmts = NULL;
    trace_t *t = NULL;
    bool_t only_q = FALSE;
    bool_t append = FALSE;
    bool_t only_r = FALSE;
    bool_t dbf_overwrite = FALSE;
    char *filename = NULL;
    char *folder = ".";
    char *dt = NULL;
    char *dt_filename = NULL;
    unsigned long partition_interval = PARTITION_INTERVAL_SECS;
    unsigned long partition_start = 0;
    int opt_idx = 0;
    int c = 0;
    int rc = 0;

    // command line option parsing
    struct option long_opts [] = {
        {"help", no_argument, NULL, 'h'},
        {"version", no_argument, NULL, 'v'},
        {"append", no_argument, NULL, 'a'},
        {"show_schema", no_argument, NULL, 's'},
        {"queries_only", no_argument, NULL, 'q'},
        {"replies_only", no_argument, NULL, 'r'},
        {"database", required_argument, NULL, 'd'},
        {"db_overwrite", no_argument, NULL, 'o'},
        {"interval", required_argument, NULL, 'i'},
        {"db_folder", required_argument, NULL, 'f'},
        { NULL, 0, NULL, 0 }
    };


    while ((c = getopt_long (argc, argv, "hvasqrd:n:oi:f:", long_opts, &opt_idx)) != -1) {
        switch (c) {
            case 'v':
            fprintf (stdout, "%s\n", DNS2SQLITE_VERSION); // VERSION defined in dns2sqlite.h
            exit (0);
            break;
            case 's':
            fprintf (stdout, "%s\n", g_tabledefs); // VERSION defined in dns2sqlite.h
            exit (0);
            break;
            case 'a':
            append = TRUE;
            break;
            case 'q':
            only_q = TRUE;
            break;
            case 'r':
            only_r = TRUE;
            break;
            case 'd':
            filename = optarg;
            break;
            case 'o':
            dbf_overwrite = TRUE;
            break;
            case 'i':
            partition_interval = strtoul (optarg, NULL, NUM_BASE);
            partition_interval = (partition_interval < 1 ? 1 : partition_interval) * 60;
            break;
            case 'f':
            folder = optarg;
            break;
            default:
            fprintf (stderr, "Unknown option: %c\n", c);
            // FALL THRU
            case 'h':
            usage (argv [0]);
            return 0;
        }
    }


    argc -= optind;
    argv += optind;

    // handle dangling command line arguments
    // N.B. this does not work if a pipe and a file is used at the same time.
    // If files are given then they should be processed before the pipe is read
    // from stdin. That is, while argc > 0 open each file and go to the main
    // loop. When argc = 0 then open stdin and go to the main loop:
    //
    // while (argc > 0) {
    //    fp = fopen (argv [argc -1], "r");
    //    if (fp == NULL) {return FAILURE}
    //    else {read_file (fp, ...);}
    //    fclose (fp);
    //    argc--;
    // }
    // fp = stdin;

    switch (argc) {
        case 0:
            fp = stdin;
            break;
        case 1:
            fp = fopen (argv [argc -1], "r");
            if (fp == NULL) {
            perror (argv [argc -1]);
            return 1;
            }
            break;
        default:
            usage (argv [0]);
            return 1;
    }

    if (filename == NULL) {
        fprintf (stderr, "Error: No database specified \n");
    }
   

    // main loop
    // This should at least be moved into its own function.
    while ((t = parse_line (fp)) != NULL) {
        partition_start = p_start (partition_start, t->s, partition_interval);

        if ((unsigned long) t->s >= (partition_start + partition_interval)) {
            rc = commit ((stmts + COMMIT)->pstmt);
            close_db (G_DB);
            G_DB = NULL;
            rc = chdir ("..");
            if (rc == -1) {
            perror (NULL);
            return FAILURE;
            }
            partition_start += partition_interval;
        }
        // check if database is open
        if (!isdbopen (G_DB)) {
          
            // create directory name
            if (dt)
                XFREE(dt);
            dt = sec_to_datetime_str (partition_start);
            if (!dt) 
                return FAILURE;
            
            // generate path 
            if (dt_filename)
                XFREE(dt_filename);
            dt_filename = make_dt_filename (dt, filename);
            if (dt_filename == NULL) {
                XFREE(dt);
                return FAILURE;
            }

            // create directory
            if (make_db_dir (dt, folder) != SUCCESS) {
                XFREE(dt);
                XFREE(dt_filename);
                return FAILURE;
            }
            XFREE(dt);

            if (dbf_overwrite)
            {
                rc = unlink(dt_filename);
                if (rc==0)
                    d2log (LOG_ERR|LOG_USER, "Unlinked file %s (due to overwrite flag).",dt_filename);
                else
                {
                    rc = errno;
                    if (rc != ENOENT)
                    {
                        d2log (LOG_ERR|LOG_USER, "Failed to unlink %s (overwrite) file code %d.",dt_filename,rc);
                        XFREE(dt);
                        XFREE(dt_filename);
                        return FAILURE;
                    }
                }
            }
            else
            {
                if (append == FALSE)
                {
                    // simplistic test whether the database file exists
                    tempfp = fopen (dt_filename, "r");
                    if (tempfp) {
                        d2log (LOG_ERR|LOG_USER, "Error: Database file %s exists ! ( use -a to append or -o owerwrite ).",dt_filename);
                        fclose (tempfp);
                        return FAILURE;
                    }
                }
            }
            
            if (!open_db (dt_filename, &G_DB, append)) {
                d2log (LOG_ERR|LOG_USER, "Failed to create new db %s.",dt_filename);
                XFREE(dt_filename);
                return FAILURE;
            }
  
            if (!prepare_stmts (G_DB, &stmts)) {
                d2log (LOG_ERR|LOG_USER, "Failed to prepare sql statements for db: %s.",dt_filename);
                close_db (G_DB);
                return FAILURE;
            }
            rc = start_transaction ((stmts + BEGIN_TRANS)->pstmt);
        }

        if (!store_to_db (G_DB, stmts, t, only_q, only_r)) {
            d2log (LOG_ERR|LOG_USER, "Failed to store data to db.\n");
        }

        trace_free (t);
    }

    // clean up before exit
    fclose (fp);
    rc = commit ((stmts + COMMIT)->pstmt);
    close_db (G_DB);
}
Ejemplo n.º 8
0
Archivo: main.c Proyecto: KurSh/crxprof
int
main(int argc, char *argv[])
{
    bool need_exit = false;
    ptrace_context ptrace_ctx;
    program_params params;
    struct itimerval itv;
    struct proc_timer proc_time;
    calltree_node *root = NULL;

    g_progname = argv[0];
    if (!parse_args(&params, argc, argv))
        usage();

    print_message("Reading symbols (list of function)");
    init_fndescr(params.pid);
    if (params.just_print_symbols) {
        print_symbols();
        free_fndescr();
        exit(0);
    }

    if (!reset_process_time(&proc_time, params.pid, params.prof_method)) {
        free_fndescr();
        errx(2, "Failed to retrieve process time");
    }


    print_message("Attaching to process: %d", params.pid);
    memset(&ptrace_ctx, 0, sizeof(ptrace_ctx));
    if (!trace_init(params.pid, &ptrace_ctx))
        err(1, "Failed to initialize unwind internals");

    signal(SIGCHLD, on_sigchld);
    if (ptrace(PTRACE_ATTACH, params.pid, 0, 0) == -1) {
        int saved_errno = errno;
        warn("ptrace(PTRACE_ATTACH) failed");
        if (saved_errno == EPERM) {
            printf("You have to see NOTES section of `man crxprof' for workarounds.\n");
        }
        exit(2);
    }

    if (do_wait(&ptrace_ctx, true) != WR_STOPPED)
        err(1, "Error occured while stopping the process");

    if (ptrace(PTRACE_CONT, params.pid, 0, 0) < 0)
        err(1, "Error occured while stopping the process 2");


    /* interval timer for snapshots */
    itv.it_interval.tv_sec = 0;
    itv.it_interval.tv_usec = params.us_sleep;
    itv.it_value = itv.it_interval;

    signal(SIGALRM, on_sigalarm);
    if (setitimer(ITIMER_REAL, &itv, NULL) == -1)
        err(1, "setitimer failed");

    print_message("Starting profile (interval %dms)", params.us_sleep / 1000);
    print_message("Press ^C once to show profile, twice to quit");
    signal(SIGINT, on_sigint);

    /* drop first meter since it contains our preparations */
    (void)get_process_dt(&proc_time); 

    while(!need_exit)
    {
        waitres_t wres = WR_NOTHING;
        sleep(1);
        
        if (timer_alarmed) {
            uint64_t proc_dt = get_process_dt(&proc_time);
            bool need_prof = (params.prof_method == PROF_REALTIME);

            if (params.prof_method == PROF_CPUTIME) {
                char st = get_procstate(&ptrace_ctx);
                if (st == 'R')
                    need_prof = true;
            }

            if (need_prof) {
                kill(params.pid, SIGSTOP);
                wres = do_wait(&ptrace_ctx, true);
                if (wres == WR_STOPPED) {
                    int signo_cont = (ptrace_ctx.stop_signal == SIGSTOP) ? 0 : ptrace_ctx.stop_signal;

                    if (!get_backtrace(&ptrace_ctx))
                        err(2, "failed to get backtrace of process");

                    /* continue tracee ASAP */
                    if (ptrace_verbose(PTRACE_CONT, params.pid, 0, signo_cont) < 0)
                        err(1, "ptrace(PTRACE_CONT) failed");

                    ptrace_ctx.nsnaps++;
                    if (fill_backtrace(proc_dt, &ptrace_ctx.stk, &root))
                        ptrace_ctx.nsnaps_accounted++;
                }
            }
        }

        if (wres != WR_FINISHED && wres != WR_NEED_DETACH) {
            wres = discard_wait(&ptrace_ctx);
        }


        if (sigint_caught_twice) {
            need_exit = true;
        } else if (sigint_caught || wres == WR_FINISHED || wres == WR_NEED_DETACH) {
            if (root) {
                print_message("%" PRIu64 " snapshot interrputs got (%" PRIu64 " dropped)", 
                    ptrace_ctx.nsnaps, ptrace_ctx.nsnaps - ptrace_ctx.nsnaps_accounted);

                visualize_profile(root, &params.vprops);
                if (params.dumpfile)
                    dump_profile(root, params.dumpfile);
            } else
                print_message("No symbolic snapshot caught yet!");
    
            sigint_caught = false;
        }

        if (wres == WR_FINISHED || wres == WR_NEED_DETACH) {
            if (wres == WR_NEED_DETACH)
                (void)ptrace_verbose(PTRACE_DETACH, params.pid, 0, ptrace_ctx.stop_signal);

            need_exit = true;
        }
    }

    free_fndescr();
    trace_free(&ptrace_ctx);
    if (root)
        calltree_destroy(root);

    return 0;
}
Ejemplo n.º 9
0
int
trace_read (const char *filename)
{
  FILE *trace = fopen(filename, "r");
  assert_inner(trace, "fopen");

  void *trace_buf = NULL;
  unsigned long trace_bufsize = 0;

  size_t n = fread(&trace_bufsize, sizeof(unsigned long), 1, trace);
  assert_set_errno(ENOTSUP, n == 1, "fread");

  trace_buf = malloc(trace_bufsize);
  assert_inner(trace_buf, "malloc");

  n = fread(trace_buf, 1, trace_bufsize, trace);
  assert_set_errno(ENOTSUP, n == trace_bufsize, "fread");
  assert_set_errno(ENOTSUP, feof(trace), "feof");

  unsigned int trace_ended = 0;

  unsigned long trace_index = 0;
  while (trace_index < trace_bufsize)
    {
      char sign = *((char*)(trace_buf + trace_index));
      trace_index += sizeof(char);
      switch (sign)
        {
        case 'e':
          trace_enter(trace_buf + trace_index);
          trace_index += 2 * sizeof(uintptr_t) + sizeof(unsigned long long);
          break;
        case 'x':
          trace_exit(trace_buf + trace_index);
          trace_index += sizeof(unsigned long long);
          break;
        case '+':
          trace_malloc(trace_buf + trace_index);
          trace_index += sizeof(size_t) + 2 * sizeof(uintptr_t) + sizeof(unsigned long long);
          break;
        case '*':
          trace_realloc(trace_buf + trace_index);
          trace_index += sizeof(size_t) + 3 * sizeof(uintptr_t) + sizeof(unsigned long long);
          break;
        case '-':
          trace_free(trace_buf + trace_index);
          trace_index += 2 * sizeof(uintptr_t) + sizeof(unsigned long long);
          break;
        case 'E':
          trace_end(trace_buf + trace_index);
          trace_index += sizeof(unsigned long long);
          trace_ended = 1;
          assert_set_errno(ENOTSUP, trace_bufsize == trace_index, "END not at end");
          break;
        default:
          assert_set_errno(ENOTSUP, 0, "sign switch");
          break;
        }
    }

  if (!trace_ended)
    assert_set_errno(ENOTSUP, 0, "no END at end");

  free(trace_buf);
  fclose(trace);

  return 0;
}
Ejemplo n.º 10
0
void test_CPipeReadBuffer(IUnitTest* _ts)
{
	TEST_SUITE(_ts,_T("Pipe"),_T("buffer operations"));

	CPipeReadedBuffer buffer;
	CPipeReadedBuffer::PipeBufferErrorsEn bufferr = CPipeReadedBuffer::PBE_Success;

	ok(buffer.is_empty(),_T("created buffer is not empty"));

	const DWORD allocate_size = 100;
	const DWORD blksz_1 = 122;
	const DWORD blksz_1_aligned = align(blksz_1,QWORD());
	const DWORD blksz_2 = 10;
	const DWORD blksz_2_aligned = align(blksz_2,QWORD());
	const DWORD blksz_3 = 15;
	const DWORD blksz_3_aligned = align(blksz_3,QWORD());

	LPVOID pbuf = NULL;
	pbuf = buffer.alloc_chunk(allocate_size);

	ok(is_all(pbuf,allocate_size,(BYTE)0),_T("alloc_chunk() not zeros memory"));
	ok(buffer.get_firstBlockRealSize()==0,_T("allocated chunk is not counted"));

	LPDWORD pdwbuf = (LPDWORD)pbuf;
	pdwbuf[0] = PDM_Data;
	pdwbuf[1] = blksz_1;

	ok(buffer.get_firstBlockRealSize()==allocate_size-sizeof(DWORD)*2,_T("bad real size"));
	ok(buffer.get_firstBlockSendedSize()==blksz_1,_T("allocated chunk is not counted"));
	ok(buffer.get_firstBlockMetaData()==PDM_Data,_T("no metadata DWORD in data chunk"));

	pbuf = buffer.alloc_chunk(allocate_size);

	fill_fortest((LPVOID)(pdwbuf+2),allocate_size-sizeof(DWORD)*2);
	DWORD cnt = blksz_1 - (allocate_size-sizeof(DWORD)*2);
	fill_fortest(pbuf,cnt,(byte)(blksz_1-cnt));

	ok(buffer.get_firstBlockRealSize()==blksz_1,_T("not processed block after it was already readed"));
	ok(buffer.get_firstBlockSendedSize()==blksz_1,_T("bad real size"));

	pdwbuf = (LPDWORD) ((LPBYTE)pbuf + blksz_1_aligned - (allocate_size-sizeof(DWORD)*2));
	pdwbuf[0] = PDM_Data;
	pdwbuf[1] = blksz_2;
	fill_fortest((LPVOID)(pdwbuf+2),blksz_2);
	pdwbuf = (LPDWORD)(
		(LPBYTE)pbuf 
			+ blksz_1_aligned - (allocate_size - sizeof(DWORD)*2)
			+ sizeof(DWORD)*2
			+ blksz_2_aligned
		);
	pdwbuf[0] = PDM_Data;
	pdwbuf[1] = blksz_3;
	fill_fortest((LPVOID)(pdwbuf+2),blksz_3);

	LPVOID preadbuf = NULL;
	DWORD dwsize = 0;

	DWORD dwMetaData = PDM_Null;
	ok(EQL(CPipeReadedBuffer::PBE_Success,buffer.read(preadbuf,dwsize,dwMetaData,true))
			&& EQL(dwMetaData,PDM_Data)
		,_T("read error")
		);
	ok(EQL(dwsize,blksz_1),_T("read error"));
	ok(test_filling(preadbuf,dwsize),_T("inccorrect data was readed"));
	ok(buffer.get_firstBlockRealSize()==blksz_2,_T("incorrect buffer size"));
	ok(buffer.get_firstBlockSendedSize()==blksz_2,_T("incorrect sended buffer size"));

	delete[] trace_free(preadbuf);
	dwsize = blksz_2+2;//set incorrect size
	preadbuf = trace_alloc(new BYTE[dwsize]);

	//test errors
	dwMetaData = PDM_Null;
	ok(EQL(CPipeReadedBuffer::PBE_WrongBufferSize,buffer.read(preadbuf,dwsize,dwMetaData,false))
		,_T("read return not PBE_WrongBufferSize")
		);
	ok(buffer.get_firstBlockRealSize()==blksz_2,_T("incorrect buffer size"));
	ok(buffer.get_firstBlockSendedSize()==blksz_2,_T("incorrect sended buffer size"));
	
	dwMetaData = PDM_Null;
	ok(EQL(CPipeReadedBuffer::PBE_InvalidArg,buffer.read(preadbuf,dwsize,dwMetaData,true))
		,_T("read return not PBE_InvalidArg")
		);
	ok(buffer.get_firstBlockRealSize()==blksz_2,_T("incorrect buffer size"));
	ok(buffer.get_firstBlockSendedSize()==blksz_2,_T("incorrect sended buffer size"));

	delete[] trace_free(preadbuf);
	dwsize = blksz_2;
	preadbuf = trace_alloc(new BYTE[dwsize]);

	ok(EQL(CPipeReadedBuffer::PBE_Success,buffer.read(preadbuf,dwsize,dwMetaData,false))
			&& EQL(dwMetaData,PDM_Data)
		,_T("read return not PBE_Success")
		);
	ok(test_filling(preadbuf,dwsize),_T("incorrect data was readed"));

	ok(EQL(buffer.get_firstBlockRealSize(),blksz_3),_T("incorrect real size"));
	ok(EQL(buffer.get_firstBlockSendedSize(),blksz_3),_T("incorrect sended size"));
	ok(EQL(buffer.free_firstBlock(),CPipeReadedBuffer::PBE_Success),_T("error while free first block"));

	ok(EQL(buffer.free_firstBlock(),CPipeReadedBuffer::PBE_DataNotReady),_T("free_firstBlock return not PBE_DataNotReady"));

	delete[] trace_free(preadbuf);
}