Beispiel #1
0
void use_gpuip()
{
    std::string err;
    float * data;
    unsigned int width, height;
    ReadImage(&data, &width, &height); // definied somewhere else

    if (!gpuip::ImageProcessor::CanCreateGpuEnvironment(gpuip::GLSL)) {
        // ... deal with error - throw exception, return function etc
    }
    gpuip::ImageProcessor::Ptr ip = gpuip::ImageProcessor::Create(gpuip::GLSL);
    ip->SetDimensions(width, height);
    gpuip::Buffer::Ptr b0 = ip->CreateBuffer("b0", gpuip::FLOAT, 4);
    gpuip::Buffer::Ptr b1 = ip->CreateBuffer("b1", gpuip::FLOAT, 4);
    gpuip::Kernel::Ptr kernel = gpuipip->CreateKernel("modify_red");
    kernel->code = GetKernelCode(); // definied somewhere else
    kernel->inBuffers.push_back(gpuip::Kernel::BufferLink(b0, "img"));
    kernel->outBuffers.push_back(gpuip::Kernel::BufferLink(b1, "out_img"));
    kernel->paramsFloat.push_back(gpuip::Parameter<float>("alpha", 0.4));
    print_timings("Build", ip->Build(&err), &err);
    print_timings("Allocate", ip->Allocate(&err), &err);
    print_timings("Copy", ip->Copy(b0, gpuip::Buffer::COPY_TO_GPU, data, &err), &err);
    print_timings("Run", ip->Run(&err), &err);
    print_timings("Copy", ip->Copy(b1, gpuip::Buffer::COPY_FROM_GPU, data, &err), &err);
}
Beispiel #2
0
int main(int argc, char** argv)
{
  double one_gb = 1024*1024*1024;
  double num_gb;
  int size;
  int* T;
  int* SA;
  FILE* f;
  int c, j;
  error_t err;

  if( argc == 1 ) {
    printf("Usage: %s <num_gb> [input_file] [input_file] ...\n", argv[0]);
    return -1;
  }
  sscanf(argv[1], "%lf", &num_gb);
  printf("Will run test with %lf GB\n", num_gb);

  size = num_gb * one_gb;

  printf("Allocating memory (size=%i)\n", size);
  T = malloc((size+4)*sizeof(int));
  assert(T);
  SA = malloc(size*sizeof(int));
  assert(SA);

  // read in some input files.
  j = 0;
  for( int i = 2; i < argc && j < size; i++ ) {
    printf("Reading %s\n", argv[i]);
    f = fopen(argv[i], "r");
    assert(f);
    while( EOF != (c = fgetc(f)) &&
           j < size ) {
      T[j++] = c;
    }
    fclose(f);
  }
  if( j < size ) {
    // make some random data
    printf("Making random data\n");
    for( int i = j; i < size; i++ ) {
      T[i] = 1 + (rand() & 0xff);
    }
  }

  printf("Suffix sorting\n");
  // sort it.
  start_clock();
  err = suffixArray(T, SA, size, 256);
  die_if_err(err);
  stop_clock();
  print_timings("Suffix Sort Bytes", size);

  return 0;
}
Beispiel #3
0
//Start of the program
int main ( int argc, char* argv[] )
{
	long long n;
	//used to put count elements printed and put newlines in output
	int thread_count;
	bool* is_prime; //sets a flag for a number if its prime or not
	//Stores the times
	double* serial_time  = malloc ( sizeof ( double ) );
	double* dynamic_time = malloc ( sizeof ( double ) );
	double* static_time  = malloc ( sizeof ( double ) );

	//if no n value is given program exits
	if ( argc != 2 )
		Usage ( argv[0] );

	thread_count = omp_get_num_procs();
	n = strtoll ( argv[1], NULL, 10 );

	//if no cores program exits
	if ( thread_count < 1 || n <= 1 )
		Usage ( argv[0] );

	//allocates bool array for all values up to and including n
	is_prime = malloc ( ( n + 1 ) * sizeof ( *is_prime ) );

	//0 and 1 are never used so false is set
	is_prime[0] = false;
	is_prime[1] = false;

	//Times the code
	serial_timing ( serial_time, is_prime, n, thread_count );
	dynamic_timing ( dynamic_time, is_prime, n, thread_count );
	static_timing ( static_time, is_prime, n, thread_count );
	//Prints timings
	print_timings ( serial_time, dynamic_time, static_time );

	return 0;
}
 /** \brief . */
 ~ProfileTiming()
 {
   set_time( func_name_.c_str(), timer_.read() );
   if( out_ )
     print_timings( *out_ );
 }
