Пример #1
0
void
piglit_init(int argc, char **argv)
{

	if (argc < 2)
		print_usage_and_exit(argv[0]);
	{
		char *endptr = NULL;
		samples = strtol(argv[1], &endptr, 0);
		if (endptr != argv[1] + strlen(argv[1]))
			print_usage_and_exit(argv[0]);
	}

	piglit_require_gl_version(30);

	int pattern_width = piglit_width / 2;
	int pattern_height = piglit_height / num_attachments;

	piglit_ortho_projection(pattern_width,
				pattern_height,
				GL_TRUE);
	/* Skip the test if samples > GL_MAX_SAMPLES */
	GLint max_samples;
	glGetIntegerv(GL_MAX_SAMPLES, &max_samples);

	if (samples > max_samples)
		piglit_report_result(PIGLIT_SKIP);
	/* Testing of integer formats other than GL_RGBA8I is not supported
	 * by utility functions in draw-buffers-common.cpp.
	 */
	ms_fbo_and_draw_buffers_setup(samples,
				      pattern_width,
				      pattern_height,
				      num_attachments,
				      GL_COLOR_BUFFER_BIT,
				      GL_RGBA8I);
	shader_compile(false /* sample_alpha_to_coverage */,
		       false /* dual_src_blend */,
		       true /* frag_out_zero_write */);
}
Пример #2
0
void parse_args(int argc, char* argv[], QString& workdir, QString & shell_command, out bool& dropMode)
{
    int next_option;
    dropMode = false;
    do{
        next_option = getopt_long(argc, argv, short_options, long_options, nullptr);
        switch(next_option)
        {
            case 'h':
                print_usage_and_exit(0);
                break;
            case 'w':
                workdir = QString::fromLocal8Bit(optarg);
                break;
            case 'e':
                shell_command = QString::fromLocal8Bit(optarg);
                // #15 "Raw" -e params
                // Passing "raw" params (like konsole -e mcedit /tmp/tmp.txt") is more preferable - then I can call QString("qterminal -e ") + cmd_line in other programs
                while (optind < argc)
                {
                    //printf("arg: %d - %s\n", optind, argv[optind]);
                    shell_command += QLatin1Char(' ') + QString::fromLocal8Bit(argv[optind++]);
                }
                break;
            case 'd':
                dropMode = true;
                break;
            case 'p':
                Properties::Instance(QString::fromLocal8Bit(optarg));
                break;
            case '?':
                print_usage_and_exit(1);
                break;
            case 'v':
                print_version_and_exit();
                break;
        }
    }
    while(next_option != -1);
}
Пример #3
0
void
piglit_init(int argc, char **argv)
{
    GLuint vs;
    int i;

    /* Parse params. */
    if (argc != 2)
        print_usage_and_exit(argv[0]);
    test_to_run = find_matching_test(argv[0], argv[1]);

    /* Set up test */
    piglit_require_GLSL_version(test_to_run->version);
    piglit_require_transform_feedback();
    vs = piglit_compile_shader_text(GL_VERTEX_SHADER, test_to_run->vs);
    prog = glCreateProgram();
    glAttachShader(prog, vs);
    glBindAttribLocation(prog, 0, "vertex_pos");
    glBindAttribLocation(prog, 1, "vertex_num");
    glTransformFeedbackVaryings(prog, test_to_run->num_varyings,
                                (const char **) test_to_run->varyings,
                                GL_INTERLEAVED_ATTRIBS_EXT);
    glLinkProgram(prog);
    if (!piglit_link_check_status(prog)) {
        glDeleteProgram(prog);
        piglit_report_result(PIGLIT_FAIL);
    }

    /* Test that GetTransformFeedbackVarying reports the correct
     * size and type for all of the varyings.
     */
    for (i = 0; i < test_to_run->num_varyings; ++i) {
        GLsizei size;
        GLenum type;
        glGetTransformFeedbackVarying(prog, i, 0, NULL, &size,
                                      &type, NULL);
        if (size != test_to_run->expected_size) {
            printf("For varying %i, expected size %i, got %i\n",
                   i, test_to_run->expected_size, size);
            size_and_type_ok = GL_FALSE;
        }
        if (type != test_to_run->expected_type) {
            printf("For varying %i, expected type %i, got %i\n",
                   i, test_to_run->expected_type, type);
            size_and_type_ok = GL_FALSE;
        }
    }

    glGenBuffers(1, &xfb_buf);
    glGenQueries(1, &query);
    glEnable(GL_VERTEX_PROGRAM_TWO_SIDE);
}
Пример #4
0
static void
parse_options( int *argc, char **argv[] ) {
  int opt;

  while( 1 ) {
    opt = getopt( *argc, *argv, "p:s:" );

    if( opt < 0 ){
      break;
    }

    switch ( opt ){
      case 'p':
        if ( ( optarg != NULL ) && ( atoi( optarg ) <= UINT16_MAX ) && ( atoi ( optarg ) >= 0 ) ) {
          listen_port = ( uint16_t ) atoi( optarg );
        }
        else {
          print_usage_and_exit();
        }
        break;

      case 's':
        if ( optarg && dump_service_name == NULL ) {
          dump_service_name = xstrdup( optarg );
        }
        else {
          print_usage_and_exit();
        }
        break;

      default:
        print_usage_and_exit();
    }
  }

  if ( dump_service_name == NULL ) {
    dump_service_name = xstrdup( DEFAULT_DUMP_SERVICE_NAME );
  }
}
void
piglit_init(int argc, char **argv)
{
	if (argc != 2)
		print_usage_and_exit(argv[0]);

	/* 1st arg: location */
	if(strcmp(argv[1], "shader") != 0 &&
	   strcmp(argv[1], "api") != 0)
		print_usage_and_exit(argv[0]);

	locations_in_shader = strcmp(argv[1], "shader") == 0;

	if (locations_in_shader)
		piglit_require_extension("GL_ARB_explicit_attrib_location");

	piglit_require_extension("GL_ARB_vertex_array_object");
	piglit_require_GLSL_version(130);
	compile_shader();
	if (!piglit_check_gl_error(GL_NO_ERROR))
		piglit_report_result(PIGLIT_FAIL);
}
Пример #6
0
int main(int argc, char **argv) {
  synchronizer sync;
  grpc_jwt_verifier *verifier;
  gpr_cmdline *cl;
  char *jwt = NULL;
  char *aud = NULL;
  grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;

  grpc_init();
  cl = gpr_cmdline_create("JWT verifier tool");
  gpr_cmdline_add_string(cl, "jwt", "JSON web token to verify", &jwt);
  gpr_cmdline_add_string(cl, "aud", "Audience for the JWT", &aud);
  gpr_cmdline_parse(cl, argc, argv);
  if (jwt == NULL || aud == NULL) {
    print_usage_and_exit(cl, argv[0]);
  }

  verifier = grpc_jwt_verifier_create(NULL, 0);

  grpc_init();

  sync.pollset = gpr_malloc(grpc_pollset_size());
  grpc_pollset_init(sync.pollset, &sync.mu);
  sync.is_done = 0;

  grpc_jwt_verifier_verify(&exec_ctx, verifier, sync.pollset, jwt, aud,
                           on_jwt_verification_done, &sync);

  gpr_mu_lock(sync.mu);
  while (!sync.is_done) {
    grpc_pollset_worker *worker = NULL;
    if (!GRPC_LOG_IF_ERROR(
            "pollset_work",
            grpc_pollset_work(&exec_ctx, sync.pollset, &worker,
                              gpr_now(GPR_CLOCK_MONOTONIC),
                              gpr_inf_future(GPR_CLOCK_MONOTONIC))))
      sync.is_done = true;
    gpr_mu_unlock(sync.mu);
    grpc_exec_ctx_flush(&exec_ctx);
    gpr_mu_lock(sync.mu);
  }
  gpr_mu_unlock(sync.mu);

  gpr_free(sync.pollset);

  grpc_jwt_verifier_destroy(&exec_ctx, verifier);
  grpc_exec_ctx_finish(&exec_ctx);
  gpr_cmdline_destroy(cl);
  grpc_shutdown();
  return !sync.success;
}
Пример #7
0
void piglit_init(int argc, char **argv)
{
	if (argc != 2)
		print_usage_and_exit(argv[0]);
	if (strcmp(argv[1], "discard") == 0)
		discard = GL_TRUE;
	else if (strcmp(argv[1], "buffer") == 0)
		buffer = GL_TRUE;
	else if (strcmp(argv[1], "prims_written") == 0)
		prims_written = GL_TRUE;
	else if (strcmp(argv[1], "prims_generated") == 0)
		prims_generated = GL_TRUE;
	else
		print_usage_and_exit(argv[0]);

	piglit_require_transform_feedback();

	if (buffer || prims_written) {
		GLuint vs;
		piglit_require_GLSL();
		vs = piglit_compile_shader_text(GL_VERTEX_SHADER, vstext);
		xfb_prog = glCreateProgram();
		glAttachShader(xfb_prog, vs);
		glTransformFeedbackVaryings(xfb_prog, 1, xfb_varyings,
					    GL_INTERLEAVED_ATTRIBS);
		glLinkProgram(xfb_prog);
		if (!piglit_link_check_status(xfb_prog)) {
			piglit_report_result(PIGLIT_FAIL);
		}
		glGenBuffers(1, &xfb_buf);
	}
	if (prims_written) {
		glGenQueries(1, &prims_written_query);
	}
	if (prims_generated) {
		glGenQueries(1, &prims_generated_query);
	}
}
Пример #8
0
void
piglit_init(int argc, char **argv)
{
	GLuint vs;
	const char *varying_name = "output_value";

	/* Parse args */
	if (argc != 2)
		print_usage_and_exit(argv[0]);
	selected_test = interpret_test_case_arg(argv[1]);
	if (selected_test == NULL)
		print_usage_and_exit(argv[0]);

	/* Make sure required GL features are present */
	piglit_require_GLSL_version(120);
	piglit_require_transform_feedback();
	if (selected_test->bind_offset != 0 && selected_test->bind_size == 0) {
		/* Test requires glBindBufferOffsetEXT, which is in
		 * EXT_transform_feedback, but was never adopted into
		 * OpenGL.
		 */
		piglit_require_extension("GL_EXT_transform_feedback");
	}

	/* Create program and buffer */
	vs = piglit_compile_shader_text(GL_VERTEX_SHADER, vstext);
	prog = glCreateProgram();
	glAttachShader(prog, vs);
	glTransformFeedbackVaryings(prog, 1, &varying_name,
				    GL_INTERLEAVED_ATTRIBS);
	glLinkProgram(prog);
	if (!piglit_link_check_status(prog))
		piglit_report_result(PIGLIT_FAIL);
	glGenBuffers(1, &xfb_buf);
	glGenQueries(1, &query);
	if (!piglit_check_gl_error(GL_NO_ERROR))
		piglit_report_result(PIGLIT_FAIL);
}
Пример #9
0
void parse_commandline(int argc, const char **argv, clioptions *options) {
  memset(options, 0, sizeof(*options));

  // parse command line arguments
  int c;

  //TODO: use getopt_long for better looking cli args
  while ((c = getopt(argc, (char **)argv, "ab:d:r:e:p:h:")) != -1) {
    switch(c) {
    case 'a':
      options->automated = true;
      break;
    case 'b':
      options->browser = optarg;
      break;
    case 'r':
      options->results_url = optarg;
      break;
    case 'e':
      options->browser_args = optarg;
      break;
    case 'p':
      options->magic_pattern = optarg;
      break;
    case 'h':
      options->parent_handle = optarg;
      break;
    case ':':
      fprintf(stderr, "Option -%c requires an operand\n", optopt);
      print_usage_and_exit();
      break;
    case '?':
	    fprintf(stderr, "Unrecognized option: '-%c'\n", optopt);
      print_usage_and_exit();
    }
  }
  
  // Validate the options.
  if (options->magic_pattern) {
    if (options->automated || options->browser || options->results_url ||
        options->browser_args) {
      fprintf(stderr, "-p is incompatible with all other options except -h.\n");
      print_usage_and_exit();
    }
  }
  if (options->automated && !options->browser) {
    fprintf(stderr, "You must specify a browser executable to run in automatic mode.\n");
    print_usage_and_exit();
  }
  if (options->results_url && !options->automated) {
    fprintf(stderr, "Results can only be reported in automatic mode.");
    print_usage_and_exit();
  }
  if (options->browser_args && !options->browser) {
    fprintf(stderr, "-b must be specified when -e is present.");
    print_usage_and_exit();
  }
}
Пример #10
0
void
piglit_init(int argc, char **argv)
{
	if (argc != 2)
		print_usage_and_exit(argv[0]);
	if (strcmp(argv[1], "fixed") == 0) {
		use_ff = true;
	} else if (strcmp(argv[1], "arb") == 0) {
		use_arb = true;
	} else if (strcmp(argv[1], "pos") == 0) {
		use_glsl = true;
		setters = "  gl_Position = rotate(position_angle) * gl_Vertex;\n";
		use_glsl_130 = true;
	} else if (strcmp(argv[1], "pos_clipvert") == 0) {
		use_glsl = true;
		setters =
			"  gl_Position = rotate(position_angle) * gl_Vertex;\n"
			"  gl_ClipVertex = rotate(clipVertex_angle) * gl_Vertex;\n";
		use_clip_vertex = true;
	} else if (strcmp(argv[1], "clipvert_pos") == 0) {
		use_glsl = true;
		setters =
			"  gl_ClipVertex = rotate(clipVertex_angle) * gl_Vertex;\n"
			"  gl_Position = rotate(position_angle) * gl_Vertex;\n";
		use_clip_vertex = true;
	} else {
		print_usage_and_exit(argv[0]);
	}

	if (use_arb) {
		piglit_require_extension("GL_ARB_vertex_program");
		setup_arb_program();
	} else if (use_glsl) {
		piglit_require_GLSL();
		piglit_require_GLSL_version(use_glsl_130 ? 130 : 110);
		setup_glsl_programs();
	}
}
Пример #11
0
int main ( int argc, char** argv )
{
	const char* op;
	const char** arg_array;
	int i, narg;
	int rc;
	if (argc == 1)
	{
		print_usage_and_exit(argv[0]);
	}
	op = argv[1];
	if (!strcmp("op", "-h") ||
	    !strcmp("op", "-help") ||
	    !strcmp("op", "--help"))
	{
		print_usage_and_exit(argv[0]);
	}
	else if (!strcmp("op", "-v") ||
	         !strcmp("op", "-V") ||
	         !strcmp("op", "-version") ||
	         !strcmp("op", "--version"))
	{
		print_version_and_exit();
	}
	else
	{
		narg = argc - 2;
		arg_array = (const char**)malloc(sizeof(const char*) * narg);
		for (i = 0; i < narg; i++)
		{
			arg_array[i] = argv[i + 2];
		}
		rc = cduck_dispatch_command(op, narg, arg_array);
		return rc;
	}
	return 0;
}
Пример #12
0
void
piglit_init(int argc, char **argv)
{
	GLuint vs, fs;

	/* Interpret command line args */
	if (argc != 2)
		print_usage_and_exit(argv[0]);
	if (strcmp(argv[1], "output") == 0)
		test_mode = TEST_MODE_OUTPUT;
	else if (strcmp(argv[1], "prims_generated") == 0)
		test_mode = TEST_MODE_PRIMS_GENERATED;
	else if (strcmp(argv[1], "prims_written") == 0)
		test_mode = TEST_MODE_PRIMS_WRITTEN;
	else
		print_usage_and_exit(argv[0]);

	piglit_require_GLSL();
	piglit_require_transform_feedback();

	vs = piglit_compile_shader_text(GL_VERTEX_SHADER, vstext);
	fs = piglit_compile_shader_text(GL_FRAGMENT_SHADER, fstext);
	prog = glCreateProgram();
	glAttachShader(prog, vs);
	glAttachShader(prog, fs);
	glBindAttribLocation(prog, 0, "in_position");
	glBindAttribLocation(prog, 1, "in_color");
	glTransformFeedbackVaryings(prog, 2, varyings, GL_INTERLEAVED_ATTRIBS);
	glLinkProgram(prog);
	if (!piglit_link_check_status(prog)) {
		glDeleteProgram(prog);
		piglit_report_result(PIGLIT_FAIL);
	}

	glGenBuffers(1, &xfb_buf);
	glGenQueries(1, &query);
}
void
piglit_init(int argc, char **argv)
{
	GLuint gs = 0;
	GLint gsCompiled = GL_TRUE;
	char* gstext = NULL;
	int i = 0;
	bool pass = true;
	GLint expected_compile_result;

	/* Parse params */
	if (argc != 2) {
		print_usage_and_exit(argv[0]);
	}

	layout = argv[1];

	/* figure out if we expect compilation to be successful. */
	expected_compile_result = GL_FALSE;
	for (i = 0; i < ARRAY_SIZE(valids); i++) {
		if (strcmp(layout, valids[i]) == 0) {
			expected_compile_result = GL_TRUE;
			break;
		}
	}

	asprintf(&gstext, gstemplate, layout);
	gs = glCreateShader(GL_GEOMETRY_SHADER);
	glShaderSource(gs, 1, (const GLchar **) &gstext, NULL);
	glCompileShader(gs);
	free(gstext);

	/* check compile result */
	glGetShaderiv(gs, GL_COMPILE_STATUS, &gsCompiled);
	if (gsCompiled != expected_compile_result) {
		if (expected_compile_result) {
			printf("Failed to compile with output qualifier "
			       "\"%s\".\n", layout);
		} else {
			printf("\"%s\" is an invalid output qualifier "
			       "but geometry shader still compiled.\n",
			       layout);
		}
		pass = false;
	}

	pass = piglit_check_gl_error(GL_NO_ERROR) && pass;
	piglit_report_result(pass ? PIGLIT_PASS : PIGLIT_FAIL);
}
Пример #14
0
void
piglit_init(int argc, char **argv)
{
    bool blit_to_fbo;

    if (argc != 2)
        print_usage_and_exit(argv[0]);

    if (strcmp(argv[1], "window") == 0)
        blit_to_fbo = false;
    else if (strcmp(argv[1], "fbo") == 0)
        blit_to_fbo = true;
    else
        print_usage_and_exit(argv[0]);

    piglit_require_extension("GL_ARB_framebuffer_object");

    src_fbo = setup_framebuffer();
    ref_fbo = setup_framebuffer();
    if (blit_to_fbo)
        dst_fbo = setup_framebuffer();
    else
        dst_fbo = 0;
}
Пример #15
0
void
piglit_init(int argc, char **argv)
{
	const struct test_desc *test;

	/* Parse params. */
	if (argc != 2)
		print_usage_and_exit(argv[0]);
	test = find_matching_test(argv[0], argv[1]);

	piglit_require_GLSL();
	piglit_require_transform_feedback();

	piglit_report_result(do_test(test) ? PIGLIT_PASS : PIGLIT_FAIL);
}
Пример #16
0
static char * parse_options (int argc, char * argv [])
{
    int c;
    char * tmp;
  
    while ((c = getopt (argc, argv, "b:icdmoMpPaAj")) != EOF) {
	switch (c) {
	case 'b':	/* print a single node */
	    opt_block_to_print = strtol (optarg, &tmp, 0);
	    if (*tmp)
		die ("parse_options: bad block size");
	    break;

	case 'p':	/* calculate number of bytes, that need to be transfered */
	    opt_pack = 'c'; break;
	case 'P':	/* dump a partition */
	    opt_pack = 'p'; break;
	case 'a':
	    opt_pack_all = 'c'; break;
	case 'A':
	    opt_pack_all = 'p'; break;

	case 'i':	/* print items of a leaf */
	    opt_print_leaf_items = 1; break;

	case 'd':	/* print directories */
	    opt_print_directory_contents = 1; break;

	case 'c':	/* print contents of a regular file */
	    opt_print_regular_file_content = 1; break;

	case 'o':	/* print a objectid map */
	    opt_print_objectid_map = 1; break;

	case 'm':	/* print a block map */
	    opt_print_block_map = 1;  break;
	case 'M':	/* print a block map with details */
	    opt_print_block_map = 2;  break;
	case 'j':
	    opt_print_journal = 1; break; /* print transactions */
	}
    }
    if (optind != argc - 1)
	/* only one non-option argument is permitted */
	print_usage_and_exit();
  
    return argv[optind];
}
Пример #17
0
void
piglit_init(int argc, char **argv)
{
	const struct test_desc *test;

	/* Parse params. */
	if (argc != 2)
		print_usage_and_exit(argv[0]);
	test = find_matching_test(argv[0], argv[1]);

	piglit_require_GLSL();
	piglit_require_transform_feedback();
	if (test->bind_mode == OFFSET) {
		/* BindBufferOffset only exists in the EXT specification */
		piglit_require_extension("GL_EXT_transform_feedback");
	}

	piglit_report_result(do_test(test) ? PIGLIT_PASS : PIGLIT_FAIL);
}
Пример #18
0
int main(int argc, char **argv) {
  synchronizer sync;
  grpc_jwt_verifier *verifier;
  gpr_cmdline *cl;
  char *jwt = NULL;
  char *aud = NULL;

  cl = gpr_cmdline_create("JWT verifier tool");
  gpr_cmdline_add_string(cl, "jwt", "JSON web token to verify", &jwt);
  gpr_cmdline_add_string(cl, "aud", "Audience for the JWT", &aud);
  gpr_cmdline_parse(cl, argc, argv);
  if (jwt == NULL || aud == NULL) {
    print_usage_and_exit(cl, argv[0]);
  }

  verifier = grpc_jwt_verifier_create(NULL, 0);

  grpc_init();

  grpc_pollset_init(&sync.pollset);
  sync.is_done = 0;

  grpc_jwt_verifier_verify(verifier, &sync.pollset, jwt, aud,
                           on_jwt_verification_done, &sync);

  gpr_mu_lock(GRPC_POLLSET_MU(&sync.pollset));
  while (!sync.is_done) {
    grpc_pollset_worker worker;
    grpc_pollset_work(&sync.pollset, &worker,
                      gpr_inf_future(GPR_CLOCK_MONOTONIC));
  }
  gpr_mu_unlock(GRPC_POLLSET_MU(&sync.pollset));

  grpc_jwt_verifier_destroy(verifier);
  gpr_cmdline_destroy(cl);
  return !sync.success;
}
Пример #19
0
int
main(int argc, const char* const* argv)
{
	const char* architecture = NULL;
	const char* dependency = NULL;
	const char* referencePath = NULL;
	bool existingOnly = false;
	const char* separator = NULL;

	while (true) {
		static struct option sLongOptions[] = {
			{ "architecture", required_argument, 0, 'a' },
			{ "dependency", required_argument, 0, 'd' },
			{ "help", no_argument, 0, 'h' },
			{ "path", required_argument, 0, 'p' },
			{ 0, 0, 0, 0 }
		};

		opterr = 0; // don't print errors
		int c = getopt_long(argc, (char**)argv, "+a:c:d:ehlp:",
			sLongOptions, NULL);
		if (c == -1)
			break;

		switch (c) {
			case 'a':
				architecture = optarg;
				break;

			case 'c':
				separator = optarg;
				break;

			case 'd':
				dependency = optarg;
				break;

			case 'e':
				existingOnly = true;
				break;

			case 'h':
				print_usage_and_exit(false);
				break;

			case 'l':
				for (size_t i = 0; i < kDirectoryConstantCount; i++) {
					const DirectoryConstantEntry& entry
						= kDirectoryConstants[i];
					printf("%s\n    - %s\n", entry.string, entry.description);
				}
				exit(0);

			case 'p':
				referencePath = optarg;
				break;

			default:
				print_usage_and_exit(true);
				break;
		}
	}

	// The remaining arguments are the kind constant and optionally the subpath.
	if (optind >= argc || optind + 2 < argc)
		print_usage_and_exit(true);

	const char* kindConstant = argv[optind++];

	const char* subPath = NULL;
	if (optind >= argc)
		subPath = argv[optind++];

	// resolve the directory constant
	path_base_directory baseDirectory = B_FIND_PATH_IMAGE_PATH;
	bool found = false;
	for (size_t i = 0; i < kDirectoryConstantCount; i++) {
		const DirectoryConstantEntry& entry = kDirectoryConstants[i];
		if (strcmp(kindConstant, entry.string) == 0) {
			found = true;
			baseDirectory = entry.constant;
			break;
		}
	}

	if (!found) {
		fprintf(stderr, "Error: Unsupported directory constant \"%s\".\n",
			kindConstant);
		exit(1);
	}

	if (referencePath != NULL) {
		BPath path;
		status_t error = BPathFinder(referencePath, dependency).FindPath(
			architecture, baseDirectory, subPath,
			existingOnly ? B_FIND_PATH_EXISTING_ONLY : 0, path);
		if (error != B_OK) {
			fprintf(stderr, "Error: Failed to find path: %s\n",
				strerror(error));
			exit(1);
		}

		printf("%s\n", path.Path());
	} else {
		BStringList paths;
		status_t error = BPathFinder::FindPaths(architecture, baseDirectory,
			subPath, existingOnly ? B_FIND_PATH_EXISTING_ONLY : 0, paths);
		if (error != B_OK) {
			fprintf(stderr, "Error: Failed to find paths: %s\n",
				strerror(error));
			exit(1);
		}

		if (separator != NULL) {
			BString result = paths.Join(separator);
			if (result.IsEmpty()) {
				fprintf(stderr, "Error: Out of memory!\n");
				exit(1);
			}
			printf("%s\n", result.String());
		} else {
			int32 count = paths.CountStrings();
			for (int32 i = 0; i < count; i++)
				printf("%s\n", paths.StringAt(i).String());
		}
	}

	return 0;
}
Пример #20
0
int main(int argc, char** argv)
{
    if (argc < 2 || !strcmp(argv[1], "-help") || !strcmp(argv[1], "--help") ||
            !strcmp(argv[1], "-h") || !strcmp(argv[1], "--usage"))
    {
        print_usage_and_exit();
    }

    double gamma_a = 1.0, gamma_b = 1.0, alpha_a = 1.0, alpha_b = 1.0, eta = 0.5;
    int max_iter = 1000, save_lag = 100, init_topics = 0;
    bool sample_hyperparameter = false;

    bool split_merge = false;
    int num_restricted_scan = 5;

    time_t t;
    time(&t);
    long seed = (long) t;

    char* directory = NULL;;
    char* algorithm = NULL;;
    char* data_path = NULL;
    char* model_path = NULL;

    for (int i = 1; i < argc; i++)
    {
        if (!strcmp(argv[i], "--algorithm"))        algorithm = argv[++i];
        else if (!strcmp(argv[i], "--data"))        data_path = argv[++i];
        else if (!strcmp(argv[i], "--max_iter"))    max_iter = atoi(argv[++i]);
        else if (!strcmp(argv[i], "--save_lag"))    save_lag = atoi(argv[++i]);
        else if (!strcmp(argv[i], "--init_topics")) init_topics = atoi(argv[++i]);
        else if (!strcmp(argv[i], "--directory"))   directory = argv[++i];
        else if (!strcmp(argv[i], "--random_seed")) seed = atoi(argv[++i]);
        else if (!strcmp(argv[i], "--gamma_a"))     gamma_a = atof(argv[++i]);
        else if (!strcmp(argv[i], "--gamma_b"))     gamma_b = atof(argv[++i]);
        else if (!strcmp(argv[i], "--alpha_a"))     alpha_a = atof(argv[++i]);
        else if (!strcmp(argv[i], "--alpha_b"))     alpha_b = atof(argv[++i]);
        else if (!strcmp(argv[i], "--eta"))         eta = atof(argv[++i]);
        else if (!strcmp(argv[i], "--restrict_scan")) num_restricted_scan = atoi(argv[++i]);
        else if (!strcmp(argv[i], "--saved_model")) model_path = argv[++i];
        else if (!strcmp(argv[i], "--split_merge"))
        {
           ++i;
            if (!strcmp(argv[i], "yes") ||  !strcmp(argv[i], "YES"))
                split_merge = true;
        }
        else if (!strcmp(argv[i], "--sample_hyper"))
        {
           ++i;
            if (!strcmp(argv[i], "yes") ||  !strcmp(argv[i], "YES"))
                sample_hyperparameter = true;
        }
        else
        {
            printf("%s, unknown parameters, exit\n", argv[i]);
            exit(0);
        }
    }

    if (algorithm == NULL || directory == NULL || data_path == NULL)
    {
        printf("Note that algorithm, directory and data are not optional!\n");
        exit(0);
    }

    if (VERBOSE && !strcmp(algorithm, "train"))
    {
        printf("\nProgram starts with following parameters:\n");

        printf("algorithm:          = %s\n", algorithm);
        printf("data_path:          = %s\n", data_path);
        printf("directory:          = %s\n", directory);

        printf("max_iter            = %d\n", max_iter);
        printf("save_lag            = %d\n", save_lag);
        printf("init_topics         = %d\n", init_topics);
        printf("random_seed         = %d\n", seed);
        printf("gamma_a             = %.2f\n", gamma_a);
        printf("gamma_b             = %.2f\n", gamma_b);
        printf("alpha_a             = %.2f\n", alpha_a);
        printf("alpha_b             = %.2f\n", alpha_b);
        printf("eta                 = %.2f\n", eta);
        printf("#restricted_scans   = %d\n", num_restricted_scan);
        if (model_path != NULL)
        printf("saved model_path    = %s\n", model_path);
        if (split_merge)
        printf("split-merge         = yes\n");
        else
        printf("split-merge         = no\n");
        if (sample_hyperparameter)
        printf("sampling hyperparam = yes\n");
        else
        printf("sampling hyperparam = no\n");
    }

    if (!dir_exists(directory))
        mkdir(directory, S_IRUSR | S_IWUSR | S_IXUSR);

    // allocate the random number structure
    RANDOM_NUMBER = gsl_rng_alloc(gsl_rng_taus);
    gsl_rng_set(RANDOM_NUMBER, (long) seed); // init the seed

    if (!strcmp(algorithm, "train"))
    {
        // read data
        corpus * c = new corpus();
        c->read_data(data_path);

        // read hyperparameters

        hdp_hyperparameter * hdp_hyperparam = new hdp_hyperparameter();
        hdp_hyperparam->setup_parameters(gamma_a, gamma_b,
                                         alpha_a, alpha_b,
                                         max_iter, save_lag,
                                         num_restricted_scan,
                                         sample_hyperparameter,
                                         split_merge);

        hdp * hdp_instance = new hdp();

        hdp_instance->setup_state(c, eta, init_topics,
                                  hdp_hyperparam);

        hdp_instance->run(directory);

        // free resources
        delete hdp_instance;
        delete c;
        delete hdp_hyperparam;
    }

    if (!strcmp(algorithm, "test"))
    {
        corpus* c = new corpus();
        c->read_data(data_path);

        hdp_hyperparameter * hdp_hyperparam = new hdp_hyperparameter();
        hdp_hyperparam->setup_parameters(gamma_a, gamma_b,
                                         alpha_a, alpha_b,
                                         max_iter, save_lag,
                                         num_restricted_scan,
                                         sample_hyperparameter,
                                         split_merge);

        hdp * hdp_instance = new hdp();
        hdp_instance->load(model_path);
        hdp_instance->setup_state(c, hdp_hyperparam);
        hdp_instance->run_test(directory);

        delete hdp_hyperparam;
        delete hdp_instance;
        delete c;
    }
    gsl_rng_free(RANDOM_NUMBER);
}
Пример #21
0
int main(int argc, char *argv[]) {
  unsigned i, argv_copy_idx;
  unsigned file_counter = 0;
  char *stdout_content_filename = NULL;
  char *stdin_content_filename = NULL;
  char *content_filenames_list[1024];
  char **argv_copy;

  if (argc < 2)
    print_usage_and_exit(argv[0]);

  KTest b;
  b.symArgvs = 0;
  b.symArgvLen = 0;

  b.numObjects = 0;
  b.objects = (KTestObject *)malloc(MAX * sizeof *b.objects);

  if ((argv_copy = (char **)malloc(sizeof(char *) * argc * 2)) == NULL) {
    fprintf(stderr, "Could not allocate more memory\n");
    return 1;
  }

  argv_copy[0] = (char *)malloc(strlen(argv[0]) + 1);
  strcpy(argv_copy[0], argv[0]);
  argv_copy_idx = 1;

  for (i = 1; i < (unsigned)argc; i++) {
    if (strcmp(argv[i], "--sym-stdout") == 0 ||
        strcmp(argv[i], "-sym-stdout") == 0) {
      if (++i == (unsigned)argc || argv[i][0] == '-')
        print_usage_and_exit(argv[0]);

      if (stdout_content_filename)
        print_usage_and_exit(argv[0]);

      stdout_content_filename = argv[i];

    } else if (strcmp(argv[i], "--sym-stdin") == 0 ||
               strcmp(argv[i], "-sym-stdin") == 0) {
      if (++i == (unsigned)argc || argv[i][0] == '-')
        print_usage_and_exit(argv[0]);

      if (stdin_content_filename)
        print_usage_and_exit(argv[0]);

      stdin_content_filename = argv[i];
    } else if (strcmp(argv[i], "--sym-file") == 0 ||
               strcmp(argv[i], "-sym-file") == 0) {
      if (++i == (unsigned)argc || argv[i][0] == '-')
        print_usage_and_exit(argv[0]);

      content_filenames_list[file_counter++] = argv[i];
    } else {
      long nbytes = strlen(argv[i]) + 1;
      static int total_args = 0;

      char arg[1024];
      sprintf(arg, "arg%d", total_args++);
      push_obj(&b, (const char *)arg, nbytes, (unsigned char *)argv[i]);

      char *buf1 = (char *)malloc(1024);
      char *buf2 = (char *)malloc(1024);
      strcpy(buf1, "-sym-arg");
      sprintf(buf2, "%ld", nbytes - 1);
      argv_copy[argv_copy_idx++] = buf1;
      argv_copy[argv_copy_idx++] = buf2;
    }
  }

  if (file_counter > 0) {
    FILE *fp;
    struct stat64 file_stat;
    char *content_filename = content_filenames_list[file_counter - 1];

    if ((fp = fopen(content_filename, "r")) == NULL ||
        stat64(content_filename, &file_stat) < 0) {
      fprintf(stderr, "Failure opening %s\n", content_filename);
      print_usage_and_exit(argv[0]);
    }

    long nbytes = file_stat.st_size;
    char filename[7] = "A-data";
    char statname[12] = "A-data-stat";

    unsigned char *file_content, *fptr;
    if ((file_content = (unsigned char *)malloc(nbytes)) == NULL) {
      fprintf(stderr, "Memory allocation failure\n");
      exit(1);
    }

    int read_char;
    fptr = file_content;
    while ((read_char = fgetc(fp)) != EOF) {
      *fptr = (unsigned char)read_char;
      fptr++;
    }

    push_obj(&b, filename, nbytes, file_content);
    push_obj(&b, statname, sizeof(struct stat64), (unsigned char *)&file_stat);

    free(file_content);

    char *buf1 = (char *)malloc(1024);
    char *buf2 = (char *)malloc(1024);
    char *buf3 = (char *)malloc(1024);
    sprintf(buf1, "-sym-files");
    sprintf(buf2, "1");
    sprintf(buf3, "%ld", nbytes);
    argv_copy[argv_copy_idx++] = buf1;
    argv_copy[argv_copy_idx++] = buf2;
    argv_copy[argv_copy_idx++] = buf3;
  }

  if (stdin_content_filename) {
    FILE *fp;
    struct stat64 file_stat;
    char filename[6] = "stdin";
    char statname[11] = "stdin-stat";

    if ((fp = fopen(stdin_content_filename, "r")) == NULL ||
        stat64(stdin_content_filename, &file_stat) < 0) {
      fprintf(stderr, "Failure opening %s\n", stdin_content_filename);
      print_usage_and_exit(argv[0]);
    }

    unsigned char *file_content, *fptr;
    if ((file_content = (unsigned char *)malloc(file_stat.st_size)) == NULL) {
      fprintf(stderr, "Memory allocation failure\n");
      exit(1);
    }

    int read_char;
    fptr = file_content;
    while ((read_char = fgetc(fp)) != EOF) {
      *fptr = (unsigned char)read_char;
      fptr++;
    }

    push_obj(&b, filename, file_stat.st_size, file_content);
    push_obj(&b, statname, sizeof(struct stat64), (unsigned char *)&file_stat);

    free(file_content);

    char *buf1 = (char *)malloc(1024);
    char *buf2 = (char *)malloc(1024);
    sprintf(buf1, "-sym-stdin");
    sprintf(buf2, "%ld", file_stat.st_size);
    argv_copy[argv_copy_idx++] = buf1;
    argv_copy[argv_copy_idx++] = buf2;
  }

  if (stdout_content_filename) {
    FILE *fp;
    struct stat64 file_stat;
    unsigned char file_content[1024];
    char filename[7] = "stdout";
    char statname[12] = "stdout-stat";

    if ((fp = fopen(stdout_content_filename, "r")) == NULL ||
        stat64(stdout_content_filename, &file_stat) < 0) {
      fprintf(stderr, "Failure opening %s\n", stdout_content_filename);
      print_usage_and_exit(argv[0]);
    }

    int read_char;
    for (int i = 0; i < file_stat.st_size && i < 1024; ++i) {
      read_char = fgetc(fp);
      file_content[i] = (unsigned char)read_char;
    }

    for (int i = file_stat.st_size; i < 1024; ++i) {
      file_content[i] = 0;
    }

    file_stat.st_size = 1024;

    push_obj(&b, filename, 1024, file_content);
    push_obj(&b, statname, sizeof(struct stat64), (unsigned char *)&file_stat);

    char *buf = (char *)malloc(1024);
    sprintf(buf, "-sym-stdout");
    argv_copy[argv_copy_idx++] = buf;
  }

  argv_copy[argv_copy_idx] = 0;

  b.numArgs = argv_copy_idx;
  b.args = argv_copy;

  push_range(&b, "model_version", 1);

  if (!kTest_toFile(&b, "file.bout"))
    assert(0);

  for (int i = 0; i < (int)b.numObjects; ++i) {
    free(b.objects[i].name);
    free(b.objects[i].bytes);
  }
  free(b.objects);

  for (int i = 0; i < (int)argv_copy_idx; ++i) {
    free(argv_copy[i]);
  }
  free(argv_copy);

  return 0;
}
Пример #22
0
Файл: main.cpp Проект: 2php/hdp
int main(int argc, char* argv[]) {
  if (argc < 2) print_usage_and_exit();

  int verbose = 0;

  // Control parameters.
  char*  directory = NULL;
  time_t t; time(&t);
  long   random_seed = (long) t;
  int    max_iter = 100;
  int    max_time = 1800;
  int    save_lag = 5;

  // Data parameters.
  char* train_data = NULL;

  // Model parameters.
  double eta = 0.01;
  double gamma = 1.0;
  double alpha = 1.0;
  double gamma_a = 1.0;
  double gamma_b = 1.0;
  double alpha_a = 1.0;
  double alpha_b = 1.0;
  int sample_hyper = 0;

  // test only parameters
  char* test_data = NULL;
  char* model_prefix = NULL;

  for (int i = 1; i < argc; ++i) {
    if (!strcmp(argv[i], "--help")) print_usage_and_exit();
    else if (!strcmp(argv[i], "--verbose"))        verbose = 1;

    else if (!strcmp(argv[i], "--directory"))       directory = argv[++i];
    else if (!strcmp(argv[i], "--random_seed"))     random_seed = atoi(argv[++i]);
    else if (!strcmp(argv[i], "--max_iter"))        max_iter = atoi(argv[++i]);
    else if (!strcmp(argv[i], "--max_time"))        max_time = atoi(argv[++i]);
    else if (!strcmp(argv[i], "--save_lag"))        save_lag = atoi(argv[++i]);

    else if (!strcmp(argv[i], "--train_data"))      train_data = argv[++i];

    else if (!strcmp(argv[i], "--eta"))             eta = atof(argv[++i]);
    else if (!strcmp(argv[i], "--gamma"))           gamma = atof(argv[++i]);
    else if (!strcmp(argv[i], "--alpha"))           alpha = atof(argv[++i]);
    else if (!strcmp(argv[i], "--gamma_a"))         gamma_a = atof(argv[++i]);
    else if (!strcmp(argv[i], "--gamma_b"))         gamma_b = atof(argv[++i]);
    else if (!strcmp(argv[i], "--gamma_a"))         gamma_a = atof(argv[++i]);
    else if (!strcmp(argv[i], "--gamma_b"))         gamma_b = atof(argv[++i]);
    else if (!strcmp(argv[i], "--sample_hyper"))    sample_hyper = 1;

    else if (!strcmp(argv[i], "--test_data"))       test_data = argv[++i];
    else if (!strcmp(argv[i], "--model_prefix"))    model_prefix = argv[++i];
    else {
      printf("%s, unknown parameters, exit\n", argv[i]); 
      print_usage_and_exit();
    }
  }
  /// print information
  printf("************************************************************************************************\n");

  if (directory == NULL)  {
    printf("Following information is missing: --directory\n");
    printf("Run ./hdp for help.\n");
    exit(0);
  }
  
  if (!dir_exists(directory)) make_directory(directory);
  printf("Working directory: %s.\n", directory);

  char name[500];
  // Init random numbe generator.
  RANDOM_NUMBER = new_random_number_generator(random_seed);
  
  if (test_data == NULL || model_prefix == NULL) {
    sprintf(name, "%s/settings.dat", directory);
    printf("Setting saved at %s.\n", name); 
    FILE* setting_file = fopen(name, "w");

    fprintf(setting_file, "Control parameters:\n");
    fprintf(setting_file, "directory: %s\n", directory);
    fprintf(setting_file, "random_seed: %d\n", (int)random_seed);
    fprintf(setting_file, "save_lag: %d\n", save_lag);
    fprintf(setting_file, "max_iter: %d\n", max_iter);
    fprintf(setting_file, "max_time: %d\n", max_time);

    fprintf(setting_file, "\nData parameters:\n");
    fprintf(setting_file, "train_data: %s\n", train_data);

    fprintf(setting_file, "\nModel parameters:\n");
    fprintf(setting_file, "eta: %.4lf\n", eta);
    fprintf(setting_file, "gamma: %.4lf\n", gamma);
    fprintf(setting_file, "alpha: %.4lf\n", alpha);
    fprintf(setting_file, "gamma_a: %.2lf\n", gamma_a);
    fprintf(setting_file, "gamma_b: %.4lf\n", gamma_b);
    fprintf(setting_file, "gamma_a: %.2lf\n", alpha_a);
    fprintf(setting_file, "gamma_b: %.4lf\n", alpha_b);
    fprintf(setting_file, "sample_hyper: %d\n", sample_hyper);

    fclose(setting_file);

    Corpus* c_train = NULL;

    printf("Reading training data from %s.\n", train_data);
    // Reading one of the train data.
    c_train = new Corpus();
    c_train->read_data(train_data);

    // Open the log file for training data.
    sprintf(name, "%s/train.log", directory);
    FILE* train_log = fopen(name, "w");
    // Heldout columns record the documents that have not seen before.
    sprintf(name, "time\titer\tnum.topics\tgamma\talpha\t\tword.count\tlikelihood\tavg.likelihood");
    if(verbose) printf("%s\n", name);
    fprintf(train_log, "%s\n", name);
    
    // Start iterating.
    time_t start, current;
    int total_time = 0;
    int iter = 0;

    HDP* hdp = new HDP();
    hdp->init_hdp(eta, gamma, alpha, c_train->size_vocab_);

    // Setting up the hdp state.
    hdp->setup_doc_states(c_train->docs_);
    // first iteration
    hdp->iterate_gibbs_state(false, false);

    while ((max_iter == -1 || iter < max_iter) && (max_time == -1 || total_time < max_time)) {
      ++iter;
      time (&start);
       
      // Iterations.
      hdp->iterate_gibbs_state(true, true);
      // Scoring the documents.
      double likelihood = hdp->log_likelihood(NULL);
      hdp->compact_hdp_state();

      if (sample_hyper) hdp->hyper_inference(gamma_a, gamma_b, alpha_a, alpha_b);
      
      // Record the time.
      time(&current);
      int elapse = (int) difftime(current, start);
      total_time += elapse;

      sprintf(name, "%d\t%d\t%d\t\t%.5f\t%.5f\t\t%d\t\t%.3f\t%.5f", 
              total_time, iter, hdp->hdp_state_->num_topics_, hdp->hdp_state_->gamma_,
              hdp->hdp_state_->alpha_, c_train->num_total_words_, likelihood, likelihood/c_train->num_total_words_);

      if (verbose) printf("%s\n", name);
      fprintf(train_log, "%s\n", name); 
      fflush(train_log);

      if (save_lag > 0 && (iter % save_lag == 0)) {
        sprintf(name, "%s/iter@%05d", directory, iter);
        hdp->save_state(name);
      }
    }

    sprintf(name, "%s/final", directory);
    hdp->save_state(name);

    // Free training data.
    if (c_train != NULL) {
      delete c_train;
    }
    fclose(train_log);

    delete hdp;
  }
  
  if (test_data != NULL && model_prefix != NULL) {
    Corpus* c_test = new Corpus();
    c_test->read_data(test_data);

    HDP* hdp = new HDP();
    printf("Loading model from prefix %s...\n", model_prefix);
    hdp->load_state(model_prefix);

    // Remember the old state.
    HDPState* old_hdp_state = new HDPState();
    old_hdp_state->copy_hdp_state(*hdp->hdp_state_);

    hdp->setup_doc_states(c_test->docs_);

    if (verbose) printf("Initialization ...\n");
    hdp->iterate_gibbs_state(false, false);

    sprintf(name, "%s/%s-test.log", directory, basename(model_prefix));
    FILE* test_log = fopen(name, "w");
    sprintf(name, "time\titer\tnum.topics\tword.count\tlikelihood\tavg.likelihood");
    if(verbose) printf("%s\n", name);
    fprintf(test_log, "%s\n", name);

    time_t start, current;
    int total_time = 0;
    int iter = 0;

    // Iterations.
    while ((max_iter == -1 || iter < max_iter) && (max_time == -1 || total_time < max_time)) {
      ++iter;
      time (&start);
      hdp->iterate_gibbs_state(true, true);
      double likelihood = hdp->log_likelihood(old_hdp_state);
      hdp->compact_hdp_state();
      time(&current);
      int elapse = (int) difftime(current, start);
      total_time += elapse;

      sprintf(name, "%d\t%d\t%d\t\t%d\t\t%.3f\t%.5f", 
              total_time, iter, hdp->hdp_state_->num_topics_,
              c_test->num_total_words_, likelihood,
              likelihood/c_test->num_total_words_);

      if (verbose) printf("%s\n", name);
      fprintf(test_log, "%s\n", name); 
      fflush(test_log);
    }
    
    if (verbose) printf("Done and saving ...\n");
    sprintf(name, "%s/%s-test", directory, basename(model_prefix));
    hdp->save_state(name);
    hdp->save_doc_states(name);
    fclose(test_log);

    delete hdp;
    delete old_hdp_state;
    delete c_test;
  }

  // Free random number generator.
  free_random_number_generator(RANDOM_NUMBER);
  return 0;
}
Пример #23
0
unsigned get_next_arg( 
	int *const index,   // in, out
	const unsigned expected_types   // in
)
{
	FAIL_IF( !index );
	FAIL_IF( *index < 0 );
	FAIL_IF( expected_types & ~( OPT | OPTARG ) );
	
	FAIL_IF( !G->prog->init_time );   // This function depends on G->prog
	
	
	for( ;; )
	{
		__int64 num = 0;
		
		/* increment index to the next argument */
		++*index;
		
		if( *index >= G->prog->argc ) /* out of command line arguments */
		{
			if( !( expected_types & OPT ) )
			{
				MSG_FATAL( "An option has no associated option argument." );
				printf( "OPT: %s\n", G->prog->argv[ *index - 1 ] );
				exit( 1 );
			}
			
			return END;
		}
		else if( str_to_int64( &num, G->prog->argv[ *index ] ) && ( num < 0 ) )
		{
			/* the command line argument is a negative number, not an option.
			a negative number would only be an option's argument
			*/
			
			if( !( expected_types & OPTARG ) )
			{
				MSG_FATAL( "An option argument has no associated option." );
				printf( "OPTARG: %s\n", G->prog->argv[ *index ] );
				exit( 1 );
			}
			
			return OPTARG;
		}
		else if( ( ( G->prog->argv[ *index ][ 0 ] == '-' ) 
				|| ( G->prog->argv[ *index ][ 0 ] == '/' ) 
			) 
			&& G->prog->argv[ *index ][ 1 ] 
			&& !G->prog->argv[ *index ][ 2 ] 
		)
		{
			/* the command line argument is an option */
			
			if( !( expected_types & OPT ) )
			{
				MSG_FATAL( "An option has no associated option argument." );
				printf( "OPT: %s\n", G->prog->argv[ *index - 1 ] );
				exit( 1 );
			}
			
			return OPT;
		}
		else if( G->prog->argv[ *index ][ 0 ] )
		{
			if( !_stricmp( G->prog->argv[ *index ], "--help" ) )
				print_usage_and_exit();
			else if( !_stricmp( G->prog->argv[ *index ], "--about" ) )
				print_overview_and_exit();
			else if( !_stricmp( G->prog->argv[ *index ], "--options" ) )
				print_more_options_and_exit();
			else if( !_stricmp( G->prog->argv[ *index ], "--examples" ) )
				print_more_examples_and_exit();
			else if( !_stricmp( G->prog->argv[ *index ], "--version" ) )
				exit( 1 ); /* version always printed */
			
			/* the command line argument is an option's argument (optarg) */
			
			if( !( expected_types & OPTARG ) )
			{
				MSG_FATAL( "An option argument has no associated option." );
				printf( "OPTARG: %s\n", G->prog->argv[ *index ] );
				exit( 1 );
			}
			
			return OPTARG;
		}
		
		/* else this command line argument is empty. loop to the next one */
	}
}
Пример #24
0
int main(int argc, char ** argv)
{
    if (argc < 3) {
        print_usage_and_exit();
    }

    if (!strcmp(argv[1], "-creat")) {
        make_test_file(argv[2]);
    } else if (!strcmp(argv[1], "-check")) {
        check_output(argv[2]);
    } else {

        /* Do the main thing*/

        /* Open fds...*/
        int fd_in = open(argv[1], O_RDONLY);
        fprintf(stderr, "Opening %s... ", argv[1]);
        if (fd_in == -1) {
            perror("open() failed");
            exit(EXIT_FAILURE);
        }
        fprintf(stderr, "success\n");
        int fd_out = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, S_IRWXU);
        fprintf(stderr, "Opening %s... ", argv[2]);
        if (fd_in == -1) {
            perror("open() failed");
            exit(EXIT_FAILURE);
        }
        fprintf(stderr, "success\n");

        /* Sorting procedure :
        *
        *       1. Sequentially read headers from input file and build index-tree
        *          that holds key, size and offset of records in input file.
        *       2. Then, walk the tree in ascending order
        *          and write records described by its nodes into output file
        */

        /*Current read position in file*/
        uint64_t in_position = 0;

        /*Tree top*/
        compact_header_t * tree = NULL;

        /*Total count of records in file (only for logging)*/
        int rec_cnt = 0;

        int fl_break = 0;
        while (!fl_break) {
            int r = do_process_record(fd_in, &in_position, &tree);
            switch (r) {
            case IO_EOF :
                /*file end is reached*/
                fl_break = 1;
                break;
            case IO_ERROR :
                fprintf(stderr, "File read error\n");
                exit(EXIT_FAILURE);
                break;
            case IO_SUCCESS :
                rec_cnt++;
                break;
            default :
                assert(0);
                break;
            }
        }

        fprintf(stderr, "Count of records: %i\n", rec_cnt);
        fprintf(stderr, "Writing sorted file...");
        walk_tree(fd_in, fd_out, tree);
        close(fd_in);
        close(fd_out);
        fprintf(stderr, "done\n");
    }
    return EXIT_SUCCESS;
}
Пример #25
0
/* init_global_config_store()
Initialize the global configuration store by parsing command line arguments.

This function must only be called from the main thread.
For now there is only one configuration store implemented and it's a global store (G->config).
'G->config' depends on the global program (G->prog) store.
*/
void init_global_config_store( void )
{
	int i = 0;
	unsigned arf = 0;
	char *debugstr = NULL;
	
	FAIL_IF( !G );   // The global store must exist.
	
	FAIL_IF( G->config->init_time );   // Fail if this store has already been initialized.
	
	FAIL_IF( !G->prog->init_time );   // The program store must be initialized.
	
	FAIL_IF( GetCurrentThreadId() != G->prog->dwMainThreadId );   // main thread only
	
	
	debugstr = getenv( "GETHOOKS_DEBUG" );
	if( debugstr && ( debugstr[ 0 ] == '1' ) && !debugstr[ 1 ] )
		G->config->flags |= CFG_DEBUG;
	
	G->config->polling = POLLING_DEFAULT;
	G->config->verbose = VERBOSE_DEFAULT;
	G->config->max_threads = MAX_THREADS_DEFAULT;
	
	/* parse command line arguments */
	i = 0;
	while( arf != END )
	{
		if( arf != OPT ) /* attempt to get an option from the command line arguments */
			arf = get_next_arg( &i, OPT );
		
		if( arf != OPT )
			continue;
		
		/* option found */
		
		switch( G->prog->argv[ i ][ 1 ] )
		{
			case '?':
			case 'h':
			case 'H':
			{
				/* show help */
				print_usage_and_exit();
			}
			
			
			/**
			desktop include option
			*/
			case 'd':
			case 'D':
			{
				G->config->desklist->type = LIST_INCLUDE_DESK;
				
				/* since this option may or may not have an associated argument, 
				test for both an option's argument(optarg) or the next option
				*/
				arf = get_next_arg( &i, OPT | OPTARG );
				
				if( arf != OPTARG )
					continue;
				
				while( arf == OPTARG ) /* option argument found */
				{
					WCHAR *name = NULL;
					
					
					/* make the desktop name as a wide character string */
					if( !get_wstr_from_mbstr( &name, G->prog->argv[ i ] ) )
					{
						MSG_FATAL( "get_wstr_from_mbstr() failed." );
						printf( "desktop: %s\n", G->prog->argv[ i ] );
						exit( 1 );
					}
					
					/* append to the linked list */
					if( !add_list_item( G->config->desklist, 0, name ) )
					{
						MSG_FATAL( "add_list_item() failed." );
						printf( "desktop: %s\n", G->prog->argv[ i ] );
						exit( 1 );
					}
					
					/* if add_list_item() was successful then it made a duplicate of the 
					wide string pointed to by name. in any case name should now be freed.
					*/
					free( name );
					name = NULL;
					
					/* get the option's next argument, which is optional */
					arf = get_next_arg( &i, OPT | OPTARG );
				}
				
				continue;
			}
			
			
			
			/** 
			monitor option
			*/
			case 'm':
			case 'M':
			{
				if( G->config->polling != POLLING_DEFAULT )
				{
					MSG_FATAL( "Option 'm': this option has already been specified." );
					printf( "sec: %d\n", G->config->polling );
					exit( 1 );
				}
				
				G->config->polling = POLLING_ENABLED_DEFAULT;
				
				/* since this option may or may not have an associated argument, 
				test for both an option's argument(optarg) or the next option
				*/
				arf = get_next_arg( &i, OPT | OPTARG );
				
				if( arf != OPTARG )
					continue;
				
				/* option argument found */
				
				if( !str_to_int( &G->config->polling, G->prog->argv[ i ] ) )
				{
					MSG_FATAL( "Option 'm': the string is not an integer representation." );
					printf( "sec: %s\n", G->prog->argv[ i ] );
					exit( 1 );
				}
				
				if( G->config->polling == 0 )
				{
					MSG_WARNING( "Option 'm': an interval of 0 uses too much CPU time." );
					printf( "sec: %s\n", G->prog->argv[ i ] );
				}
				
				if( G->config->polling > 86400 ) // number of seconds in a day
				{
					MSG_WARNING( "Option 'm': more seconds than in a day (86400)." );
					printf( "sec: %s\n", G->prog->argv[ i ] );
				}
				
				if( G->config->polling < POLLING_MIN )
				{
					MSG_FATAL( "Option 'm': less seconds than the minimum allowed." );
					printf( "sec: %s\n", G->prog->argv[ i ] );
					printf( "POLLING_MIN: %d\n", POLLING_MIN );
					exit( 1 );
				}
				else if( G->config->polling > POLLING_MAX )
				{
					MSG_FATAL( "Option 'm': more seconds than the maximum allowed." );
					printf( "sec: %s\n", G->prog->argv[ i ] );
					printf( "POLLING_MAX: %d\n", POLLING_MAX );
					exit( 1 );
				}
				
				continue;
			}
			
			
			
			/**
			hook include/exclude options
			i: include list for hooks
			x: exclude list for hooks
			*/
			case 'i':
			case 'I':
			{
				if( G->config->hooklist->type == LIST_EXCLUDE_HOOK )
				{
					MSG_FATAL( "Options 'i' and 'x' are mutually exclusive." );
					exit( 1 );
				}
				
				G->config->hooklist->type = LIST_INCLUDE_HOOK;
			}
			/* pass through to the exclude code. 
			the exclude code can handle either type of list, include or exclude.
			*/
			case 'x':
			case 'X':
			{
				if( G->config->hooklist->type != LIST_INCLUDE_HOOK )
				{
					G->config->hooklist->type = LIST_EXCLUDE_HOOK;
				}
				else if( ( G->prog->argv[ i ][ 1 ] == 'x' ) || ( G->prog->argv[ i ][ 1 ] == 'X' ) )
				{
					MSG_FATAL( "Options 'i' and 'x' are mutually exclusive." );
					exit( 1 );
				}
				
				/* the 'i' or 'x' option requires at least one associated argument (optarg).
				if an optarg is not found get_next_arg() will exit(1)
				*/
				arf = get_next_arg( &i, OPTARG );
				
				while( arf == OPTARG ) /* option argument found */
				{
					__int64 id = 0;
					WCHAR *name = NULL;
					
					/* if the string is not an integer then it's a hook name not an id */
					if( !str_to_int64( &id, G->prog->argv[ i ] ) )
					{
						id = 0;
						
						/* make the hook name as a wide character string */
						if( !get_wstr_from_mbstr( &name, G->prog->argv[ i ] ) )
						{
							MSG_FATAL( "get_wstr_from_mbstr() failed." );
							printf( "hook: %s\n", G->prog->argv[ i ] );
							exit( 1 );
						}
						
						_wcsupr( name ); /* convert hook name to uppercase */
					}
					
					/* append to the linked list */
					if( !add_list_item( G->config->hooklist, id, name ) )
					{
						MSG_FATAL( "add_list_item() failed." );
						printf( "hook: %s\n", G->prog->argv[ i ] );
						exit( 1 );
					}
					
					/* if add_list_item() was successful then it made a duplicate of the 
					wide string pointed to by name. in any case name should now be freed.
					*/
					free( name );
					name = NULL;
					
					/* get the option's next argument, which is optional */
					arf = get_next_arg( &i, OPT | OPTARG );
				}
				
				continue;
			}
			
			
			
			/**
			program include/exclude options
			p: include list for programs
			r: exclude list for programs
			*/
			case 'p':
			case 'P':
			{
				if( G->config->proglist->type == LIST_EXCLUDE_PROG )
				{
					MSG_FATAL( "Options 'p' and 'r' are mutually exclusive." );
					exit( 1 );
				}
				
				G->config->proglist->type = LIST_INCLUDE_PROG;
			}
			/* pass through to the exclude code. 
			the exclude code can handle either type of list, include or exclude.
			*/
			case 'r':
			case 'R':
			{
				if( G->config->proglist->type != LIST_INCLUDE_PROG )
				{
					G->config->proglist->type = LIST_EXCLUDE_PROG;
				}
				else if( ( G->prog->argv[ i ][ 1 ] == 'r' ) || ( G->prog->argv[ i ][ 1 ] == 'R' ) )
				{
					MSG_FATAL( "Options 'p' and 'r' are mutually exclusive." );
					exit( 1 );
				}
				
				
				/* the 'p' or 'r' option requires at least one associated argument (optarg).
				if an optarg is not found get_next_arg() will exit(1)
				*/
				arf = get_next_arg( &i, OPTARG );
				
				while( arf == OPTARG ) /* option argument found */
				{
					__int64 id = 0;
					WCHAR *name = NULL;
					const char *p = G->prog->argv[ i ];
					
					
					/* a colon is used as the escape character. 
					if the first character is a colon then a program name 
					is specified, not a PID/TID. this is only necessary 
					in cases where a program name can be mistaken by 
					the parser for an option or a PID/TID.
					*/
					if( *p == ':' )
						++p;
					
					/* if the first character is a colon, or the string is not an integer, 
					or it is and the integer is negative, then assume program name
					*/
					if( ( p != G->prog->argv[ i ] ) 
						|| ( str_to_int64( &id, G->prog->argv[ i ] ) != NUM_POS )
					)
					{
						/* make the program name as a wide character string */
						if( !get_wstr_from_mbstr( &name, p ) )
						{
							MSG_FATAL( "get_wstr_from_mbstr() failed." );
							printf( "prog: %s\n", G->prog->argv[ i ] );
							exit( 1 );
						}
						
						//_wcslwr( name ); /* convert program name to lowercase */
						
						/* program name and id are mutually exclusive. 
						elsewhere in the code if a list item's name != NULL 
						then its id is ignored.
						*/
					}
					/* else the id is valid and name remains NULL*/
					
					/* append to the linked list */
					if( !add_list_item( G->config->proglist, id, name ) )
					{
						MSG_FATAL( "add_list_item() failed." );
						printf( "prog: %s\n", G->prog->argv[ i ] );
						exit( 1 );
					}
					
					/* if add_list_item() was successful then it made a duplicate of the 
					wide string pointed to by name. in any case name should now be freed.
					*/
					free( name );
					name = NULL;
					
					/* get the option's next argument, which is optional */
					arf = get_next_arg( &i, OPT | OPTARG );
				}
				
				continue;
			}
			
			
			
			/** 
			verbosity option
			*/
			case 'v':
			case 'V':
			{
				if( G->config->verbose != VERBOSE_DEFAULT )
				{
					MSG_FATAL( "Option 'v': this option has already been specified." );
					printf( "verbosity level: %d\n", G->config->verbose );
					exit( 1 );
				}
				
				G->config->verbose = VERBOSE_ENABLED_DEFAULT;
				
				/* since this option may or may not have an associated argument, 
				test for both an option's argument(optarg) or the next option
				*/
				arf = get_next_arg( &i, OPT | OPTARG );
				
				if( arf != OPTARG )
					continue;
				
				/* option argument found */
				
				if( !str_to_int( &G->config->verbose, G->prog->argv[ i ] ) )
				{
					MSG_FATAL( "Option 'v': the string is not an integer representation." );
					printf( "num: %s\n", G->prog->argv[ i ] );
					exit( 1 );
				}
				
				if( G->config->verbose < VERBOSE_MIN )
				{
					MSG_FATAL( "Option 'v': less verbosity than the minimum allowed." );
					printf( "num: %s\n", G->prog->argv[ i ] );
					printf( "VERBOSE_MIN: %d\n", VERBOSE_MIN );
					exit( 1 );
				}
				else if( G->config->verbose > VERBOSE_MAX )
				{
					MSG_FATAL( "Option 'v': more verbosity than the maximum allowed." );
					printf( "num: %s\n", G->prog->argv[ i ] );
					printf( "VERBOSE_MAX: %d\n", VERBOSE_MAX );
					exit( 1 );
				}
				
				continue;
			}
			
			
			
			/**
			threads option (advanced)
			*/
			case 't':
			case 'T':
			{
				if( G->config->max_threads != MAX_THREADS_DEFAULT )
				{
					MSG_FATAL( "Option 't': this option has already been specified." );
					printf( "max threads: %u\n", G->config->max_threads );
					exit( 1 );
				}
				
				/* this option must have an associated argument (optarg). 
				if an optarg is not found get_next_arg() will exit(1)
				*/
				arf = get_next_arg( &i, OPTARG );
				
				/* option argument found */
				
				/* if the string is not a positive integer representation > 0 */
				if( ( str_to_uint( &G->config->max_threads, G->prog->argv[ i ] ) != NUM_POS ) 
					|| ( G->config->max_threads <= 0 ) 
				)
				{
					MSG_FATAL( "Option 't': maximum number of threads invalid." );
					printf( "num: %s\n", G->prog->argv[ i ] );
					exit( 1 );
				}
				
				continue;
			}
			
			
			
			/**
			test mode include option (advanced)
			*/
			case 'z':
			case 'Z':
			{
				unsigned __int64 id = 0;
				WCHAR *name = NULL;
				
				
				G->config->testlist->type = LIST_INCLUDE_TEST;
				
				/* the 'z' option requires one associated argument (optarg), and a second which is 
				optional.
				*/
				arf = get_next_arg( &i, OPT | OPTARG );
				if( arf != OPTARG )
				{
					print_testmode_usage();
					exit( 1 );
				}
				
				/* make the test name as a wide character string */
				if( !get_wstr_from_mbstr( &name, G->prog->argv[ i ] ) )
				{
					MSG_FATAL( "get_wstr_from_mbstr() failed." );
					printf( "name: %s\n", G->prog->argv[ i ] );
					exit( 1 );
				}
				
				arf = get_next_arg( &i, OPT | OPTARG ); // get the second optarg, which is optional
				
				/* at least one option argument (optarg) was found */
				
				/* if a second optarg was found it's the id. the value of id will be UI64_MAX if 
				the conversion fails or there's no second optarg.
				*/
				if( arf == OPTARG )
					str_to_uint64( &id, G->prog->argv[ i ] );
				else
					id = UI64_MAX;
				
				/* append to the linked list */
				if( !add_list_item( G->config->testlist, (__int64)id, name ) )
				{
					MSG_FATAL( "add_list_item() failed." );
					printf( "test id: 0x%I64X\n", id );
					printf( "test name: %ls\n", name );
					exit( 1 );
				}
				
				/* if add_list_item() was successful then it made a duplicate of the 
				wide string pointed to by name. in any case name should now be freed.
				*/
				free( name );
				name = NULL;
				
				continue;
			}
			
			
			
			/**
			option to ignore internal hooks (advanced)
			*/
			case 'e':
			case 'E':
			{
				G->config->flags |= CFG_IGNORE_INTERNAL_HOOKS;
				arf = get_next_arg( &i, OPT );
				continue;
			}
			
			
			
			/**
			option to ignore known hooks (advanced)
			*/
			case 'u':
			case 'U':
			{
				G->config->flags |= CFG_IGNORE_KNOWN_HOOKS;
				arf = get_next_arg( &i, OPT );
				continue;
			}
			
			
			
			/**
			option to ignore targeted hooks (advanced)
			*/
			case 'g':
			case 'G':
			{
				G->config->flags |= CFG_IGNORE_TARGETED_HOOKS;
				arf = get_next_arg( &i, OPT );
				continue;
			}
			
			
			
			/**
			option to ignore failed NtQuerySystemInformation() calls (advanced)
			*/
			case 'f':
			case 'F':
			{
				G->config->flags |= CFG_IGNORE_FAILED_QUERIES;
				arf = get_next_arg( &i, OPT );
				continue;
			}
			
			
			
			/**
			option to ignore hook lock count changes (advanced)
			*/
			case 'c':
			case 'C':
			{
				G->config->flags |= CFG_IGNORE_LOCK_COUNTS;
				arf = get_next_arg( &i, OPT );
				continue;
			}
			
			
			
			/**
			option to go completely passive (advanced)
			*/
			case 'y':
			case 'Y':
			{
				G->config->flags |= CFG_COMPLETELY_PASSIVE;
				arf = get_next_arg( &i, OPT );
				continue;
			}
			
			
			
			default:
			{
				MSG_FATAL( "Unknown option." );
				printf( "OPT: %s\n", G->prog->argv[ i ] );
				exit( 1 );
			}
		}
	}
	
	
	
	if( ( G->config->proglist->type == LIST_INCLUDE_PROG )
		|| ( G->config->proglist->type == LIST_EXCLUDE_PROG )
	)
		GetSystemTimeAsFileTime( (FILETIME *)&G->config->proglist->init_time );
	
	if( ( G->config->hooklist->type == LIST_INCLUDE_HOOK )
		|| ( G->config->hooklist->type == LIST_EXCLUDE_HOOK )
	)
		GetSystemTimeAsFileTime( (FILETIME *)&G->config->hooklist->init_time );
	
	if( ( G->config->desklist->type == LIST_INCLUDE_DESK ) )
		GetSystemTimeAsFileTime( (FILETIME *)&G->config->desklist->init_time );
	
	if( ( G->config->testlist->type == LIST_INCLUDE_TEST ) )
		GetSystemTimeAsFileTime( (FILETIME *)&G->config->testlist->init_time );
	
	
	/* G->config has been initialized */
	GetSystemTimeAsFileTime( (FILETIME *)&G->config->init_time );
	return;
}
Пример #26
0
void
piglit_init(int argc, char **argv)
{
	GLuint vs, fs_paint_red, fs_sample;
	GLenum fb_status;

	/* Parse params */
	if (argc != 3)
		print_usage_and_exit(argv[0]);
	if (strcmp(argv[1], "sample") == 0)
		subtest = SUBTEST_SAMPLE;
	else if (strcmp(argv[1], "read_pixels") == 0)
		subtest = SUBTEST_READ_PIXELS;
	else if (strcmp(argv[1], "blit") == 0)
		subtest = SUBTEST_BLIT;
	else if (strcmp(argv[1], "copy") == 0)
		subtest = SUBTEST_COPY;
	else
		print_usage_and_exit(argv[0]);
	if (strcmp(argv[2], "rb") == 0)
		use_texture = false;
	else if (strcmp(argv[2], "tex") == 0)
		use_texture = true;
	else
		print_usage_and_exit(argv[0]);

	/* Detect parameter conflicts */
	if (subtest == SUBTEST_SAMPLE && !use_texture) {
		printf("Subtest 'sample' requires buffer_type 'tex'.\n");
		piglit_report_result(PIGLIT_FAIL);
	}

	/* Requirements */
	piglit_require_gl_version(11);
	piglit_require_GLSL_version(110);
	piglit_require_extension("GL_ARB_framebuffer_object");

	/* Compile shaders */
	vs = piglit_compile_shader_text(GL_VERTEX_SHADER, vs_text);
	fs_paint_red = piglit_compile_shader_text(GL_FRAGMENT_SHADER,
						  fs_text_paint_red);
	prog_paint_red = piglit_link_simple_program(vs, fs_paint_red);
	if (!prog_paint_red)
		piglit_report_result(PIGLIT_FAIL);
	fs_sample = piglit_compile_shader_text(GL_FRAGMENT_SHADER,
					       fs_text_sample);
	prog_sample = piglit_link_simple_program(vs, fs_sample);
	if (!prog_sample)
		piglit_report_result(PIGLIT_FAIL);
	if (!piglit_check_gl_error(GL_NO_ERROR))
		piglit_report_result(PIGLIT_FAIL);

	/* Set up framebuffer */
	glGenFramebuffers(1, &fb);
	glBindFramebuffer(GL_FRAMEBUFFER, fb);
	if (use_texture) {
		tex1 = allocate_texture();
		glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
				       GL_TEXTURE_2D, tex1, 0 /* level */);
	} else {
		GLuint rb;
		glGenRenderbuffers(1, &rb);
		glBindRenderbuffer(GL_RENDERBUFFER, rb);
		glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA,
				      TEX_WIDTH, TEX_HEIGHT);
		glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
					  GL_RENDERBUFFER, rb);
	}
	if (!piglit_check_gl_error(GL_NO_ERROR))
		piglit_report_result(PIGLIT_FAIL);
	fb_status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
	if (fb_status != GL_FRAMEBUFFER_COMPLETE) {
		printf("Framebuffer status: %s\n",
		       piglit_get_gl_enum_name(fb_status));
		piglit_report_result(PIGLIT_FAIL);
	}

	/* Set up second texture (used by "copy" test only) */
	if (subtest == SUBTEST_COPY)
		tex2 = allocate_texture();
	if (!piglit_check_gl_error(GL_NO_ERROR))
		piglit_report_result(PIGLIT_FAIL);
}
Пример #27
0
int main(int argc, char *argv[]) {
    struct ns_mgr mgr;
    struct ns_connection *nc;
    int i, redirect = 0;
    const char *vhost = NULL;

    ns_mgr_init(&mgr, NULL);

    /* Parse command line arguments */
    for (i = 1; i < argc; i++) {
        if (strcmp(argv[i], "-D") == 0) {
            mgr.hexdump_file = argv[i + 1];
            i++;
        } else if (strcmp(argv[i], "-k") == 0) {
            s_backend_keepalive = 1;
        } else if (strcmp(argv[i], "-l") == 0 && i + 1 < argc) {
            if (strcmp(argv[i + 1], "-") == 0) {
                s_log_file = stdout;
            } else {
                s_log_file = fopen(argv[i + 1], "a");
                if (s_log_file == NULL) {
                    perror("fopen");
                    exit(EXIT_FAILURE);
                }
            }
            i++;
        } else if (strcmp(argv[i], "-p") == 0) {
            s_http_port = argv[i + 1];
            i++;
        } else if (strcmp(argv[i], "-r") == 0 && i + 1 < argc) {
            redirect = 1;
        } else if (strcmp(argv[i], "-v") == 0 && i + 1 < argc) {
            if (strcmp(argv[i + 1], "") == 0) {
                vhost = NULL;
            } else {
                vhost = argv[i + 1];
            }
            i++;
        } else if (strcmp(argv[i], "-b") == 0 && i + 2 < argc) {
            struct http_backend *be =
                    vhost != NULL ? &s_vhost_backends[s_num_vhost_backends++]
                    : &s_default_backends[s_num_default_backends++];
            STAILQ_INIT(&be->conns);
            char *r = NULL;
            be->vhost = vhost;
            be->uri_prefix = argv[i + 1];
            be->host_port = argv[i + 2];
            be->redirect = redirect;
            be->uri_prefix_replacement = be->uri_prefix;
            if ((r = strchr(be->uri_prefix, '=')) != NULL) {
                *r = '\0';
                be->uri_prefix_replacement = r + 1;
            }
            printf(
                "Adding backend for %s%s : %s "
                "[redirect=%d,prefix_replacement=%s]\n",
                be->vhost == NULL ? "" : be->vhost, be->uri_prefix, be->host_port,
                be->redirect, be->uri_prefix_replacement);
            vhost = NULL;
            redirect = 0;
            i += 2;
#ifdef NS_ENABLE_SSL
        } else if (strcmp(argv[i], "-s") == 0 && i + 1 < argc) {
            s_ssl_cert = argv[++i];
#endif
        } else {
            print_usage_and_exit(argv[0]);
        }
    }

    /* Open listening socket */
    if ((nc = ns_bind(&mgr, s_http_port, ev_handler)) == NULL) {
        fprintf(stderr, "ns_bind(%s) failed\n", s_http_port);
        exit(EXIT_FAILURE);
    }

#if NS_ENABLE_SSL
    if (s_ssl_cert != NULL) {
        const char *err_str = ns_set_ssl(nc, s_ssl_cert, NULL);
        if (err_str != NULL) {
            fprintf(stderr, "Error loading SSL cert: %s\n", err_str);
            exit(1);
        }
    }
#endif
    ns_set_protocol_http_websocket(nc);

    if (s_num_vhost_backends + s_num_default_backends == 0) {
        print_usage_and_exit(argv[0]);
    }

    signal(SIGINT, signal_handler);
    signal(SIGTERM, signal_handler);

    /* Run event loop until signal is received */
    printf("Starting LB on port %s\n", s_http_port);
    while (s_sig_num == 0) {
        ns_mgr_poll(&mgr, 1000);
    }

    /* Cleanup */
    ns_mgr_free(&mgr);

    printf("Exiting on signal %d\n", s_sig_num);

    return EXIT_SUCCESS;
}
Пример #28
0
// main
int
main(int argc, char** argv)
{
	BApplication app("application/x-vnd.antares-netfs_server_prefs");

	// parse first argument
	int argi = 1;
	const char* arg = next_arg(argc, argv, argi);
	if (strcmp(arg, "-h") == 0 || strcmp(arg, "--help") == 0)
		print_usage_and_exit(false);

	if (strcmp(arg, "launch") == 0) {
		// launch
		no_more_args(argc, argi);
		launch_server();
	} else if (strcmp(arg, "terminate") == 0) {
		// terminate
		no_more_args(argc, argi);
		terminate_server();
	} else if (strcmp(arg, "save") == 0) {
		// save
		no_more_args(argc, argi);
		save_server_setttings();
	} else if (strcmp(arg, "l") == 0 || strcmp(arg, "list") == 0) {
		// list
		no_more_args(argc, argi);
		list();
	} else if (strcmp(arg, "add") == 0) {
		// add
		arg = next_arg(argc, argv, argi);
		if (strcmp(arg, "share") == 0) {
			// share
			const char* name = next_arg(argc, argv, argi);
			const char* path = next_arg(argc, argv, argi);
			no_more_args(argc, argi);
			add_share(name, path);
		} else if (strcmp(arg, "user") == 0) {
			// user
			const char* name = next_arg(argc, argv, argi);
			const char* password = next_arg(argc, argv, argi, true);
			no_more_args(argc, argi);
			add_user(name, password);
		} else
			print_usage_and_exit(true);
	} else if (strcmp(arg, "remove") == 0) {
		// remove
		arg = next_arg(argc, argv, argi);
		if (strcmp(arg, "share") == 0) {
			// share
			const char* name = next_arg(argc, argv, argi);
			no_more_args(argc, argi);
			remove_share(name);
		} else if (strcmp(arg, "user") == 0) {
			// user
			const char* name = next_arg(argc, argv, argi);
			no_more_args(argc, argi);
			remove_user(name);
		} else
			print_usage_and_exit(true);
	} else if (strcmp(arg, "permissions") == 0) {
		// permissions
		const char* user = next_arg(argc, argv, argi);
		const char* share = next_arg(argc, argv, argi);
		uint32 permissions = 0;
		while (argi < argc) {
			uint32 perms = 0;
			arg = next_arg(argc, argv, argi);
			if (!get_permissions(arg, &perms))
				print_usage_and_exit(true);
			permissions |= perms;
		}
		set_user_permissions(user, share, permissions);
	} else {
		print_usage_and_exit(true);
	}

	return 0;
}
Пример #29
0
/* main 
 * graph is read from a given file as parameter */