Beispiel #5
0
static void 
process_SearchCmd(HMMD_COMMAND *cmd, WORKER_ENV *env)
{ 
  int              i;
  int              cnt;
  int              limit;
  int              status;
  int              blk_size;
  WORKER_INFO     *info       = NULL;
  ESL_ALPHABET    *abc;
  ESL_STOPWATCH   *w;
  ESL_THREADS     *threadObj  = NULL;
  pthread_mutex_t  inx_mutex;
  int              current_index;
  QUEUE_DATA      *query      = NULL;
  time_t           date;
  char             timestamp[32];

  w = esl_stopwatch_Create();
  abc = esl_alphabet_Create(eslAMINO);

  if (pthread_mutex_init(&inx_mutex, NULL) != 0) p7_Fail("mutex init failed");
  ESL_ALLOC(info, sizeof(*info) * env->ncpus);

  /* Log the current time (at search start) */
  date = time(NULL);
  ctime_r(&date, timestamp);
  printf("\n%s", timestamp);	/* note that ctime_r() leaves \n on end of timestamp  */

  /* initialize thread data */
  query = process_QueryCmd(cmd, env);
  esl_stopwatch_Start(w);

  info->range_list = NULL;
  if (esl_opt_IsUsed(query->opts, "--seqdb_ranges")) {
    ESL_ALLOC(info->range_list, sizeof(RANGE_LIST));
    hmmpgmd_GetRanges(info->range_list, esl_opt_GetString(query->opts, "--seqdb_ranges"));
  }


  if (query->cmd_type == HMMD_CMD_SEARCH) threadObj = esl_threads_Create(&search_thread);
  else                                    threadObj = esl_threads_Create(&scan_thread);

  if (query->query_type == HMMD_SEQUENCE) {
    fprintf(stdout, "Search seq %s  [L=%ld]", query->seq->name, (long) query->seq->n);
  } else {
    fprintf(stdout, "Search hmm %s  [M=%d]", query->hmm->name, query->hmm->M);
  }
  fprintf(stdout, " vs %s DB %d [%d - %d]",
          (query->cmd_type == HMMD_CMD_SEARCH) ? "SEQ" : "HMM", 
          query->dbx, query->inx, query->inx + query->cnt - 1);

  if (info->range_list)
    fprintf(stdout, " in range(s) %s", esl_opt_GetString(query->opts, "--seqdb_ranges"));

  fprintf(stdout, "\n");

  /* Create processing pipeline and hit list */
  for (i = 0; i < env->ncpus; ++i) {
    info[i].abc   = query->abc;
    info[i].hmm   = query->hmm;
    info[i].seq   = query->seq;
    info[i].opts  = query->opts;

    info[i].range_list  = info[0].range_list;

    info[i].th    = NULL;
    info[i].pli   = NULL;

    info[i].inx_mutex = &inx_mutex;
    info[i].inx       = &current_index;/* this is confusing trickery - to share a single variable across all threads */
    info[i].blk_size  = &blk_size;     /* ditto */
    info[i].limit     = &limit;	       /* ditto. TODO: come back and clean this up. */

    if (query->cmd_type == HMMD_CMD_SEARCH) {
      HMMER_SEQ **list  = env->seq_db->db[query->dbx].list;
      info[i].sq_list   = &list[query->inx];
      info[i].sq_cnt    = query->cnt;
      info[i].db_Z      = env->seq_db->db[query->dbx].K;
      info[i].om_list   = NULL;
      info[i].om_cnt    = 0;
    } else {
      info[i].sq_list   = NULL;
      info[i].sq_cnt    = 0;
      info[i].db_Z      = 0;
      info[i].om_list   = &env->hmm_db->list[query->inx];
      info[i].om_cnt    = query->cnt;
    }

    esl_threads_AddThread(threadObj, &info[i]);
  }

  /* try block size of 5000.  we will need enough sequences for four
   * blocks per thread or better.
   */
  blk_size = 5000;
  cnt = query->cnt / env->ncpus / blk_size;
  limit = query->cnt * 2 / 3;
  if (cnt < 4) {
    /* try block size of 1000  */
    blk_size /= 5;
    cnt = query->cnt / env->ncpus / blk_size;
    if (cnt < 4) {
      /* still not enough.  just divide it up into one block per thread */
      blk_size = query->cnt / env->ncpus + 1;
      limit = query->cnt * 2;
    }
  }
  current_index = 0;

  esl_threads_WaitForStart(threadObj);
  esl_threads_WaitForFinish(threadObj);

  esl_stopwatch_Stop(w);
#if 1
  fprintf (stdout, "   Sequences  Residues                              Elapsed\n");
  for (i = 0; i < env->ncpus; ++i) {
    print_timings(i, info[i].elapsed, info[i].pli);
  }
#endif
  /* merge the results of the search results */
  for (i = 1; i < env->ncpus; ++i) {
    p7_tophits_Merge(info[0].th, info[i].th);
    p7_pipeline_Merge(info[0].pli, info[i].pli);
    p7_pipeline_Destroy(info[i].pli);
    p7_tophits_Destroy(info[i].th);
  }

  print_timings(99, w->elapsed, info[0].pli);
  send_results(env->fd, w, info);

  /* free the last of the pipeline data */
  p7_pipeline_Destroy(info->pli);
  p7_tophits_Destroy(info->th);

  free_QueueData(query);

  esl_threads_Destroy(threadObj);

  pthread_mutex_destroy(&inx_mutex);

  if (info->range_list) {
    if (info->range_list->starts)  free(info->range_list->starts);
    if (info->range_list->ends)    free(info->range_list->ends);
    free (info->range_list);
  }

  free(info);

  esl_stopwatch_Destroy(w);
  esl_alphabet_Destroy(abc);

  return;

 ERROR:
  LOG_FATAL_MSG("malloc", errno);
}
Beispiel #6
0
static void sign_and_verify(const bench_options_t* options) {
  static const uint8_t m[] = {1,  2,  3,  4,  5,  6,  7,  8,  9,  10, 11, 12, 13, 14, 15, 16,
                              17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32};

  timing_and_size_t* timings_fis = calloc(options->iter, sizeof(timing_and_size_t));

  const size_t max_signature_size = picnic_signature_size(options->params);
  if (!max_signature_size) {
    printf("Failed to create Picnic instance.\n");
    return;
  }

  uint8_t sig[PICNIC_MAX_SIGNATURE_SIZE];

  timing_context_t ctx;
  timing_init(&ctx);

  for (unsigned int i = 0; i != options->iter; ++i) {
#ifndef WITH_DETAILED_TIMING
    timing_and_size_t* timing_and_size;
    uint64_t start_time = timing_read(&ctx);
#endif
    timing_and_size           = &timings_fis[i];
    timing_and_size->max_size = max_signature_size;

    picnic_privatekey_t private_key;
    picnic_publickey_t public_key;

    if (picnic_keygen(options->params, &public_key, &private_key)) {
      printf("Failed to create key.\n");
      break;
    }

#ifndef WITH_DETAILED_TIMING
    uint64_t tmp_time       = timing_read(&ctx);
    timing_and_size->keygen = tmp_time - start_time;
    start_time              = timing_read(&ctx);
#endif
    size_t siglen = max_signature_size;
    if (!picnic_sign(&private_key, m, sizeof(m), sig, &siglen)) {
#ifndef WITH_DETAILED_TIMING
      tmp_time              = timing_read(&ctx);
      timing_and_size->sign = tmp_time - start_time;
      timing_and_size->size = siglen;
      start_time            = timing_read(&ctx);
#endif

      if (picnic_verify(&public_key, m, sizeof(m), sig, siglen)) {
        printf("picnic_verify: failed\n");
      }
#ifndef WITH_DETAILED_TIMING
      tmp_time                = timing_read(&ctx);
      timing_and_size->verify = tmp_time - start_time;
#endif
    } else {
      printf("picnic_sign: failed\n");
    }
  }

#ifdef VERBOSE
  printf("Picnic signature:\n\n");
#endif
  timing_close(&ctx);
  print_timings(timings_fis, options->iter);

  OQS_MEM_insecure_free(timings_fis);
}
Beispiel #7
0
int main( int argc, char** argv )
{
  char* index_path;
  char* todo;
  int max = INT32_MAX;
  int64_t chunk_size = 1000;
  if( argc != 3 && argc != 4) usage(argv[0]);

  index_path = argv[1];
  todo = argv[2];
  if( argc==4 ) chunk_size = max = atoi(argv[3]);

  {
    error_t err;
    index_locator_t loc;
    femto_server_t srv;
    int64_t nresults = 0;

    printf("Reading queries\n");
    read_queries(stdin);

    // start the server.
    err = femto_start_server_err(&srv, 0);
    die_if_err( err );

    // Get the locator for the index we're using.
    err = femto_loc_for_path_err(&srv, index_path, &loc);
    die_if_err( err );

    if( 0 == strcmp(todo, "-singlecount") ) {
      printf("Starting single count\n");
      start_clock();
      for( int i = 0; i < nqueries; i++ ) {
        err = parallel_count(&srv, loc, 1, &qlen[i], &queries[i], &count[i], NULL);
        die_if_err(err);
      }
      stop_clock();
      print_timings("single count queries", nqueries);
    } else if( 0 == strcmp(todo, "-count") ) {
      printf("Starting count\n");
      start_clock();

      err = parallel_count(&srv, loc, nqueries, qlen, queries, count, NULL);
      die_if_err(err);
      stop_clock();
      nresults = 0;
      for( int i = 0; i < nqueries; i++ ) {
        nresults += count[i];
        //printf("pat#%i %i occs\n", i, (int) count[i]);
      }
      print_timings("parallel count queries", nqueries);
      printf("Counted %" PRIi64 " results\n", nresults);
    } else if( 0 == strcmp(todo, "-singlelocate") ) {
      printf("Single locate\n");
      start_clock();
      for( int i = 0; i < nqueries; i++ ) {
        offsets[i] = NULL;
        err = serial_locate(&srv, loc, 1, &qlen[i], &queries[i], max, &noccs[i], &offsets[i]);
        //err = parallel_locate(&srv, loc, 1, &qlen[i], &queries[i], max, &noccs[i], &offsets[i]);
        die_if_err(err);
        free(offsets[i]);
        offsets[i] = NULL;
      }
      stop_clock();
      nresults = 0;
      for( int i = 0; i < nqueries; i++ ) {
        nresults += noccs[i];
      }
      print_timings("single locate queries", nqueries);
      print_timings("single locate results", nresults);
    } else if( 0 == strcmp(todo, "-locate") ) {
      start_clock();
      err = parallel_locate(&srv, loc, nqueries, qlen, queries, max, noccs, offsets);
      die_if_err(err);
      stop_clock();

      nresults = 0;
      for( int i = 0; i < nqueries; i++ ) {
        nresults += noccs[i];
        //printf("pat#%i %i occs\n", i, (int) noccs[i]);
        free(offsets[i]);
      }
      print_timings("parallel locate queries", nqueries);
      print_timings("parallel locate results", nresults);
    } else if( 0 == strcmp(todo, "-chunklocate") ) {
      int64_t first, last, current, end;

      printf("Chunk locate\n");
      start_clock();
      for( int i = 0; i < nqueries; i++ ) {
        //printf("Chunk locate - count\n");
        // first do the count.
        err = parallel_count(&srv, loc, 1, &qlen[i], &queries[i], &count_first[i], &count_last[i]);
        die_if_err(err);

        // now do the locate in chunks.
        first = count_first[i];
        last = count_last[i];
        noccs[i] = 1 + last - first;

        for( current = first; current <= last; current += chunk_size)
        {
          end = current + chunk_size - 1;
          if( end > last ) end = last;
          offsets[i] = malloc(sizeof(int64_t) * (1+end-current));
          //printf("Chunk locate: range %" PRIi64 " - %" PRIi64 "\n", current, end);
          err = parallel_locate_range(&srv, loc, current, end, offsets[i]);
          die_if_err(err);
          free(offsets[i]);
          offsets[i] = NULL;
        }

      }
      stop_clock();
      nresults = 0;
      for( int i = 0; i < nqueries; i++ ) {
        nresults += noccs[i];
      }
      print_timings("chunk locate queries", nqueries);
      print_timings("chunk locate results", nresults);
    } else if ( 0 == strcmp(todo, "-paralleldocuments") ) {
      parallel_query_t ctx;

      printf("Parallel document locate\n");
      start_clock();

      err = setup_parallel_query(&ctx, NULL, loc, sizeof(string_results_query_t), nqueries);
      die_if_err(err);
      for( int i = 0; i < nqueries; i++ ) {
        err = setup_string_results_query((string_results_query_t*) ith_query(&ctx, i),
                  NULL, loc, chunk_size, RESULT_TYPE_DOCUMENTS,
                  qlen[i], queries[i]);
        die_if_err(err);
      }

      err = femto_run_query(&srv, (query_entry_t*) &ctx);
      die_if_err(err);

      nresults = 0;
      for( int i = 0; i < nqueries; i++ ) {
        string_results_query_t* q = (string_results_query_t*) ith_query(&ctx, i);
        nresults += q->results.results.num_documents;
        results_destroy(&q->results.results);
      }

      stop_clock();
      print_timings("parallel document locate queries", nqueries);
      print_timings("parallel document locate results", nresults);
    } else if ( 0 == strcmp(todo, "-documents") ) {
      string_results_query_t q;

      printf("Document locate\n");
      start_clock();

      for( int i = 0; i < nqueries; i++ ) {
        err = setup_string_results_query(&q,
                  NULL, loc, chunk_size, RESULT_TYPE_DOCUMENTS,
                  qlen[i], queries[i]);
        die_if_err(err);

        err = femto_run_query(&srv, (query_entry_t*) &q);
        die_if_err(err);

        nresults += q.results.results.num_documents;
        results_destroy(&q.results.results);
      }

      stop_clock();
      print_timings("document locate queries", nqueries);
      print_timings("document locate results", nresults);

    }

    /*printf("Block requests: %" PRIi64 " faults %" PRIi64 "\n",
           uu->stats.block_requests, sst->stats.block_faults);
     */

    femto_stop_server(&srv);
  }

  if( 0 ) {
    int i,j;
    if( noccs ) {
      for( i = 0; i < nqueries; i++ ) {
        if( noccs[i] ) {
          for( j = 0; j < noccs[i] && j < max; j++ ) {
            printf("%i %i/%i %li\n", i, j, noccs[i], (long int) offsets[i][j]);
          }
        }
      }
    }
  }

  return 0;
}
Beispiel #8
0
int main( int argc, char** argv ) 
{
  int mark_period;
  FILE* output;
  char* info_path = "/tmp/info";
  FILE* aux;
  int chunk_size = 4096; //2048;//1024;
  const char* path;
  error_t err;

  if( argc < 4 ) {
    printf("Usage: %s <mark_period> <file_to_index> <output_file> <document_info_output> <chunk_size> <document_map_output>\n", argv[0]);
    printf(" <mark_period> -- set the marking period. This program will marks every character with offset %% mark_period = 0. Marked characters store full offset information; locating is faster for smaller mark_periods, but the index will be larger. If <mark_period> is 0, no characters are marked. 20 is a reasonable value here.\n");
    printf(" <file_to_index> -- a file or directory containing the document(s) to be indexed; if it is a directory, every file in that directory will be indexed.\n");
    printf(" <output_file> -- where to store the Burrows-Wheeler Transform of the prepared text\n");
    printf(" <document_info_output> -- where to store a file containing document information (e.g. the URL of each document)\n");
    printf(" <chunk_size> -- the number of rows in the Burrows-Wheeler transform to group together and save a list of matching documents. Larger chunks mean that queries for very common terms will report faster and the index will be smaller. Smaller chunks allow the chunks to be used for less common terms. 4096 is a reasonable value here.\n");
    printf(" <document_map_output> -- where to store the list of matching documents for each <chunk_size> group of rows\n");
    exit(-1);
  }

  {
    int i = 1;
    char* name;
    sscanf(argv[i++], "%i", &mark_period);
    path = argv[i++];
    printf("Will save bwt for %s marking %i\n", path, mark_period);
    name = argv[i++];
    printf("Saving bwt to %s\n", name);
    output = fopen(name, "w+");
    if( ! output ) {
      printf("Could not open output file %s\n", name);
      die_if_err(ERR_IO_UNK);
    }
    name = argv[i++];
    printf("Saving document infos to %s\n", name);
    info_path = name;
    if( argc >= 6 ) {
      if( argc < 7 ) {
        printf("Missing <chunk_size> <doc_output_file>\n");
        exit(-1);
      }
      sscanf(argv[i++], "%i", &chunk_size);
      name = argv[i++];
      printf("Saving document map to %s chunking %i\n", name, chunk_size);
      aux = fopen(name, "w+");
      if( ! aux ) {
        printf("Could not open aux. output file %s\n", name);
        die_if_err(ERR_IO_UNK);
      }
    } else aux = NULL;
  }

  start_clock();
  // step 1: prepare the text.
  // initialize the structure
  printf("Reading and preparing text\n"); 
  start_clock();
  err = init_prepared_text(&bwt_globals.p, info_path);
  die_if_err(err);
  
  // read in any documents
  err = init_file_find(&bwt_globals.ffs, 1, &path);
  die_if_err(err);
  err = file_find(&bwt_globals.ffs, size_file, &bwt_globals);
  die_if_err(err);
  free_file_find(&bwt_globals.ffs);

  // For each file... 
  err = init_file_find(&bwt_globals.ffs, 1, &path);
  die_if_err(err);
  err = file_find(&bwt_globals.ffs, read_file, &bwt_globals);
  die_if_err(err);
  free_file_find(&bwt_globals.ffs);


  stop_clock();

  {
    int64_t num_chars, num_docs; 
    err = prepared_num_docs( &bwt_globals.p, &num_docs);
    die_if_err(err);
    err = prepared_num_chars( &bwt_globals.p, &num_chars);
    die_if_err(err);


    printf("Read %"PRIi64 " chars %" PRIi64 " documents \n",
           num_chars, num_docs);

    print_timings("preparing bytes", num_chars );
  }


  printf("Creating output\n");
  err = save_prepared_bwt(&bwt_globals.p, mark_period,
                          output, chunk_size, aux, 1);
  die_if_err(err);
  
  free_prepared_text(&bwt_globals.p);

  return 0;
}
Beispiel #9
0
void DllStop()
{
	#if defined(SHOW_EXE_TIMINGS) || defined(SHOW_EXE_MSGBOX)
		wchar_t szTimingMsg[512]; UNREFERENCED_PARAMETER(szTimingMsg);
		HANDLE hTimingHandle = GetStdHandle(STD_OUTPUT_HANDLE);
	#endif

	print_timings(L"DllStop");
	//gbDllStopCalled = TRUE; -- в конце

	#ifdef HOOK_USE_DLLTHREAD
	DllThreadClose();
	#endif
	
	#ifdef _DEBUG
	wchar_t *szModule = (wchar_t*)calloc((MAX_PATH+1),sizeof(wchar_t));
	if (!GetModuleFileName(NULL, szModule, MAX_PATH+1))
		_wcscpy_c(szModule, MAX_PATH+1, L"GetModuleFileName failed");
	const wchar_t* pszName = PointToName(szModule);
	//if (!lstrcmpi(pszName, L"mingw32-make.exe"))
	//	GuiMessageBox(ghConEmuWnd, L"mingw32-make.exe terminating", L"ConEmuHk", MB_SYSTEMMODAL);
	free(szModule);
	#endif

	// 120528 - Очистить буфер от мышиных событий, иначе получаются казусы.
	// Если во время выполнения команды (например "dir c: /s")
	// успеть дернуть мышкой - то при возврате в ФАР сразу пойдет фаровский драг
	if (ghConWnd)
	{
		print_timings(L"FlushMouseEvents");
		FlushMouseEvents();
	}


#ifdef USE_PIPE_SERVER
	if (gpHookServer)
	{
		print_timings(L"StopPipeServer");
		gpHookServer->StopPipeServer();
		free(gpHookServer);
		gpHookServer = NULL;
	}
#endif
	
	#ifdef _DEBUG
	if (ghGuiClientRetHook)
	{
		print_timings(L"unhookWindowsHookEx");
		user->unhookWindowsHookEx(ghGuiClientRetHook);
	}
	#endif

	if (/*!gbSkipInjects &&*/ gbHooksWasSet)
	{
		print_timings(L"ShutdownHooks");
		gbHooksWasSet = FALSE;
		// Завершить работу с реестром
		DoneHooksReg();
		// "Закрыть" хуки
		ShutdownHooks();
	}

	//if (gnRunMode == RM_APPLICATION)
	//{
	print_timings(L"SendStopped");
	SendStopped();
	//}

	if (gpConMap)
	{
		print_timings(L"gpConMap->CloseMap");
		gpConMap->CloseMap();
		gpConInfo = NULL;
		delete gpConMap;
		gpConMap = NULL;
	}
	
	//#ifndef TESTLINK
	print_timings(L"CommonShutdown");
	CommonShutdown();

	
	print_timings(L"FinalizeHookedModules");
	FinalizeHookedModules();

#ifndef _DEBUG
	HeapDeinitialize();
#endif
	
	#ifdef _DEBUG
		#ifdef UseDebugExceptionFilter
			// ?gfnPrevFilter?
			// Вернуть. A value of NULL for this parameter specifies default handling within UnhandledExceptionFilter.
			SetUnhandledExceptionFilter(NULL);
		#endif
	#endif

	gbDllStopCalled = TRUE;
	print_timings(L"DllStop - Done");
}
Beispiel #10
0
DWORD WINAPI DllStart(LPVOID /*apParm*/)
{
	wchar_t *szModule = (wchar_t*)calloc((MAX_PATH+1),sizeof(wchar_t));
	if (!GetModuleFileName(NULL, szModule, MAX_PATH+1))
		_wcscpy_c(szModule, MAX_PATH+1, L"GetModuleFileName failed");
	const wchar_t* pszName = PointToName(szModule);

	#if defined(SHOW_EXE_TIMINGS) || defined(SHOW_EXE_MSGBOX)
		wchar_t szTimingMsg[512]; UNREFERENCED_PARAMETER(szTimingMsg);
		HANDLE hTimingHandle = GetStdHandle(STD_OUTPUT_HANDLE);
		if (!lstrcmpi(pszName, SHOW_EXE_MSGBOX_NAME))
		{
			gbShowExeMsgBox = true;
		}
	#endif


	// *******************  begin  *********************

	print_timings(L"DllStart: InitializeHookedModules");
	InitializeHookedModules();

	//HANDLE hStartedEvent = (HANDLE)apParm;


	#if defined(SHOW_EXE_MSGBOX)
		if (gbShowExeMsgBox)
		{
			STARTUPINFO si = {sizeof(si)};
			GetStartupInfo(&si);
			LPCWSTR pszCmd = GetCommandLineW();
			// GuiMessageBox еще не прокатит, ничего не инициализировано
			HMODULE hUser = LoadLibrary(user32);
			typedef int (WINAPI* MessageBoxW_t)(HWND hWnd,LPCTSTR lpText,LPCTSTR lpCaption,UINT uType);
			if (hUser)
			{
				MessageBoxW_t MsgBox = (MessageBoxW_t)GetProcAddress(hUser, "MessageBoxW");
				if (MsgBox)
				{
					wchar_t szMsg[128]; lstrcpyn(szMsg, pszName, 96); lstrcat(szMsg, L" loaded!");
					wchar_t szTitle[64]; msprintf(szTitle, countof(szTitle), L"ConEmuHk, PID=%u, TID=%u", GetCurrentProcessId(), GetCurrentThreadId());
					MsgBox(NULL, szMsg, szTitle, MB_SYSTEMMODAL);
				}
				FreeLibrary(hUser);
			}
		}
	#endif
	
	#ifdef _DEBUG
	{
		wchar_t szCpInfo[128];
		DWORD nCP = GetConsoleOutputCP();
		_wsprintf(szCpInfo, SKIPLEN(countof(szCpInfo)) L"Current Output CP = %u", nCP);
		print_timings(szCpInfo);
	}
	#endif

	if ((lstrcmpi(pszName, L"powershell.exe") == 0) || (lstrcmpi(pszName, L"powershell") == 0))
	{
		HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
		if (IsOutputHandle(hStdOut))
		{
			gbPowerShellMonitorProgress = true;
			MY_CONSOLE_SCREEN_BUFFER_INFOEX csbi = {sizeof(csbi)};
			if (apiGetConsoleScreenBufferInfoEx(hStdOut, &csbi))
			{
				gnConsolePopupColors = csbi.wPopupAttributes;
			}
			else
			{
				WARNING("Получить Popup атрибуты из мэппинга");
				//gnConsolePopupColors = ...;
				gnConsolePopupColors = 0;
			}
		}
	}

	// Поскольку процедура в принципе может быть кем-то перехвачена, сразу найдем адрес
	// iFindAddress = FindKernelAddress(pi.hProcess, pi.dwProcessId, &fLoadLibrary);
	//HMODULE hKernel = ::GetModuleHandle(L"kernel32.dll");
	//if (hKernel)
	//{
	//	gfnLoadLibrary = (UINT_PTR)::GetProcAddress(hKernel, "LoadLibraryW");
	//	_ASSERTE(gfnLoadLibrary!=NULL);
	//}
	//else
	//{
	//	_ASSERTE(hKernel!=NULL);
	//	gfnLoadLibrary = NULL;
	//}
	if (!GetLoadLibraryAddress())
	{
		_ASSERTE(gfnLoadLibrary!=0);
	}
	
	ghUser32 = GetModuleHandle(user32);
	if (ghUser32) ghUser32 = LoadLibrary(user32); // если подлинкован - увеличить счетчик

	WARNING("Попробовать не создавать LocalSecurity при старте");
	
	//#ifndef TESTLINK
	gpLocalSecurity = LocalSecurity();
	//gnMsgActivateCon = RegisterWindowMessage(CONEMUMSG_ACTIVATECON);
	//#endif
	//wchar_t szSkipEventName[128];
	//msprintf(szSkipEventName, SKIPLEN(countof(szSkipEventName)) CEHOOKDISABLEEVENT, GetCurrentProcessId());
	//HANDLE hSkipEvent = OpenEvent(EVENT_ALL_ACCESS , FALSE, szSkipEventName);
	////BOOL lbSkipInjects = FALSE;

	//if (hSkipEvent)
	//{
	//	gbSkipInjects = (WaitForSingleObject(hSkipEvent, 0) == WAIT_OBJECT_0);
	//	CloseHandle(hSkipEvent);
	//}
	//else
	//{
	//	gbSkipInjects = FALSE;
	//}

	WARNING("Попробовать не ломиться в мэппинг, а взять все из переменной ConEmuData");
	// Открыть мэппинг консоли и попытаться получить HWND GUI, PID сервера, и пр...
	if (ghConWnd)
	{
		print_timings(L"OnConWndChanged");
		OnConWndChanged(ghConWnd);
		//GetConMap();
	}

	if (ghConEmuWnd)
	{
#ifdef SHOW_INJECT_MSGBOX
		wchar_t* szDbgMsg = (wchar_t*)calloc(1024, sizeof(wchar_t));
		wchar_t* szTitle = (wchar_t*)calloc(128, sizeof(wchar_t));
		msprintf(szTitle, 1024, L"ConEmuHk, PID=%u", GetCurrentProcessId());
		msprintf(szDbgMsg, 128, L"SetAllHooks, ConEmuHk, PID=%u\n%s", GetCurrentProcessId(), szModule);
		GuiMessageBox(ghConEmuWnd, szDbgMsg, szTitle, MB_SYSTEMMODAL);
		free(szDbgMsg);
		free(szTitle);
#endif
	}

	//if (!gbSkipInjects && ghConWnd)
	//{
	//	InitializeConsoleInputSemaphore();
	//}


	print_timings(L"GetImageSubsystem");

	
	// Необходимо определить битность и тип (CUI/GUI) процесса, в который нас загрузили
	gnImageBits = WIN3264TEST(32,64);
	gnImageSubsystem = IMAGE_SUBSYSTEM_WINDOWS_CUI;
	// Определим тип (CUI/GUI)
	GetImageSubsystem(gnImageSubsystem, gnImageBits);
	// Проверка чего получилось
	_ASSERTE(gnImageBits==WIN3264TEST(32,64));
	_ASSERTE(gnImageSubsystem==IMAGE_SUBSYSTEM_WINDOWS_GUI || gnImageSubsystem==IMAGE_SUBSYSTEM_WINDOWS_CUI);
	
	
	//BOOL lbGuiWindowAttach = FALSE; // Прицепить к ConEmu гуевую программу (notepad, putty, ...)

	
#ifdef USE_PIPE_SERVER
	_ASSERTEX(gpHookServer==NULL);
	print_timings(L"gpHookServer");
	gpHookServer = (PipeServer<CESERVER_REQ>*)calloc(1,sizeof(*gpHookServer));
	if (gpHookServer)
	{
		wchar_t szPipeName[128];
		msprintf(szPipeName, countof(szPipeName), CEHOOKSPIPENAME, L".", GetCurrentProcessId());
		
		gpHookServer->SetMaxCount(3);
		gpHookServer->SetOverlapped(true);
		gpHookServer->SetLoopCommands(false);
		gpHookServer->SetDummyAnswerSize(sizeof(CESERVER_REQ_HDR));
		
		if (!gpHookServer->StartPipeServer(szPipeName, (LPARAM)gpHookServer, LocalSecurity(), HookServerCommand, HookServerFree, NULL, NULL, HookServerReady))
		{
			_ASSERTEX(FALSE); // Ошибка запуска Pipes?
			gpHookServer->StopPipeServer();
			free(gpHookServer);
			gpHookServer = NULL;
		}
	}
	else
	{
		_ASSERTEX(gpHookServer!=NULL);
	}
#endif

	

	WARNING("Попробовать не ломиться в мэппинг, а взять все из переменной ConEmuData");
	if (ghConWnd)
	{
		print_timings(L"CShellProc");
		CShellProc* sp = new CShellProc;
		if (sp)
		{
			if (sp->LoadGuiMapping())
			{
			
				wchar_t *szExeName = (wchar_t*)calloc((MAX_PATH+1),sizeof(wchar_t));
				//BOOL lbDosBoxAllowed = FALSE;
				if (!GetModuleFileName(NULL, szExeName, MAX_PATH+1)) szExeName[0] = 0;

				if (sp->GetUseInjects() == 2)
				{
					// Можно ли использовать облегченную версию хуков (только для exe-шника)?
					if (!gbSelfIsRootConsoleProcess && !IsFarExe(szExeName))
					{
						gbHookExecutableOnly = true;
					}
				}

				CESERVER_REQ* pIn = sp->NewCmdOnCreate(eInjectingHooks, L"",
					szExeName, GetCommandLineW(),
					NULL, NULL, NULL, NULL, // flags
					gnImageBits, gnImageSubsystem,
					GetStdHandle(STD_INPUT_HANDLE), GetStdHandle(STD_OUTPUT_HANDLE), GetStdHandle(STD_ERROR_HANDLE));
				if (pIn)
				{
					//HWND hConWnd = GetConsoleWindow();
					CESERVER_REQ* pOut = ExecuteGuiCmd(ghConWnd, pIn, ghConWnd);
					ExecuteFreeResult(pIn);
					if (pOut) ExecuteFreeResult(pOut);
				}
				free(szExeName);
			}
			delete sp;
		}
	}
	else if (gnImageSubsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI)
	{
		print_timings(L"IMAGE_SUBSYSTEM_WINDOWS_GUI");
		DWORD dwConEmuHwnd = 0;
		BOOL  bAttachExistingWindow = FALSE;
		wchar_t szVar[64], *psz;
		ConEmuGuiMapping* GuiMapping = (ConEmuGuiMapping*)calloc(1,sizeof(*GuiMapping));
		if (GuiMapping && LoadGuiMapping(gnSelfPID, *GuiMapping))
		{
			gnGuiPID = GuiMapping->nGuiPID;
			ghConEmuWnd = GuiMapping->hGuiWnd;
			bAttachExistingWindow = gbAttachGuiClient = TRUE;
			//ghAttachGuiClient = 
		}
		SafeFree(GuiMapping);

		// Если аттачим существующее окно - таб в ConEmu еще не готов
		if (!bAttachExistingWindow)
		{
			if (!dwConEmuHwnd && GetEnvironmentVariable(ENV_CONEMUHWND_VAR_W, szVar, countof(szVar)))
			{
				if (szVar[0] == L'0' && szVar[1] == L'x')
				{
					dwConEmuHwnd = wcstoul(szVar+2, &psz, 16);
					if (!user->isWindow((HWND)dwConEmuHwnd))
						dwConEmuHwnd = 0;
					else if (!user->getClassNameW((HWND)dwConEmuHwnd, szVar, countof(szVar)))
						dwConEmuHwnd = 0;
					else if (lstrcmp(szVar, VirtualConsoleClassMain) != 0)
						dwConEmuHwnd = 0;
				}
			}
			
			if (dwConEmuHwnd)
			{
				// Предварительное уведомление ConEmu GUI, что запущено GUI приложение
				// и оно может "захотеть во вкладку ConEmu".
				DWORD nSize = sizeof(CESERVER_REQ_HDR)+sizeof(CESERVER_REQ_ATTACHGUIAPP);
				CESERVER_REQ *pIn = (CESERVER_REQ*)malloc(nSize);
				ExecutePrepareCmd(pIn, CECMD_ATTACHGUIAPP, nSize);
				pIn->AttachGuiApp.nPID = GetCurrentProcessId();
				GetModuleFileName(NULL, pIn->AttachGuiApp.sAppFileName, countof(pIn->AttachGuiApp.sAppFileName));
				pIn->AttachGuiApp.hkl = (DWORD)(LONG)(LONG_PTR)GetKeyboardLayout(0);

				wchar_t szGuiPipeName[128];
				msprintf(szGuiPipeName, countof(szGuiPipeName), CEGUIPIPENAME, L".", dwConEmuHwnd);
				
				CESERVER_REQ* pOut = ExecuteCmd(szGuiPipeName, pIn, 10000, NULL);

				free(pIn);

				if (pOut)
				{
					if (pOut->hdr.cbSize > sizeof(CESERVER_REQ_HDR))
					{
						if (pOut->AttachGuiApp.nFlags & agaf_Success)
						{
							user->allowSetForegroundWindow(pOut->hdr.nSrcPID); // PID ConEmu.
							_ASSERTEX(gnGuiPID==0 || gnGuiPID==pOut->hdr.nSrcPID);
							gnGuiPID = pOut->hdr.nSrcPID;
							//ghConEmuWnd = (HWND)dwConEmuHwnd;
							_ASSERTE(ghConEmuWnd==NULL || gnGuiPID!=0);
							_ASSERTE(pOut->AttachGuiApp.hConEmuWnd==(HWND)dwConEmuHwnd);
							ghConEmuWnd = pOut->AttachGuiApp.hConEmuWnd;
							ghConEmuWndDC = pOut->AttachGuiApp.hConEmuWndDC;
							ghConWnd = pOut->AttachGuiApp.hSrvConWnd;
							_ASSERTE(ghConEmuWndDC && user->isWindow(ghConEmuWndDC));
							grcConEmuClient = pOut->AttachGuiApp.rcWindow;
							gnServerPID = pOut->AttachGuiApp.nPID;
							if (pOut->AttachGuiApp.hkl)
							{
								LONG_PTR hkl = (LONG_PTR)(LONG)pOut->AttachGuiApp.hkl;
								BOOL lbRc = ActivateKeyboardLayout((HKL)hkl, KLF_SETFORPROCESS) != NULL;
								UNREFERENCED_PARAMETER(lbRc);
							}
							OnConWndChanged(ghConWnd);
							gbAttachGuiClient = TRUE;
						}
					}
					ExecuteFreeResult(pOut);
				}
			}
		}
	}

	//if (!gbSkipInjects)
	{
		//gnRunMode = RM_APPLICATION;

		#ifdef _DEBUG
		//wchar_t szModule[MAX_PATH+1]; szModule[0] = 0;
		//GetModuleFileName(NULL, szModule, countof(szModule));
		_ASSERTE((gnImageSubsystem==IMAGE_SUBSYSTEM_WINDOWS_CUI) || (lstrcmpi(pszName, L"DosBox.exe")==0) || gbAttachGuiClient);
		//if (!lstrcmpi(pszName, L"far.exe") || !lstrcmpi(pszName, L"mingw32-make.exe"))
		//if (!lstrcmpi(pszName, L"as.exe"))
		//	MessageBoxW(NULL, L"as.exe loaded!", L"ConEmuHk", MB_SYSTEMMODAL);
		//else if (!lstrcmpi(pszName, L"cc1plus.exe"))
		//	MessageBoxW(NULL, L"cc1plus.exe loaded!", L"ConEmuHk", MB_SYSTEMMODAL);
		//else if (!lstrcmpi(pszName, L"mingw32-make.exe"))
		//	MessageBoxW(NULL, L"mingw32-make.exe loaded!", L"ConEmuHk", MB_SYSTEMMODAL);
		//if (!lstrcmpi(pszName, L"g++.exe"))
		//	MessageBoxW(NULL, L"g++.exe loaded!", L"ConEmuHk", MB_SYSTEMMODAL);
		//{
		#endif

		print_timings(L"StartupHooks");
		gbHooksWasSet = StartupHooks(ghOurModule);
		print_timings(L"StartupHooks - done");

		#ifdef _DEBUG
		//}
		#endif

		// Если NULL - значит это "Detached" консольный процесс, посылать "Started" в сервер смысла нет
		if (ghConWnd != NULL)
		{
			print_timings(L"SendStarted");
			SendStarted();

			//#ifdef _DEBUG
			//// Здесь это приводит к обвалу _chkstk,
			//// похоже из-за того, что dll-ка загружена НЕ из известных модулей,
			//// а из специально сформированного блока памяти
			// -- в одной из функций, под локальные переменные выделялось слишком много памяти
			// -- переделал в malloc/free, все заработало
			//TestShellProcessor();
			//#endif
		}
	}
	//else
	//{
	//	gbHooksWasSet = FALSE;
	//}
	
	//delete sp;

	/*
	#ifdef _DEBUG
	if (!lstrcmpi(pszName, L"mingw32-make.exe"))
		GuiMessageBox(ghConEmuWnd, L"mingw32-make.exe DllMain finished", L"ConEmuHk", MB_SYSTEMMODAL);
	#endif
	*/

	SafeFree(szModule);
	
	//if (hStartedEvent)
	//	SetEvent(hStartedEvent);

	print_timings(L"DllStart - done");
	
	return 0;
}