int main(int argc, char *argv[])
{
    if(argc < 2)
    {
        print_usage_and_exit();
    }
    
    int option = 0;
    int greedyIterations = 10;
    char fileName[255];
    bool isFileNameSet = false;
    int iterationsCount = 1;
    bool printTime = false;
    bool printEFTEC = false;
    bool printMinimumCr = false;
    bool lessVerbose = false;
    bool distributedTime = false;
    
    while ((option = getopt(argc, argv,"f:i:temn:ld")) != -1) 
    {
        switch (option)
        {
             case 'f' : strcpy(fileName, optarg);
						isFileNameSet = true;
                 break;
             case 'i' : iterationsCount = atoi(optarg);
                 break;
             case 't' : printTime = true;
                 break;
             case 'e' : printEFTEC = true;
                 break;
             case 'm' : printMinimumCr = true;
                 break;
             case 'n' : greedyIterations = atoi(optarg);
				 break;
             case 'l':  lessVerbose = true;
                 break;
             case 'd': distributedTime = true;
                 break;
             default: print_usage_and_exit(); 
        }   
    }   
    
    if (!isFileNameSet)
    {
        print_usage_and_exit();
    }

    
    int edgesCount, vertexCount, edgesFailedToEmbedCount;
    int minCr = 9999999, sumCr = 0;

    int ** edgesList = readGraphFromFile(fileName, &edgesCount, &vertexCount);
    
    if(edgesList == NULL)
    {
        std::cout << "reading from file failed" << std::endl;
        exit(1);
    }

    int ** edgesFailedToEmbedList = (int**)malloc(edgesCount * sizeof(int*));
    
    for(int i = 0; i < edgesCount; i++)
    {
    	edgesFailedToEmbedList[i] = (int*)malloc(2 * sizeof(int));
    }

    std::vector<std::pair<int, int> > * edgesSucceedToEmbed = new std::vector<std::pair<int, int> >;

    clock_t begin, end, cbegin = 0, cend = 0, ebegin = 0, eend = 0;
    double time_spent;
    
	int minEFTEC = 0;
	
    begin = clock();
	//MAIN BODY
    
	
    for(int i = 0; i < iterationsCount; i++)
    {
        ebegin = clock();
		edgesFailedToEmbedCount = getEFTEC(edgesList, edgesCount, 
			edgesFailedToEmbedList, edgesSucceedToEmbed, greedyIterations);
        eend = clock();
        
	    cbegin = clock();
		int cr = getCrossingNumber(edgesSucceedToEmbed, edgesCount,
			edgesFailedToEmbedList, edgesFailedToEmbedCount, vertexCount);
	    cend = clock();
        if(cr < minCr)
		{
			minCr = cr;
			minEFTEC = edgesFailedToEmbedCount;
		}
		
		sumCr += cr;
	}
	
	//END MAIN BODY
	end = clock();

	time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
    if(lessVerbose)
    {
        std::cout << minCr << std::endl;
    }
    else
    {
        if(distributedTime)
        {
            std::cout << "time spent on EFTEC search - " << (double)(eend - ebegin) / CLOCKS_PER_SEC << std::endl;
            std::cout << "time spent on crossings search - " << (double)(cend - cbegin) / CLOCKS_PER_SEC << std::endl;
        } 
        if(printTime)
        {
            std::cout << "time spent - " << time_spent << std::endl;
        }
        
        if(printEFTEC)
        {
            
            std::cout << "EFTEC - " << minEFTEC << std::endl;
        }
        
        if(printMinimumCr)
        {
            std::cout << "minimum crossing number - " << minCr << std::endl;
        }
        
        std::cout << "average crossing number - " << (float)sumCr / iterationsCount << std::endl;
    }
	
	delete edgesSucceedToEmbed;
    freeEdgesList(edgesList, edgesCount);
    freeEdgesList(edgesFailedToEmbedList, edgesCount);
    
    return 0;
}
Пример #30
0
int main(int argc, char *argv[]) {
    char * bytes_count_str = NULL;
    char * devname;
    reiserfs_filsys_t fs;
    struct reiserfs_super_block * rs;

    int c;
    int error;

    struct reiserfs_super_block *sb_old;

    unsigned long block_count_new;

    print_banner ("resize_reiserfs");

    while ((c = getopt(argc, argv, "fvcqs:")) != EOF) {
        switch (c) {
        case 's' :
            if (!optarg)
                die("%s: Missing argument to -s option", argv[0]);
            bytes_count_str = optarg;
            break;
        case 'f':
            opt_force = 1;
            break;
        case 'v':
            opt_verbose++;
            break;
        case 'n':
            /* no nowrite option at this moment */
            /* opt_nowrite = 1; */
            break;
        case 'c':
            opt_safe = 1;
            break;
        case 'q':
            opt_verbose = 0;
            break;
        default:
            print_usage_and_exit ();
        }
    }

    if (optind == argc )
        print_usage_and_exit();
    devname = argv[optind];

    fs = reiserfs_open(devname, O_RDONLY, &error, 0);
    if (!fs)
        die ("%s: can not open '%s': %s", argv[0], devname, strerror(error));

    if (no_reiserfs_found (fs)) {
        die ("resize_reiserfs: no reiserfs found on the device");
    }
    if (!spread_bitmaps (fs)) {
        die ("resize_reiserfs: cannot resize reiserfs in old (not spread bitmap) format.\n");
    }

    rs = fs->s_rs;

    if(bytes_count_str) {	/* new fs size is specified by user */
        block_count_new = calc_new_fs_size(rs_block_count(rs), fs->s_blocksize, bytes_count_str);
    } else {		/* use whole device */
        block_count_new = count_blocks(devname, fs->s_blocksize, -1);
    }

    if (is_mounted (devname)) {
        reiserfs_close(fs);
        return resize_fs_online(devname, block_count_new);
    }

    if (rs_state(rs) != REISERFS_VALID_FS)
        die ("%s: the file system isn't in valid state\n", argv[0]);

    if(!valid_offset(fs->s_dev, (loff_t) block_count_new * fs->s_blocksize - 1))
        die ("%s: %s too small", argv[0], devname);

    sb_old = 0;		/* Needed to keep idiot compiler from issuing false warning */
    /* save SB for reporting */
    if(opt_verbose) {
        sb_old = getmem(SB_SIZE);
        memcpy(sb_old, SB_DISK_SUPER_BLOCK(fs), SB_SIZE);
    }

    if (block_count_new == SB_BLOCK_COUNT(fs))
        die ("%s: Calculated fs size is the same as the previous one.", argv[0]);

    if (block_count_new > SB_BLOCK_COUNT(fs))
        expand_fs(fs, block_count_new);
    else
        shrink_fs(fs, block_count_new);

    if(opt_verbose) {
        sb_report(rs, sb_old);
        freemem(sb_old);
    }

    set_state (rs, REISERFS_VALID_FS);
    bwrite_cond(SB_BUFFER_WITH_SB(fs));

    if (opt_verbose) {
        printf("\nSyncing..");
        fflush(stdout);
    }
    reiserfs_close (fs);
    if (opt_verbose)
        printf("done\n");

    return 0;
}