Status initializeGlobalShardingState(OperationContext* txn,
                                     const ConnectionString& configCS,
                                     bool allowNetworking) {
    if (configCS.type() == ConnectionString::SYNC) {
        return {ErrorCodes::UnsupportedFormat,
                "SYNC config server connection string is not allowed."};
    }

    SyncClusterConnection::setConnectionValidationHook(
        [](const HostAndPort& target, const executor::RemoteCommandResponse& isMasterReply) {
            return ShardingNetworkConnectionHook::validateHostImpl(target, isMasterReply);
        });
    auto network =
        executor::makeNetworkInterface("NetworkInterfaceASIO-ShardRegistry",
                                       stdx::make_unique<ShardingNetworkConnectionHook>(),
                                       stdx::make_unique<ShardingEgressMetadataHook>());
    auto networkPtr = network.get();
    auto shardRegistry(
        stdx::make_unique<ShardRegistry>(stdx::make_unique<RemoteCommandTargeterFactoryImpl>(),
                                         makeTaskExecutorPool(std::move(network)),
                                         networkPtr,
                                         makeTaskExecutor(executor::makeNetworkInterface(
                                             "NetworkInterfaceASIO-ShardRegistry-TaskExecutor")),
                                         configCS));

    auto catalogManager = makeCatalogManager(getGlobalServiceContext(),
                                             shardRegistry.get(),
                                             HostAndPort(getHostName(), serverGlobalParams.port));

    shardRegistry->startup();
    grid.init(std::move(catalogManager),
              std::move(shardRegistry),
              stdx::make_unique<ClusterCursorManager>(getGlobalServiceContext()->getClockSource()));

    while (!inShutdown()) {
        try {
            Status status = grid.catalogManager(txn)->startup(txn, allowNetworking);
            uassertStatusOK(status);

            if (serverGlobalParams.configsvrMode == CatalogManager::ConfigServerMode::NONE) {
                grid.shardRegistry()->reload(txn);
            }
            return Status::OK();
        } catch (const DBException& ex) {
            Status status = ex.toStatus();
            if (status == ErrorCodes::ReplicaSetNotFound) {
                // ReplicaSetNotFound most likely means we've been waiting for the config replica
                // set to come up for so long that the ReplicaSetMonitor stopped monitoring the set.
                // Rebuild the config shard to force the monitor to resume monitoring the config
                // servers.
                grid.shardRegistry()->rebuildConfigShard();
            }
            log() << "Error initializing sharding state, sleeping for 2 seconds and trying again"
                  << causedBy(status);
            sleepmillis(2000);
            continue;
        }
    }

    return Status::OK();
}
Esempio n. 2
0
StoragePtr TableFunctionRemote::executeImpl(const ASTPtr & ast_function, const Context & context) const
{
    ASTs & args_func = typeid_cast<ASTFunction &>(*ast_function).children;

    if (args_func.size() != 1)
        throw Exception(help_message, ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH);

    ASTs & args = typeid_cast<ASTExpressionList &>(*args_func.at(0)).children;

    const size_t max_args = is_cluster_function ? 3 : 5;
    if (args.size() < 2 || args.size() > max_args)
        throw Exception(help_message, ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH);

    String cluster_name;
    String cluster_description;
    String remote_database;
    String remote_table;
    String username;
    String password;

    size_t arg_num = 0;

    auto getStringLiteral = [](const IAST & node, const char * description)
    {
        const ASTLiteral * lit = typeid_cast<const ASTLiteral *>(&node);
        if (!lit)
            throw Exception(description + String(" must be string literal (in single quotes)."), ErrorCodes::BAD_ARGUMENTS);

        if (lit->value.getType() != Field::Types::String)
            throw Exception(description + String(" must be string literal (in single quotes)."), ErrorCodes::BAD_ARGUMENTS);

        return safeGet<const String &>(lit->value);
    };

    if (is_cluster_function)
    {
        ASTPtr ast_name = evaluateConstantExpressionOrIdentifierAsLiteral(args[arg_num], context);
        cluster_name = static_cast<const ASTLiteral &>(*ast_name).value.safeGet<const String &>();
    }
    else
    {
        if (auto ast_cluster = typeid_cast<const ASTIdentifier *>(args[arg_num].get()))
            cluster_name = ast_cluster->name;
        else
            cluster_description = getStringLiteral(*args[arg_num], "Hosts pattern");
    }
    ++arg_num;

    args[arg_num] = evaluateConstantExpressionOrIdentifierAsLiteral(args[arg_num], context);
    remote_database = static_cast<const ASTLiteral &>(*args[arg_num]).value.safeGet<String>();
    ++arg_num;

    size_t dot = remote_database.find('.');
    if (dot != String::npos)
    {
        /// NOTE Bad - do not support identifiers in backquotes.
        remote_table = remote_database.substr(dot + 1);
        remote_database = remote_database.substr(0, dot);
    }
    else
    {
        if (arg_num >= args.size())
            throw Exception(help_message, ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH);

        args[arg_num] = evaluateConstantExpressionOrIdentifierAsLiteral(args[arg_num], context);
        remote_table = static_cast<const ASTLiteral &>(*args[arg_num]).value.safeGet<String>();
        ++arg_num;
    }

    /// Username and password parameters are prohibited in cluster version of the function
    if (!is_cluster_function)
    {
        if (arg_num < args.size())
        {
            username = getStringLiteral(*args[arg_num], "Username");
            ++arg_num;
        }
        else
            username = "******";

        if (arg_num < args.size())
        {
            password = getStringLiteral(*args[arg_num], "Password");
            ++arg_num;
        }
    }

    if (arg_num < args.size())
        throw Exception(help_message, ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH);

    /// ExpressionAnalyzer will be created in InterpreterSelectQuery that will meet these `Identifier` when processing the request.
    /// We need to mark them as the name of the database or table, because the default value is column.
    for (auto & arg : args)
        if (ASTIdentifier * id = typeid_cast<ASTIdentifier *>(arg.get()))
            id->kind = ASTIdentifier::Table;

    ClusterPtr cluster;
    if (!cluster_name.empty())
    {
        /// Use an existing cluster from the main config
        cluster = context.getCluster(cluster_name);
    }
    else
    {
        /// Create new cluster from the scratch
        size_t max_addresses = context.getSettingsRef().table_function_remote_max_addresses;
        std::vector<String> shards = parseDescription(cluster_description, 0, cluster_description.size(), ',', max_addresses);

        std::vector<std::vector<String>> names;
        for (size_t i = 0; i < shards.size(); ++i)
            names.push_back(parseDescription(shards[i], 0, shards[i].size(), '|', max_addresses));

        if (names.empty())
            throw Exception("Shard list is empty after parsing first argument", ErrorCodes::BAD_ARGUMENTS);

        cluster = std::make_shared<Cluster>(context.getSettings(), names, username, password, context.getTCPPort(), false);
    }

    auto res = StorageDistributed::createWithOwnCluster(
        getName(),
        getStructureOfRemoteTable(*cluster, remote_database, remote_table, context),
        remote_database,
        remote_table,
        cluster,
        context);
    res->startup();
    return res;
}
Esempio n. 3
0
Main::Main(QWidget *parent) :
CoastalMain()
{
    ui.setupUi((QMainWindow *)this);
    status(tr("loading..."));

    indexData = NULL;
    index_validator = new ValidateIndex;

    program_name = "Coastal Manpager";
    program_about = "Coastal Manual Page Viewer";

    QWidget *toolbar = extendToolbar(ui.toolBar);
    tb.setupUi(toolbar);

    QSettings settings;
    resize(settings.value("size", QSize(760, 540)).toSize());

#ifdef Q_OS_WIN
    const char *separator = ";";
    QString manpath = settings.value("manpath").toString();
    if(manpath.isEmpty())
        manpath = "C:\\tools\\man";
#else
    const char *separator = ":";
    QString manpath = getenv("MANPATH");
    if(manpath.isEmpty())
        manpath = settings.value("manpath").toString();

    if(manpath.isEmpty())
        manpath = "/usr/share/man:/usr/local/share/man";
#endif

    manpaths = manpath.split(separator, QString::SkipEmptyParts);

    sections[0] = ui.actionSection1;
    sections[1] = ui.actionSection2;
    sections[2] = ui.actionSection3;
    sections[3] = ui.actionSection4;
    sections[4] = ui.actionSection5;
    sections[5] = ui.actionSection6;
    sections[6] = ui.actionSection7;
    sections[7] = ui.actionSection8;
    sections[8] = ui.actionSectionl;
    sections[9] = ui.actionSectionn;

    settings.beginGroup("Sections");
    ui.actionSection1->setChecked(settings.value("1", ui.actionSection1->isChecked()).toBool());
    ui.actionSection2->setChecked(settings.value("2", ui.actionSection2->isChecked()).toBool());
    ui.actionSection3->setChecked(settings.value("3", ui.actionSection3->isChecked()).toBool());
    ui.actionSection4->setChecked(settings.value("4", ui.actionSection4->isChecked()).toBool());
    ui.actionSection5->setChecked(settings.value("5", ui.actionSection5->isChecked()).toBool());
    ui.actionSection6->setChecked(settings.value("6", ui.actionSection6->isChecked()).toBool());
    ui.actionSection7->setChecked(settings.value("7", ui.actionSection7->isChecked()).toBool());
    ui.actionSection8->setChecked(settings.value("8", ui.actionSection8->isChecked()).toBool());
    ui.actionSectionl->setChecked(settings.value("l", ui.actionSectionl->isChecked()).toBool());
    ui.actionSectionn->setChecked(settings.value("n", ui.actionSectionn->isChecked()).toBool());
    settings.endGroup();

    searchGroup = new QActionGroup(this);
    ui.actionIndex->setActionGroup(searchGroup);
    ui.actionKeywords->setActionGroup(searchGroup);

    ui.indexView->setEnabled(false);
    ui.indexView->setShowGrid(false);
    ui.indexView->setSortingEnabled(false);
    ui.indexView->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui.indexView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui.indexView->setSelectionMode(QAbstractItemView::SingleSelection);
    ui.indexView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);

    ui.indexView->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(ui.indexView, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(open(const QPoint&)));

    // menu action signals

    connect(ui.actionOptions, SIGNAL(triggered()), this, SLOT(options()));
    connect(ui.actionAbout, SIGNAL(triggered()), this, SLOT(about()));
    connect(ui.actionQuit, SIGNAL(triggered()), qApp, SLOT(quit()));
    connect(ui.actionReload, SIGNAL(triggered()), this, SLOT(reload()));
    connect(ui.actionSupport, SIGNAL(triggered()), this, SLOT(support()));

    connect(ui.actionAll, SIGNAL(triggered()), this, SLOT(all()));
    connect(ui.actionClear, SIGNAL(triggered()), this, SLOT(clear()));

    for(unsigned pos = 0; pos < 10; ++pos)
        connect(sections[pos], SIGNAL(triggered()), this, SLOT(reload()));

    // input validation

    tb.searchBox->setValidator(index_validator);

    // forms, tabs, and view signals

    connect(tb.searchBox, SIGNAL(editTextChanged(const QString&)), this, SLOT(search(const QString&)));
    connect(tb.searchBox, SIGNAL(activated(const QString&)), this, SLOT(load(const QString&)));
    connect(ui.tabs, SIGNAL(tabCloseRequested(int)), this, SLOT(close(int)));
    connect(ui.indexView, SIGNAL(activated(const QModelIndex&)), this, SLOT(load(const QModelIndex&)));
    connect(ui.actionView, SIGNAL(triggered()), this, SLOT(view()));
    connect(ui.actionOpen, SIGNAL(triggered()), this, SLOT(open()));

    // application signals

    connect(this, SIGNAL(resized()), this, SLOT(columns()));
    connect(this, SIGNAL(startup()), this, SLOT(reload()), Qt::QueuedConnection);

    setContextMenuPolicy(Qt::CustomContextMenu);
    connect(this, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(menu(const QPoint&)));

    emit startup();
}
Esempio n. 4
0
 //! Startup with given logger.
 void startup(logger_ptr logger)
 {
   startup(std::thread::hardware_concurrency(), logger, 0, true);
 }
Esempio n. 5
0
int main(int argc, char **argv) {
	int return_status = 1;

	#define MAIN_SDL_CHECK(expression, error_prefix) { \
		if (!(expression)) { \
			log_error(error_prefix, SDL_GetError()); \
			goto exit; \
		} \
	}

	MAIN_SDL_CHECK(SDL_Init(SDL_INIT_VIDEO) == 0, "SDL_Init");
	if (IMG_Init(IMG_INIT_PNG) != IMG_INIT_PNG) {
		log_error("IMG_Init", IMG_GetError());
		goto exit;
	}

	MAIN_SDL_CHECK(SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "2"), "SDL_SetHint SDL_HINT_RENDER_SCALE_QUALITY");

	startup_info_t info = startup(argc, argv);
	if (!info.success)
		goto exit;

	net_mode_t net_mode = info.net_mode;
	network = info.network;

	char wtitle[256];
	if (net_mode == NET_SERVER) {
		snprintf(wtitle, sizeof(wtitle), "NetCheckers - server (%s)", info.port);
	} else {
		snprintf(wtitle, sizeof(wtitle), "NetCheckers - client (%s:%s)", info.host, info.port);
	}
	window = SDL_CreateWindow(
		wtitle,
#if 1
		SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
#else
		(net_mode == NET_SERVER ? 10 : window_width + 20), SDL_WINDOWPOS_CENTERED,
#endif
		window_width, window_height,
		SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI
	);
	MAIN_SDL_CHECK(window, "SDL_CreateWindow");

	renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
	MAIN_SDL_CHECK(renderer, "SDL_CreateRenderer");
	MAIN_SDL_CHECK(SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND) == 0, "SDL_SetRenderDrawBlendMode SDL_BLENDMODE_BLEND");

	char *error = 0;
	char path[1024];
	#define LOAD_TEXTURE_CHECKED(var, file) { \
		sprintf(path, "%s/" file, info.assets_path); \
		var = load_png_texture(path, &error); \
		if (error) { \
			log_error("load_png_texture " file, error); \
			goto exit; \
		} \
	}
	LOAD_TEXTURE_CHECKED(tex.textures.board, "board.png");
	LOAD_TEXTURE_CHECKED(tex.textures.red_piece, "piece_red.png");
	LOAD_TEXTURE_CHECKED(tex.textures.red_piece_king, "piece_red_king.png");
	LOAD_TEXTURE_CHECKED(tex.textures.white_piece, "piece_white.png");
	LOAD_TEXTURE_CHECKED(tex.textures.white_piece_king, "piece_white_king.png");
	LOAD_TEXTURE_CHECKED(tex.textures.highlight, "highlight.png");
	LOAD_TEXTURE_CHECKED(tex.textures.player_turn, "player_turn.png");
	LOAD_TEXTURE_CHECKED(tex.textures.opponent_turn, "opponent_turn.png");
	LOAD_TEXTURE_CHECKED(tex.textures.victory, "victory.png");
	LOAD_TEXTURE_CHECKED(tex.textures.defeat, "defeat.png");

	window_resized(window_width, window_height);

// Put the pieces on the board
#if 0
	// Game over testing
	for (int i = 0; i < 24; i++) {
		piece_t *piece = pieces + i;
		piece->color = (i >= 12) ? PIECE_BLACK : PIECE_WHITE;
		piece->captured = true;
	}
	pieces[0].captured = false;
	pieces[0].king = true;
	pieces[0].pos = cell_pos(1, 3);
	board[1][3] = &pieces[0];

	pieces[12].captured = false;
	pieces[12].king = true;
	pieces[12].pos = cell_pos(5, 3);
	board[5][3] = &pieces[12];
#else
	int fill_row = 0;
	int fill_col = 0;

	for (int i = 0; i < 12; i++) {
		piece_t *piece = pieces + i;
		piece->color = PIECE_WHITE;
		piece->pos = cell_pos(fill_row, fill_col);
		board[fill_row][fill_col] = piece;
		advance_board_row_col(&fill_row, &fill_col);
	}

	fill_row = 5;
	fill_col = 1;
	for (int i = 12; i < 24; i++) {
		piece_t *piece = pieces + i;
		piece->color = PIECE_BLACK;
		piece->pos = cell_pos(fill_row, fill_col);
		board[fill_row][fill_col] = piece;
		advance_board_row_col(&fill_row, &fill_col);
	}
#endif

	game_over = false;
	current_turn = PIECE_BLACK;
	local_color = (net_mode == NET_SERVER) ? PIECE_BLACK : PIECE_WHITE;

	bool running = true;
	int last_time = SDL_GetTicks();
	while (running) {
		int current_time = SDL_GetTicks();
		int ellapsed_ms = current_time - last_time;
		last_time = current_time;
		float delta_time = (float)ellapsed_ms / 1000.0f;

		SDL_Event event = {0};
		while (SDL_PollEvent(&event)) {
			switch (event.type) {
				case SDL_QUIT: {
					running = false;
				} break;
				case SDL_WINDOWEVENT: {
					if (event.window.event == SDL_WINDOWEVENT_SIZE_CHANGED) {
						window_resized(event.window.data1, event.window.data2);
					}
				} break;
				case SDL_MOUSEBUTTONDOWN: {
					#if 1
					if (event.button.state == SDL_PRESSED && event.button.button == SDL_BUTTON_RIGHT) {
						message_t net_msg = {0};
						net_msg.move_piece = cell_pos(5, 1);
						net_msg.move_target = cell_pos(4, 0);
						net_send_message(network, &net_msg);
					}
					#endif
					if (event.button.state == SDL_PRESSED && event.button.button == SDL_BUTTON_LEFT) {
						if (!game_over && !animating_piece && current_turn == local_color) {
							int click_x = event.button.x * dpi_rate;
							int click_y = event.button.y * dpi_rate;
							if (rect_includes(&board_rect, click_x, click_y)) {
								cell_pos_t clicked_cell = point_to_cell(click_x, click_y);
								piece_t *clicked_piece = board[clicked_cell.row][clicked_cell.col];
								if (clicked_piece && clicked_piece->color == current_turn) {
									piece_moves_t moves = find_valid_moves(clicked_piece);
									if (moves.count) {
										selected_piece = clicked_piece;
										available_moves = moves;
									}
								} else if (selected_piece) {
									cell_pos_t from_cell = selected_piece->pos;

									move_result_t res = perform_move(selected_piece, clicked_cell);
									if (res != MOVE_INVALID) {
										if (res == MOVE_END_TURN) {
											selected_piece = 0;
										} else {
											available_moves = find_valid_moves(selected_piece);
										}

										message_t net_msg = {0};
										net_msg.move_piece = from_cell;
										net_msg.move_target = clicked_cell;
										if (!net_send_message(network, &net_msg)) {
											int err = SDL_ShowSimpleMessageBox(
												SDL_MESSAGEBOX_ERROR,
												"Erro - Falha de comunicação",
												"Falha ao enviar movimento para o adversário.",
												window
											);
											if (err) {
												log_error("SDL_ShowSimpleMessageBox invalid movement", SDL_GetError());
											}
											goto exit;
										}
									}
								}
							}
						}
					}
				} break;
			}
		}

		if (net_get_state(network) != NET_RUNNING) {
			int err = SDL_ShowSimpleMessageBox(
				SDL_MESSAGEBOX_ERROR,
				"Erro - Conexão Interrompida",
				"A conexão foi interrompida pelo adversário",
				window
			);
			if (err) {
				log_error("SDL_ShowSimpleMessageBox invalid movement", SDL_GetError());
			}
			goto exit;
		}

		message_t net_msg;
		if (net_poll_message(network, &net_msg)) {
			bool valid_move = false;

			piece_t *piece = board[net_msg.move_piece.row][net_msg.move_piece.col];
			if (piece && current_turn != local_color && piece->color != local_color) {
				move_result_t res = perform_move(piece, net_msg.move_target);
				if (res != MOVE_INVALID)
					valid_move = true;
			}

			if (!valid_move) {
				int err = SDL_ShowSimpleMessageBox(
					SDL_MESSAGEBOX_ERROR,
					"Erro - Movimento inválido",
					"Seu adversário enviou um movimento inválido.",
					window
				);
				if (err) {
					log_error("SDL_ShowSimpleMessageBox invalid movement", SDL_GetError());
				}
				goto exit;
			}
		}

		render(delta_time);
	}

	return_status = 0;
exit:
	if (network)
		net_destroy(network);
	for (int i = 0; i < ARRAY_SIZE(tex.array); i++) {
		if (tex.array[i])
			SDL_DestroyTexture(tex.array[i]);
	}
	if (renderer)
		SDL_DestroyRenderer(renderer);
	if (window)
		SDL_DestroyWindow(window);
	IMG_Quit();
	SDL_Quit();
	return return_status;
}
Esempio n. 6
0
int
main(int argc, char *argv[])
{
	int ch, reps, ret;
	const char *config, *home;

	config = NULL;

	if ((g.progname = strrchr(argv[0], '/')) == NULL)
		g.progname = argv[0];
	else
		++g.progname;

#if 0
	/* Configure the GNU malloc for debugging. */
	(void)setenv("MALLOC_CHECK_", "2", 1);
#endif
#if 0
	/* Configure the FreeBSD malloc for debugging. */
	(void)setenv("MALLOC_OPTIONS", "AJ", 1);
#endif

	/* Track progress unless we're re-directing output to a file. */
	g.track = isatty(STDOUT_FILENO) ? 1 : 0;

	/* Set values from the command line. */
	home = NULL;
	while ((ch = getopt(argc, argv, "1C:c:h:Llqrt:")) != EOF)
		switch (ch) {
		case '1':			/* One run */
			g.c_runs = 1;
			break;
		case 'C':			/* wiredtiger_open config */
			g.config_open = optarg;
			break;
		case 'c':			/* Configuration from a file */
			config = optarg;
			break;
		case 'h':
			home = optarg;
			break;
		case 'L':			/* Re-direct output to a log */
			/*
			 * The -l option is a superset of -L, ignore -L if we
			 * have already configured logging for operations.
			 */
			if (g.logging == 0)
				g.logging = LOG_FILE;
			break;
		case 'l':			/* Turn on operation logging */
			g.logging = LOG_OPS;
			break;
		case 'q':			/* Quiet */
			g.track = 0;
			break;
		case 'r':			/* Replay a run */
			g.replay = 1;
			break;
		default:
			usage();
		}
	argc -= optind;
	argv += optind;

	/*
	 * If we weren't given a configuration file, set values from "CONFIG",
	 * if it exists.
	 *
	 * Small hack to ignore any CONFIG file named ".", that just makes it
	 * possible to ignore any local CONFIG file, used when running checks.
	 */
	if (config == NULL && access("CONFIG", R_OK) == 0)
		config = "CONFIG";
	if (config != NULL && strcmp(config, ".") != 0)
		config_file(config);

	/*
	 * The rest of the arguments are individual configurations that modify
	 * the base configuration.
	 */
	for (; *argv != NULL; ++argv)
		config_single(*argv, 1);

	/*
	 * Multithreaded runs can be replayed: it's useful and we'll get the
	 * configuration correct.  Obviously the order of operations changes,
	 * warn the user.
	 */
	if (g.replay && !SINGLETHREADED)
		printf("Warning: replaying a threaded run\n");

	/*
	 * Single-threaded runs historically exited after a single replay, which
	 * makes sense when you're debugging, leave that semantic in place.
	 */
	if (g.replay && SINGLETHREADED)
		g.c_runs = 1;

	/* Use line buffering on stdout so status updates aren't buffered. */
	(void)setvbuf(stdout, NULL, _IOLBF, 0);

	/*
	 * Initialize locks to single-thread named checkpoints and hot backups
	 * and to single-thread last-record updates.
	 */
	if ((ret = pthread_rwlock_init(&g.append_lock, NULL)) != 0)
		die(ret, "pthread_rwlock_init: append lock");
	if ((ret = pthread_rwlock_init(&g.backup_lock, NULL)) != 0)
		die(ret, "pthread_rwlock_init: hot-backup lock");

	/* Clean up on signal. */
	(void)signal(SIGINT, onint);

	/* Seed the random number generator. */
	srand((u_int)(0xdeadbeef ^ (u_int)time(NULL)));

	/* Set up paths. */
	path_setup(home);

	printf("%s: process %" PRIdMAX "\n", g.progname, (intmax_t)getpid());
	while (++g.run_cnt <= g.c_runs || g.c_runs == 0 ) {
		startup();			/* Start a run */

		config_setup();			/* Run configuration */
		config_print(0);		/* Dump run configuration */
		key_len_setup();		/* Setup keys */

		track("starting up", 0ULL, NULL);
		if (SINGLETHREADED)
			bdb_open();		/* Initial file config */
		wts_open(g.home, 1, &g.wts_conn);
		wts_create();

		wts_load();			/* Load initial records */
		wts_verify("post-bulk verify");	/* Verify */

						/* Loop reading & operations */
		for (reps = 0; reps < 3; ++reps) {
			wts_read_scan();	/* Read scan */

			if (g.c_ops != 0)	/* Random operations */
				wts_ops();

			/*
			 * Statistics.
			 *
			 * XXX
			 * Verify closes the underlying handle and discards the
			 * statistics, read them first.
			 */
			if (g.c_ops == 0 || reps == 2)
				wts_stats();

						/* Verify */
			wts_verify("post-ops verify");

			/*
			 * If no operations scheduled, quit after a single
			 * read pass.
			 */
			if (g.c_ops == 0)
				break;
		}

		track("shutting down", 0ULL, NULL);
		if (SINGLETHREADED)
			bdb_close();
		wts_close();

		/*
		 * If single-threaded, we can dump and compare the WiredTiger
		 * and Berkeley DB data sets.
		 */
		if (SINGLETHREADED)
			wts_dump("standard", 1);

		/*
		 * If no records are deleted, we can salvage the file and test
		 * the result.  (The problem with deleting records is salvage
		 * restores deleted records if a page splits leaving a deleted
		 * record on one side of the split.)
		 *
		 * Salvage, verify the salvaged files, then dump (comparing
		 * against the Berkeley DB data set again, if possible).
		 */
		if (g.c_delete_pct == 0) {
			wts_open(g.home, 1, &g.wts_conn);
			wts_salvage();
			wts_verify("post-salvage verify");
			wts_close();

			wts_dump("salvage", SINGLETHREADED);
		}

		/* Overwrite the progress line with a completion line. */
		if (g.track)
			printf("\r%78s\r", " ");
		printf("%4d: %s, %s\n",
		    g.run_cnt, g.c_data_source, g.c_file_type);
	}

	/* Flush/close any logging information. */
	if (g.logfp != NULL)
		(void)fclose(g.logfp);
	if (g.rand_log != NULL)
		(void)fclose(g.rand_log);

	config_print(0);

	if ((ret = pthread_rwlock_destroy(&g.append_lock)) != 0)
		die(ret, "pthread_rwlock_destroy: append lock");
	if ((ret = pthread_rwlock_destroy(&g.backup_lock)) != 0)
		die(ret, "pthread_rwlock_destroy: hot-backup lock");

	config_clear();

	return (EXIT_SUCCESS);
}
Esempio n. 7
0
int
main(int argc, char *argv[])
{
    // define usage
    const char *usage = "Usage: sudoku n00b|l33t [#]\n";

    // ensure that number of arguments is as expected
    if (argc != 2 && argc != 3)
    {
        fprintf(stderr, usage);
        return 1;
    }

    // ensure that level is valid
    if (strcmp(argv[1], "debug") == 0)
        g.level = "debug";
    else if (strcmp(argv[1], "n00b") == 0)
        g.level = "n00b";
    else if (strcmp(argv[1], "l33t") == 0)
        g.level = "l33t";
    else
    {
        fprintf(stderr, usage);
        return 2;
    }

    // n00b and l33t levels have 1024 boards; debug level has 9
    int max = (strcmp(g.level, "debug") == 0) ? 9 : 1024;

    // ensure that #, if provided, is in [1, max]
    if (argc == 3)
    {
        // ensure n is integral
        char c;
        if (sscanf(argv[2], " %d %c", &g.number, &c) != 1)
        {
            fprintf(stderr, usage);
            return 3;
        }

        // ensure n is in [1, max]
        if (g.number < 1 || g.number > max)
        {
            fprintf(stderr, "That board # does not exist!\n");
            return 4;
        }

        // seed PRNG with # so that we get same sequence of boards
        srand(g.number);
    }
    else
    {
        // seed PRNG with current time so that we get any sequence of boards
        srand(time(NULL));

        // choose a random n in [1, max]
        g.number = rand() % max + 1;
    }

    // start up ncurses
    if (!startup())
    {
        fprintf(stderr, "Error starting up ncurses!\n");
        return 5;
    }

    // register handler for SIGWINCH (SIGnal WINdow CHanged)
    signal(SIGWINCH, (void (*)(int)) handle_signal);

    // start the first game
    if (!restart_game())
    {
        shutdown();
        fprintf(stderr, "Could not load board from disk!\n");
        return 6;
    }
    redraw_all();
    
    // initialize legal variable
    g.legal = true;
    
    // initialize won variable
    g.won = false;

    // let the user play!
    int ch;
    do
    {
        // refresh the screen
        refresh();

        // get user's input
        ch = getch();

        // capitalize input to simplify cases
        ch = toupper(ch);

        // process user's input
        switch (ch)
        {
            // start a new game
            case 'N': 
                g.number = rand() % max + 1;
                if (!restart_game())
                {
                    shutdown();
                    fprintf(stderr, "Could not load board from disk!\n");
                    return 6;
                }
                break;

            // restart current game
            case 'R': 
                if (!restart_game())
                {
                    shutdown();
                    fprintf(stderr, "Could not load board from disk!\n");
                    return 6;
                }
                break;

            // let user manually redraw screen with ctrl-L
            case CTRL('l'):
                redraw_all();
                break;
            
            // move cursor on the board   
            case KEY_DOWN:                
            case KEY_UP:
            case KEY_LEFT:
            case KEY_RIGHT:
                move_cursor(ch);
                break;
                
            case KEY_BACKSPACE:
            case KEY_DC:
            case 46: // .
            case 48: // 0
            case 49: // 1
            case 50: // 2
            case 51: // 3
            case 52: // 4
            case 53: // 5
            case 54: // 6
            case 55: // 7
            case 56: // 8
            case 57: // 9
                change_number(ch);
                if(!legal(ch))
                {
                    show_banner("Illegal Move...");
                    show_cursor();
                    g.legal = false;
                }
                else
                {
                    hide_banner();
                    show_cursor();
                    g.legal = true;
                }
                if(won(ch))
                {
                    show_banner("You Won The Game!!!");
                    g.won = true;
                }
                break;
        }
        

        // log input (and board's state) if any was received this iteration
        if (ch != ERR)
            log_move(ch);
    }
    while (ch != 'Q');

    // shut down ncurses
    shutdown();

    // tidy up the screen (using ANSI escape sequences)
    printf("\033[2J");
    printf("\033[%d;%dH", 0, 0);

    // that's all folks
    printf("\nkthxbai!\n\n");
    return 0;
}
Esempio n. 8
0
int main(int argc, char **argv)
{
   startup(argc,argv);  /* setup configurations */
   old_main();          /* LATER: exit(daemon()); */
   return 0;            /* if we didn't exit before, just give back success */
}
void CHostGameSettingsState::Enter()
{
    prevMouse = POINT{ 0, 0 };
    guiInterface = new CRenderGUI(CGame::GetInstance()->GetRenderer());
    float width = (float)GlobalDef::windowWidth;
    float height = (float)GlobalDef::windowHeight;
    guiInterface->LoadTexture("backGround", L"Assets/Textures/HostSettings.dds");
    guiInterface->LoadTexture("Map", L"Assets/Textures/Map.dds");

    mBackGroundImg = new CGUIElement(guiInterface->GetTextureSRV("backGround"), .99f, 0, 0, 1920, 1080);
    mMapImg = new CGUIElement(guiInterface->GetTextureSRV("Map"), Layer(1), 0, 0, 275, 275);
    RECT rect;
    rect.top = 0;
    rect.left = 0;
    rect.right = (LONG)width;
    rect.bottom = (LONG)height;
    mBackGroundImg->SetScreenDisplayRect(rect);
    mBackGroundImg->SetScreenPos(0, 0.f);
    guiInterface->AddGUIElement(mBackGroundImg);
    guiInterface->AddGUIElement(mMapImg);
    mMapImg->SetScreenPos(0.4156f * width, 0.2648f * height);
    LeftMapArrow = new CButton(guiInterface, L"Assets/Textures/LeftArrow.dds", Layer(2), 65, 65);
    LeftMapArrow->SetPosition(0.385f * width, 0.36204f * height);
    LeftMapArrow->SetScale(0.5f);

    RightMapArrow = new CButton(guiInterface, L"Assets/Textures/RightArrow.dds", Layer(2), 65, 65);
    RightMapArrow->SetPosition(0.565f * width, 0.36204f * height);
    RightMapArrow->SetScale(0.5f);

    LeftPlayerArrow = new CButton(guiInterface, L"Assets/Textures/LeftArrow.dds", Layer(2), 65, 65);
    LeftPlayerArrow->SetPosition(0.495f * width, 0.555f * height);
    LeftPlayerArrow->SetScale(0.3f);

    RightPlayerArrow = new CButton(guiInterface, L"Assets/Textures/RightArrow.dds", Layer(2), 65, 65);
    RightPlayerArrow->SetPosition(0.585f * width, 0.555f * height);
    RightPlayerArrow->SetScale(0.3f);


    LeftStartArrow = new CButton(guiInterface, L"Assets/Textures/LeftArrow.dds", Layer(2), 65, 65);
    LeftStartArrow->SetPosition(0.495f * width, 0.625f * height);
    LeftStartArrow->SetScale(0.3f);

    RightStartArrow = new CButton(guiInterface, L"Assets/Textures/RightArrow.dds", Layer(2), 65, 65);
    RightStartArrow->SetPosition(0.585f * width, 0.625f * height);
    RightStartArrow->SetScale(0.3f);

    LeftEndArrow = new CButton(guiInterface, L"Assets/Textures/LeftArrow.dds", Layer(2), 65, 65);
    LeftEndArrow->SetPosition(0.495f * width, 0.695f * height);
    LeftEndArrow->SetScale(0.3f);

    RightEndArrow = new CButton(guiInterface, L"Assets/Textures/RightArrow.dds", Layer(2), 65, 65);
    RightEndArrow->SetPosition(0.585f * width, 0.695f * height);
    RightEndArrow->SetScale(0.3f);

    ContinueButton = new CButton(guiInterface, L"Assets/Textures/ContinueButton.dds", Layer(2), 250, 74);
    ContinueButton->SetPosition(0.425f * width, 0.75f * height);
    ContinueButton->SetScale(0.8f);

    mPlayerText = new CGUIElement(to_wstring(MaxPlayers), .96f, (int)(0.54f * width), (int)(0.545f * height), (int)(0.58f * width), (int)(0.585f * height), false, XMFLOAT2(0.75f, 0.75f), DirectX::Colors::Black);
    guiInterface->AddGUIElement(mPlayerText);
    mStartText = new CGUIElement(to_wstring(StartWave), .96f, (int)(0.54f * width), (int)(0.615f * height), (int)(0.58f * width), (int)(0.655f * height), false, XMFLOAT2(0.75f, 0.75f), DirectX::Colors::Black);
    guiInterface->AddGUIElement(mStartText);
    mEndText = new CGUIElement(to_wstring(EndWave), .96f, (int)(0.54f * width), (int)(0.685f * height), (int)(0.58f * width), (int)(0.725f * height), false, XMFLOAT2(0.75f, 0.75f), DirectX::Colors::Black);
    guiInterface->AddGUIElement(mEndText);

    guiInterface->LoadTexture("Cursor", L"Assets/Textures/Cursor.dds");
    Cursor = new CGUIElement(guiInterface->GetTextureSRV("Cursor"), Layer(0), 0, 0, 124, 224, false);
    Cursor->SetScale(0.25f);
    Cursor->SetRotation(-0.5f);
    guiInterface->AddGUIElement(Cursor);
    startup("../SirCuddlesServer/SirCuddlesServer.exe");
    closing = false;
    CGame::GetInstance()->GetEventSystem()->Subscribe(EventID::Keypress, this);
    guiInterface->FadeIn();

    LeftPlayerArrow->Fading(false);
    RightPlayerArrow->Fading(false);
    LeftMapArrow->Fading(false);
    RightMapArrow->Fading(false);
    LeftStartArrow->Fading(false);
    RightStartArrow->Fading(false);
    LeftEndArrow->Fading(false);
    RightEndArrow->Fading(false);
    ContinueButton->Fading(false);
}
Esempio n. 10
0
/*
 * JNI methods
 */
JNIEXPORT jint JNICALL Java_com_mangrajalkin_synth_Synth_startup
   (JNIEnv *env, jobject obj){
	return startup();
}
Esempio n. 11
0
Common::Error BladeRunnerEngine::run() {
	Graphics::PixelFormat format = createRGB555();
	initGraphics(640, 480, &format);

	_system->showMouse(true);

	bool hasSavegames = !SaveFileManager::list(_targetName).empty();

	if (!startup(hasSavegames)) {
		shutdown();
		return Common::Error(Common::kUnknownError, "Failed to initialize resources");
	}



#if BLADERUNNER_DEBUG_GAME
	{
#else
	if (warnUserAboutUnsupportedGame()) {
#endif
		if (hasSavegames) {
			_kia->_forceOpen = true;
			_kia->open(kKIASectionLoad);
		}
		// TODO: why is game starting new game here when everything is done in startup?
		//  else {
		// 	newGame(1);
		// }

		gameLoop();

		_mouse->disable();

		if (_gameOver) {
			// autoSaveGame(4, 1); // TODO
			_endCredits->show();
		}
	}

	shutdown();

	return Common::kNoError;
}

bool BladeRunnerEngine::startup(bool hasSavegames) {
	// These are static objects in original game

	_screenEffects = new ScreenEffects(this, 0x8000);

	_endCredits = new EndCredits(this);

	_actorDialogueQueue = new ActorDialogueQueue(this);

	_settings = new Settings(this);

	_itemPickup = new ItemPickup(this);

	_lights = new Lights(this);

	// TODO: outtake player - but this is done bit differently

	_policeMaze = new PoliceMaze(this);

	_obstacles = new Obstacles(this);

	_sceneScript = new SceneScript(this);

	_debugger = new Debugger(this);

	// This is the original startup in the game

	bool r;

	_surfaceFront.create(640, 480, createRGB555());
	_surfaceBack.create(640, 480, createRGB555());
	_surface4.create(640, 480, createRGB555());

	_gameTime = new Time(this);

	r = openArchive("STARTUP.MIX");
	if (!r)
		return false;

	_gameInfo = new GameInfo(this);
	if (!_gameInfo)
		return false;

	r = _gameInfo->open("GAMEINFO.DAT");
	if (!r) {
		return false;
	}


	// TODO: Create datetime - not used

	// TODO: Create graphics surfaces 1-4

	// TODO: Allocate audio cache

	if (hasSavegames) {
		if (!loadSplash()) {
			return false;
		}
	}

	_waypoints = new Waypoints(this, _gameInfo->getWaypointCount());

	_combat = new Combat(this);

	_gameVars = new int[_gameInfo->getGlobalVarCount()]();

	// TODO: Init Actor AI Update counter

	// Seed rand

	// TODO: Sine and cosine lookup tables for intervals of 1.0, 4.0, and 12.0
	_cosTable1024 = new Common::CosineTable(1024); // 10-bits = 1024 points for 2*PI;
	_sinTable1024 = new Common::SineTable(1024);

	_view = new View();

	_sceneObjects = new SceneObjects(this, _view);

	_gameFlags = new GameFlags();
	_gameFlags->setFlagCount(_gameInfo->getFlagCount());

	_items = new Items(this);

	_audioMixer = new AudioMixer(this);

	_audioPlayer = new AudioPlayer(this);

	_music = new Music(this);

	_audioSpeech = new AudioSpeech(this);

	_ambientSounds = new AmbientSounds(this);

	// TODO: Read BLADE.INI

	_chapters = new Chapters(this);
	if (!_chapters)
		return false;

	if (!openArchive("MUSIC.MIX"))
		return false;

	if (!openArchive("SFX.MIX"))
		return false;

	if (!openArchive("SPCHSFX.TLK"))
		return false;

	_overlays = new Overlays(this);
	_overlays->init();

	_zbuffer = new ZBuffer();
	_zbuffer->init(640, 480);

	int actorCount = (int)_gameInfo->getActorCount();
	assert(actorCount < kActorCount);
	for (int i = 0; i != actorCount; ++i) {
		_actors[i] = new Actor(this, i);
		_actors[i]->setup(i);
	}
	_actors[kActorVoiceOver] = new Actor(this, kActorVoiceOver);
	_playerActor = _actors[_gameInfo->getPlayerId()];

	_playerActor->setFPS(15);
	_playerActor->timerStart(6, 200);

	// TODO: Set actor ids (redundant?)

	_policeMaze = new PoliceMaze(this);

	_textActorNames = new TextResource(this);
	if (!_textActorNames->open("ACTORS"))
		return false;

	_textCrimes = new TextResource(this);
	if (!_textCrimes->open("CRIMES"))
		return false;

	_textClueTypes = new TextResource(this);
	if (!_textClueTypes->open("CLUETYPE"))
		return false;

	_textKIA = new TextResource(this);
	if (!_textKIA->open("KIA"))
		return false;

	_textSpinnerDestinations = new TextResource(this);
	if (!_textSpinnerDestinations->open("SPINDEST"))
		return false;

	_textVK = new TextResource(this);
	if (!_textVK->open("VK"))
		return false;

	_textOptions = new TextResource(this);
	if (!_textOptions->open("OPTIONS"))
		return false;

	_dialogueMenu = new DialogueMenu(this);
	if (!_dialogueMenu->loadText("DLGMENU"))
		return false;

	_suspectsDatabase = new SuspectsDatabase(this, _gameInfo->getSuspectCount());

	_kia = new KIA(this);

	_spinner = new Spinner(this);

	_elevator = new Elevator(this);

	_scores = new Scores(this);

	_mainFont = new Font(this);
	_mainFont->open("KIA6PT.FON", 640, 480, -1, 0, 0x252D);
	_mainFont->setSpacing(1, 0);

	for (int i = 0; i != 43; ++i) {
		Shape *shape = new Shape(this);
		shape->open("SHAPES.SHP", i);
		_shapes.push_back(shape);
	}

	_esper = new ESPER(this);

	_vk = new VK(this);

	_mouse = new Mouse(this);
	// _mouse->setCursorPosition(320, 240);
	_mouse->setCursor(0);

	_sliceAnimations = new SliceAnimations(this);
	r = _sliceAnimations->open("INDEX.DAT");
	if (!r)
		return false;

	r = _sliceAnimations->openCoreAnim();
	if (!r) {
		return false;
	}

	_sliceRenderer = new SliceRenderer(this);
	_sliceRenderer->setScreenEffects(_screenEffects);

	_crimesDatabase = new CrimesDatabase(this, "CLUES", _gameInfo->getClueCount());

	// TODO: Scene
	_scene = new Scene(this);

	// Load INIT.DLL
	InitScript initScript(this);
	initScript.SCRIPT_Initialize_Game();

	// TODO: Load AI-ACT1.DLL
	_aiScripts = new AIScripts(this, actorCount);

	initChapterAndScene();

	return true;
}
Esempio n. 12
0
/*
   Movers move the unprocessed updated tokens from the update queue table to
   the main memory task queue. They also wake up the doers whenever they move
   any new tokens to the task queue.
 */
DWORD WINAPI mover(LPVOID ptr)
{
    int result;
    int i;

#if !defined _MIDDLE
    MI_CONNECTION *conn = NULL;
    conn = startup();
#endif

    while (!g_fTerminate)
    {
        // The mover dispatcher can wake up the movers when a data source is updated
        WaitForSingleObject(wakeup_mover_by_mover_dispatcher_sem, INFINITE);
        if (g_fTerminate)
            break;

        // Increment the number of active movers
        EnterCriticalSection(&mover_num_mutex);
        num_mover++;
        LeaveCriticalSection(&mover_num_mutex );

        EnterCriticalSection(&suspend_mutex);
        // Lock the mutex so that the cleaners and the movers are not
        // active at the same time
        EnterCriticalSection(&mover_cleaner_mutex);

#ifdef _MIDDLE
        // Movers perform till the task queue is full or when all the tokens from the updated
        // data sources have been moved.
        // A ceiling is imposed on the task queue to apply back pressure on the movers
        // to stop after the task queue is full. This will prevent the doers from lagging behind
        // and movers from moving too many tolens at the same time.
        result = TASK_QUEUE_NOT_FULL;
        while (result == TASK_QUEUE_NOT_FULL)
        {
            result = vl_move_tasks();
            if ((result == TASK_QUEUE_FULL) || (result == TASK_QUEUE_NOT_FULL))
                // Wake up all the doers
            {
                for (i = 0; i < MAXDOER; i++)
                    ReleaseSemaphore(wakeup_doer_by_mover_sem, 1, NULL);
            }
        }
#else
        result = execUDR(conn,"execute function vl_move_tasks();");
#endif

        LeaveCriticalSection(&mover_cleaner_mutex);
        LeaveCriticalSection(&suspend_mutex);

        // Decrement the number of active movers
        EnterCriticalSection(&mover_num_mutex);
        num_mover--;
        LeaveCriticalSection(&mover_num_mutex );
    }

    // Release the doers.
    for (i = 0; i < MAXDOER; i++)
    {
        ReleaseSemaphore(wakeup_doer_by_mover_sem, 1, NULL);
    }
#if !defined _MIDDLE
    mi_close(conn);
#endif

    return 1;
}
Esempio n. 13
0
int main(int argc,char* argv[])
{
    if(argc != 3)
    {
        usage(argv[0]);
        exit(1);
    }

    signal(SIGCHLD,wait_child);
    char* ip = argv[1];
    int port =atoi( argv[2]);

    struct sockaddr_in client_info;//out
    socklen_t client_len = 0;//out
    int listen_sock = startup(ip,port);
    printf("blind and listen success,please wait accept data!\n");

    while(1)
    {
       int new_client = accept(listen_sock,(struct sockaddr*)&client_info,&client_len);
       if(new_client < 0)
       {
           perror("accept");
           continue;
       }

       printf("get a new connect...\n");
#ifdef _FUN1_
       char buf[1024];
       memset(buf,'\0',sizeof(buf));
       printf("usage fun1...\n");
       while(1)
       {
           ssize_t _size = read(new_client,buf,sizeof(buf)-1);
           if(_size < 0)
           {
               perror("read");
               break;
           }else if(_size == 0)
           {
               printf("client is release\n");
               break;
           }else
           {
               buf[_size] = '\0';
               printf("client:->%s\n",buf);
           }
       }
#endif
#ifdef _FUN2_ 
       printf("many procs,use fun2.......\n");
       pid_t id = fork();
       if(id < 0)
       {
           perror("fork");
           exit(1);
       }else if(id == 0){
          // close(listen_sock);
           char buf[1024];
           while(1)
           {
                memset(buf,'\0',sizeof(buf));
                ssize_t _size = read(new_client,buf,sizeof(buf)-1);
               if(_size < 0)
               {
                   perror("read");
                   exit(1);
               }
               else if(_size == 0){
                   printf("client is release\n");
                   exit(1);
               }else{
                   printf("client->%s\n",buf);
                   continue;
               }
           }
           //close(new_client);
           //exit(1);
           continue;
       }
#endif
#ifdef _FUN3_
       printf("thread,use fun3..........\n");
       pthread_t t_id;
       pthread _create(&t_id,NULL,thread_run,(void*)new_client);
       pthread_detach(t_id);
#endif
    }
    return 0;
}
Esempio n. 14
0
/*
 * mpool_t *mpool_open
 *
 * DESCRIPTION:
 *
 * Open/allocate a new memory pool.
 *
 * RETURNS:
 *
 * Success - Pool pointer which must be passed to mpool_close to
 * deallocate.
 *
 * Failure - NULL
 *
 * ARGUMENTS:
 *
 * flags -> Flags to set attributes of the memory pool.  See the top
 * of mpool.h.
 *
 * page_size -> Set the internal memory page-size.  This must be a
 * multiple of the getpagesize() value.  Set to 0 for the default.
 *
 * start_addr -> Starting address to try and allocate memory pools.
 * This is ignored if the MPOOL_FLAG_USE_SBRK is enabled.
 *
 * error_p <- Pointer to integer which, if not NULL, will be set with
 * a mpool error code.
 */
mpool_t	*mpool_open(const unsigned int flags, const unsigned int page_size,
                    void *start_addr, int *error_p)
{
    mpool_block_t	*block_p;
    int		page_n, ret;
    mpool_t	mp, *mp_p;
    void		*free_addr;

    if (! enabled_b) {
        startup();
    }

    /* zero our temp struct */
    memset(&mp, 0, sizeof(mp));

    mp.mp_magic = MPOOL_MAGIC;
    mp.mp_flags = flags;
    mp.mp_alloc_c = 0;
    mp.mp_user_alloc = 0;
    mp.mp_max_alloc = 0;
    mp.mp_page_c = 0;
    /* mp.mp_page_size set below */
    /* mp.mp_blocks_bit_n set below */
    /* mp.mp_fd set below */
    /* mp.mp_top set below */
    /* mp.mp_addr set below */
    mp.mp_log_func = NULL;
    mp.mp_min_p = NULL;
    mp.mp_bounds_p = NULL;
    mp.mp_first_p = NULL;
    mp.mp_last_p = NULL;
    mp.mp_magic2 = MPOOL_MAGIC;

    /* get and sanity check our page size */
    if (page_size > 0) {
        mp.mp_page_size = page_size;
        if (mp.mp_page_size % getpagesize() != 0) {
            SET_POINTER(error_p, MPOOL_ERROR_ARG_INVALID);
            return NULL;
        }
    }
    else {
        mp.mp_page_size = getpagesize() * DEFAULT_PAGE_MULT;
        if (mp.mp_page_size % 1024 != 0) {
            SET_POINTER(error_p, MPOOL_ERROR_PAGE_SIZE);
            return NULL;
        }
    }

    if (BIT_IS_SET(flags, MPOOL_FLAG_USE_SBRK)) {
        mp.mp_fd = -1;
        mp.mp_addr = NULL;
        mp.mp_top = 0;
    }
    else if (BIT_IS_SET(flags, MPOOL_FLAG_USE_MAP_ANON)) {
        mp.mp_fd = -1;
        mp.mp_addr = start_addr;
        mp.mp_top = 0;
    }
    else {
        /* open dev-zero for our mmaping */
        mp.mp_fd = open("/dev/zero", O_RDWR, 0);
        if (mp.mp_fd < 0) {
            SET_POINTER(error_p, MPOOL_ERROR_OPEN_ZERO);
            return NULL;
        }
        mp.mp_addr = start_addr;
        /* we start at the front of the file */
        mp.mp_top = 0;
    }

    /*
     * Find out how many pages we need for our mpool structure.
     *
     * NOTE: this adds possibly unneeded space for mpool_block_t which
     * may not be in this block.
     */
    page_n = PAGES_IN_SIZE(&mp, sizeof(mpool_t));

    /* now allocate us space for the actual struct */
    mp_p = alloc_pages(&mp, page_n, error_p);
    if (mp_p == NULL) {
        if (mp.mp_fd >= 0) {
            (void)close(mp.mp_fd);
            mp.mp_fd = -1;
        }
        return NULL;
    }

    /*
     * NOTE: we do not normally free the rest of the block here because
     * we want to lesson the chance of an allocation overwriting the
     * main structure.
     */
    if (BIT_IS_SET(flags, MPOOL_FLAG_HEAVY_PACKING)) {

        /* we add a block header to the front of the block */
        block_p = (mpool_block_t *)mp_p;

        /* init the block header */
        block_p->mb_magic = BLOCK_MAGIC;
        block_p->mb_bounds_p = (char *)block_p + SIZE_OF_PAGES(&mp, page_n);
        block_p->mb_next_p = NULL;
        block_p->mb_magic2 = BLOCK_MAGIC;

        /* the mpool pointer is then the 2nd thing in the block */
        mp_p = FIRST_ADDR_IN_BLOCK(block_p);
        free_addr = (char *)mp_p + sizeof(mpool_t);

        /* free the rest of the block */
        ret = free_pointer(&mp, free_addr,
                           (char *)block_p->mb_bounds_p - (char *)free_addr);
        if (ret != MPOOL_ERROR_NONE) {
            if (mp.mp_fd >= 0) {
                (void)close(mp.mp_fd);
                mp.mp_fd = -1;
            }
            /* NOTE: after this line mp_p will be invalid */
            (void)free_pages(block_p, SIZE_OF_PAGES(&mp, page_n),
                             BIT_IS_SET(flags, MPOOL_FLAG_USE_SBRK));
            SET_POINTER(error_p, ret);
            return NULL;
        }

        /*
         * NOTE: if we are HEAVY_PACKING then the 1st block with the mpool
         * header is not on the block linked list.
         */

        /* now copy our tmp structure into our new memory area */
        memcpy(mp_p, &mp, sizeof(mpool_t));

        /* we setup min/max to our current address which is as good as any */
        mp_p->mp_min_p = block_p;
        mp_p->mp_bounds_p = block_p->mb_bounds_p;
    }
    else {
        /* now copy our tmp structure into our new memory area */
        memcpy(mp_p, &mp, sizeof(mpool_t));

        /* we setup min/max to our current address which is as good as any */
        mp_p->mp_min_p = mp_p;
        mp_p->mp_bounds_p = (char *)mp_p + SIZE_OF_PAGES(mp_p, page_n);
    }

    SET_POINTER(error_p, MPOOL_ERROR_NONE);
    return mp_p;
}
Esempio n. 15
0
File: cff.cpp Progetto: EQ4/adplug
/*
  Lempel-Ziv-Tyr ;-)
*/
long CcffLoader::cff_unpacker::unpack(unsigned char *ibuf, unsigned char *obuf)
{
  if (memcmp(ibuf,"YsComp""\x07""CUD1997""\x1A\x04",16))
    return 0;

  input = ibuf + 16;
  output = obuf;

  output_length = 0;

  heap = (unsigned char *)malloc(0x10000);
  dictionary = (unsigned char **)malloc(sizeof(unsigned char *)*0x8000);

  memset(heap,0,0x10000);
  memset(dictionary,0,0x8000);

  cleanup();
  if(!startup())
    goto out;

  // LZW
  while (1)
    {
      new_code = get_code();

      // 0x00: end of data
      if (new_code == 0)
	break;

      // 0x01: end of block
      if (new_code == 1)
	{
	  cleanup();
	  if(!startup())
	    goto out;

	  continue;
	}

      // 0x02: expand code length
      if (new_code == 2)
	{
	  code_length++;

	  continue;
	}

      // 0x03: RLE
      if (new_code == 3)
	{
	  unsigned char old_code_length = code_length;

	  code_length = 2;

	  unsigned char repeat_length = get_code() + 1;

	  code_length = 4 << get_code();

	  unsigned long repeat_counter = get_code();

	  if(output_length + repeat_counter * repeat_length > 0x10000) {
	    output_length = 0;
	    goto out;
	  }

	  for (unsigned int i=0;i<repeat_counter*repeat_length;i++)
	    output[output_length++] = output[output_length - repeat_length];

	  code_length = old_code_length;

	  if(!startup())
	    goto out;

	  continue;
	}

      if (new_code >= (0x104 + dictionary_length))
	{
	  // dictionary <- old.code.string + old.code.char
	  the_string[++the_string[0]] = the_string[1];
	}
      else
	{
	  // dictionary <- old.code.string + new.code.char
	  unsigned char temp_string[256];

	  translate_code(new_code,temp_string);

	  the_string[++the_string[0]] = temp_string[1];
	}

      expand_dictionary(the_string);

      // output <- new.code.string
      translate_code(new_code,the_string);

      if(output_length + the_string[0] > 0x10000) {
	output_length = 0;
	goto out;
      }

      for (int i=0;i<the_string[0];i++)
	output[output_length++] = the_string[i+1];

      old_code = new_code;
    }

 out:
  free(heap);
  free(dictionary);
  return output_length;
}
Esempio n. 16
0
static void start_event(int unused_event, char *context)
{
    SESSION *session = (SESSION *) context;

    startup(session);
}
Esempio n. 17
0
int
main(int argc, char *argv[])
{
    int     i;
    int     rval, ll;
    struct text *kk;

    init();		/* Initialize everything */
    signal(SIGINT, trapdel);

    if (argc > 1) {	/* Restore file specified */
        /* Restart is label 8305 (Fortran) */
        i = restore(argv[1]);	/* See what we've got */
        switch (i) {
        case 0:			/* The restore worked fine */
            yea = Start();
            k = null;
            unlink(argv[1]);/* Don't re-use the save */
            goto l8;	/* Get where we're going */
        case 1:		/* Couldn't open it */
            errx(1, "can't open file");	/* So give up */
        case 2:		/* Oops -- file was altered */
            rspeak(202);	/* You dissolve */
            exit(2);	/* File could be non-adventure */
        }			/* So don't unlink it. */
    }

    startup();		/* prepare for a user		*/

    for (;;) {		/* main command loop (label 2)	*/
        if (newloc < 9 && newloc != 0 && closng) {
            rspeak(130);	/* if closing leave only by	*/
            newloc = loc;	/*	main office		*/
            if (!panic)
                clock2 = 15;
            panic = TRUE;
        }

        rval = fdwarf();		/* dwarf stuff			*/
        if (rval == 99)
            die(99);

l2000:
        if (loc == 0)
            die(99);	/* label 2000			*/
        kk = &stext[loc];
        if ((abb[loc] % abbnum) ==0 || kk->seekadr == 0)
            kk = &ltext[loc];
        if (!forced(loc) && dark()) {
            if (wzdark && pct(35)) {
                die(90);
                goto l2000;
            }
            kk = &rtext[16];
        }
l2001:
        if (toting(bear))
            rspeak(141);	/* 2001			*/
        speak(kk);
        k = 1;
        if (forced(loc))
            goto l8;
        if (loc == 33 && pct(25) && !closng)
            rspeak(8);
        if (!dark()) {
            abb[loc]++;
            for (i = atloc[loc]; i != 0; i = linkx[i]) {	/*2004*/
                obj = i;
                if (obj > 100)
                    obj -= 100;
                if (obj == steps && toting(nugget))
                    continue;
                if (prop[obj] < 0) {
                    if (closed)
                        continue;
                    prop[obj] = 0;
                    if (obj == rug || obj == chain)
                        prop[obj] = 1;
                    tally--;
                    if (tally == tally2 && tally != 0)
                        if (limit > 35)
                            limit = 35;
                }
                ll = prop[obj];	/* 2006	*/
                if (obj == steps && loc == fixed[steps])
                    ll = 1;
                pspeak(obj, ll);
            }		/* 2008 */
            goto l2012;
l2009:
            k = 54;			/* 2009			*/
l2010:
            spk = k;
l2011:
            rspeak(spk);
        }
l2012:
        verb = 0;		/* 2012			*/
        obj = 0;
l2600:
        checkhints();		/* to 2600-2602		*/
        if (closed) {
            if (prop[oyster] < 0 && toting(oyster))
                pspeak(oyster, 1);
            for (i = 1; i < 100; i++)
                if (toting(i) && prop[i] < 0)	/* 2604 */
                    prop[i] = -1 - prop[i];
        }
        wzdark = dark();	/* 2605			*/
        if (knfloc > 0 && knfloc != loc)
            knfloc = 1;
        getin(wd1, sizeof(wd1), wd2, sizeof(wd2));
        if (delhit) {		/* user typed a DEL	*/
            delhit = 0;	/* reset counter	*/
            /* pretend he's quitting */
            strlcpy(wd1, "quit", sizeof(wd1));
            wd2[0] = 0;
        }
l2608:
        if ((foobar = -foobar) > 0)
            foobar = 0;	/* 2608		*/
        /* should check here for "magic mode"		*/
        turns++;
        if (demo && turns >= SHORT)
            done(1);	/* to 13000	*/

        if (verb == say && wd2[0] != 0)
            verb = 0;
        if (verb == say)
            goto l4090;
        if (tally == 0 && loc >= 15 && loc != 33)
            clock1--;
        if (clock1 == 0) {
            closing();			/* to 10000	*/
            goto l19999;
        }
        if (clock1 < 0)
            clock2--;
        if (clock2 == 0) {
            caveclose();		/* to 11000		*/
            continue;		/* back to 2		*/
        }
        if (prop[lamp] == 1)
            limit--;
        if (limit <= 30 && here(batter) && prop[batter] == 0
                && here(lamp)) {
            rspeak(188);		/* 12000		*/
            prop[batter] = 1;
            if (toting(batter))
                drop(batter, loc);
            limit += 2500;
            lmwarn = FALSE;
            goto l19999;
        }
        if (limit == 0) {
            limit = -1;		/* 12400		*/
            prop[lamp] = 0;
            rspeak(184);
            goto l19999;
        }
        if (limit < 0 && loc <= 8) {
            rspeak(185);		/* 12600		*/
            gaveup = TRUE;
            done(2);		/* to 20000		*/
        }
        if (limit <= 30) {
            if (lmwarn || !here(lamp))
                goto l19999;	/*12200*/
            lmwarn = TRUE;
            spk = 187;
            if (place[batter] == 0)
                spk = 183;
            if (prop[batter] == 1)
                spk = 189;
            rspeak(spk);
        }
l19999:
        k = 43;
        if (liqloc(loc) == water)
            k = 70;
        if (weq(wd1, "enter") &&
                (weq(wd2, "strea") || weq(wd2, "water")))
            goto l2010;
        if (weq(wd1, "enter") && *wd2 != 0)
            goto l2800;
        if ((!weq(wd1, "water") && !weq(wd1, "oil"))
                || (!weq(wd2, "plant") && !weq(wd2, "door")))
            goto l2610;
        if (at(vocab(wd2, 1, 0)))
            strlcpy(wd2, "pour", sizeof(wd2));

l2610:
        if (weq(wd1, "west"))
            if (++iwest == 10)
                rspeak(17);
l2630:
        i = vocab(wd1, -1, 0);
        if (i== -1) {
            spk = 60;			/* 3000		*/
            if (pct(20))
                spk = 61;
            if (pct(20))
                spk = 13;
            rspeak(spk);
            goto l2600;
        }
        k = i % 1000;
        kq = i / 1000 + 1;
        switch (kq) {
        case 1:
            goto l8;
        case 2:
            goto l5000;
        case 3:
            goto l4000;
        case 4:
            goto l2010;
        default:
            bug(22);
        }

l8:
        switch (march()) {
        case 2:
            continue;		/* i.e. goto l2		*/
        case 99:
            die(99);
            goto l2000;
        default:
            bug(110);
        }

l2800:
        strlcpy(wd1, wd2, sizeof(wd1));
        wd2[0] = 0;
        goto l2610;

l4000:
        verb = k;
        spk = actspk[verb];
        if (wd2[0] != 0 && verb != say)
            goto l2800;
        if (verb == say)
            obj = wd2[0];
        if (obj != 0)
            goto l4090;
l4080:
        switch (verb) {
        case 1:			/* take = 8010		*/
            if (atloc[loc] == 0 || linkx[atloc[loc]] != 0)
                goto l8000;
            for (i = 1; i <= 5; i++)
                if (dloc[i] == loc && dflag >= 2)
                    goto l8000;
            obj = atloc[loc];
            goto l9010;
        case 2:
        case 3:
        case 9:		/* 8000 : drop, say, wave */
        case 10:
        case 16:
        case 17:	/* calm, rub, toss	*/
        case 19:
        case 21:
        case 28:	/* find, feed, break	*/
        case 29:			/* wake			*/
l8000:
            printf("%s what?\n", wd1);
            obj = 0;
            goto l2600;
        case 4:
        case 6:		/* 8040 open, lock	*/
            spk = 28;
            if (here(clam))
                obj = clam;
            if (here(oyster))
                obj = oyster;
            if (at(door))
                obj = door;
            if (at(grate))
                obj = grate;
            if (obj != 0 && here(chain))
                goto l8000;
            if (here(chain))
                obj = chain;
            if (obj == 0)
                goto l2011;
            goto l9040;
        case 5:
            goto l2009;		/* nothing		*/
        case 7:
            goto l9070;		/* on			*/
        case 8:
            goto l9080;		/* off			*/
        case 11:
            goto l8000;	/* walk			*/
        case 12:
            goto l9120;	/* kill			*/
        case 13:
            goto l9130;	/* pour			*/
        case 14:			/* eat: 8140		*/
            if (!here(food))
                goto l8000;
l8142:
            dstroy(food);
            spk = 72;
            goto l2011;
        case 15:
            goto l9150;	/* drink		*/
        case 18:			/* quit: 8180		*/
            gaveup = yes(22, 54, 54);
            if (gaveup)
                done(2);	/* 8185			*/
            goto l2012;
        case 20:			/* invent = 8200	*/
            spk = 98;
            for (i = 1; i <= 100; i++) {
                if (i != bear && toting(i)) {
                    if (spk == 98)
                        rspeak(99);
                    blklin = FALSE;
                    pspeak(i, -1);
                    blklin = TRUE;
                    spk = 0;
                }
            }
            if (toting(bear))
                spk = 141;
            goto l2011;
        case 22:
            goto l9220;	/* fill			*/
        case 23:
            goto l9230;	/* blast		*/
        case 24:			/* score: 8240		*/
            scorng = TRUE;
            printf("If you were to quit now, you would score");
            printf(" %d out of a possible ", score());
            printf("%d.", mxscor);
            scorng = FALSE;
            gaveup = yes(143, 54, 54);
            if (gaveup)
                done(2);
            goto l2012;
        case 25:			/* foo: 8250		*/
            k = vocab(wd1, 3, 0);
            spk = 42;
            if (foobar == 1 - k)
                goto l8252;
            if (foobar != 0)
                spk = 151;
            goto l2011;
l8252:
            foobar = k;
            if (k != 4)
                goto l2009;
            foobar = 0;
            if (place[eggs] == plac[eggs]
                    || (toting(eggs) && loc == plac[eggs])) goto l2011;
            if (place[eggs] == 0 && place[troll] == 0 && prop[troll] == 0)
                prop[troll] = 1;
            k = 2;
            if (here(eggs))
                k = 1;
            if (loc == plac[eggs])
                k = 0;
            move(eggs, plac[eggs]);
            pspeak(eggs, k);
            goto l2012;
        case 26:			/* brief = 8260		*/
            spk = 156;
            abbnum = 10000;
            detail = 3;
            goto l2011;
        case 27:			/* read = 8270		*/
            if (here(magzin))
                obj = magzin;
            if (here(tablet))
                obj = obj * 100 + tablet;
            if (here(messag))
                obj = obj * 100 + messag;
            if (closed && toting(oyster))
                obj = oyster;
            if (obj > 100 || obj == 0 || dark())
                goto l8000;
            goto l9270;
        case 30:			/* suspend = 8300	*/
            spk = 201;
            if (demo)
                goto l2011;
            printf("I can suspend your adventure for you so");
            printf(" you can resume later, but\n");
            printf("you will have to wait at least");
            printf(" %d minutes before continuing.", latncy);
            if (!yes(200, 54, 54))
                goto l2012;
            time(&savet);
            ciao();		/* Do we quit? */
            continue;		/* Maybe not */
        case 31:			/* hours = 8310		*/
            printf("Colossal cave is closed 9am-5pm Mon ");
            printf("through Fri except holidays.\n");
            goto l2012;
        default:
            bug(23);
        }

l4090:
        switch (verb) {
        case 1:			/* take = 9010		*/
l9010:
            switch (trtake()) {
            case 2011:
                goto l2011;
            case 9220:
                goto l9220;
            case 2009:
                goto l2009;
            case 2012:
                goto l2012;
            default:
                bug(102);
            }
l9020:
        case 2:			/* drop = 9020		*/
            switch (trdrop()) {
            case 2011:
                goto l2011;
            case 19000:
                done(3);
            case 2012:
                goto l2012;
            default:
                bug(105);
            }
l9030:
        case 3:
            switch (trsay()) {
            case 2012:
                goto l2012;
            case 2630:
                goto l2630;
            default:
                bug(107);
            }
l9040:
        case 4:
        case 6:		/* open, close		*/
            switch (tropen()) {
            case 2011:
                goto l2011;
            case 2010:
                goto l2010;
            default:
                bug(106);
            }
        case 5:
            goto l2009;	/* nothing		*/
        case 7:			/* on	9070		*/
l9070:
            if (!here(lamp))
                goto l2011;
            spk = 184;
            if (limit < 0)
                goto l2011;
            prop[lamp] = 1;
            rspeak(39);
            if (wzdark)
                goto l2000;
            goto l2012;

        case 8:			/* off			*/
l9080:
            if (!here(lamp))
                goto l2011;
            prop[lamp] = 0;
            rspeak(40);
            if (dark())
                rspeak(16);
            goto l2012;

        case 9:			/* wave			*/
            if ((!toting(obj)) && (obj != rod || !toting(rod2)))
                spk = 29;
            if (obj != rod || !at(fissur)||!toting(obj) || closng)
                goto l2011;
            prop[fissur] = 1-prop[fissur];
            pspeak(fissur, 2-prop[fissur]);
            goto l2012;
        case 10:
        case 11:
        case 18:	/* calm, walk, quit	*/
        case 24:
        case 25:
        case 26:	/* score, foo, brief	*/
        case 30:
        case 31:		/* suspend, hours	*/
            goto l2011;
l9120:
        case 12:			/* kill			*/
            switch (trkill()) {
            case 8000:
                goto l8000;
            case 8:
                goto l8;
            case 2011:
                goto l2011;
            case 2608:
                goto l2608;
            case 19000:
                done(3);
            default:
                bug(112);
            }
l9130:
        case 13:			/* pour			*/
            if (obj == bottle || obj == 0)
                obj = liq();
            if (obj == 0)
                goto l8000;
            if (!toting(obj))
                goto l2011;
            spk = 78;
            if (obj != oil && obj != water)
                goto l2011;
            prop[bottle] = 1;
            place[obj] = 0;
            spk = 77;
            if (!(at(plant) || at(door)))
                goto l2011;
            if (at(door)) {
                prop[door] = 0;	/* 9132			*/
                if (obj == oil)
                    prop[door] = 1;
                spk = 113 + prop[door];
                goto l2011;
            }
            spk = 112;
            if (obj != water)
                goto l2011;
            pspeak(plant, prop[plant] + 1);
            prop[plant] = (prop[plant] + 2) % 6;
            prop[plant2] = prop[plant] / 2;
            k = null;
            goto l8;
        case 14:			/* 9140 - eat		*/
            if (obj == food)
                goto l8142;
            if (obj == bird || obj == snake || obj == clam || obj == oyster
                    || obj == dwarf || obj == dragon || obj == troll
                    || obj == bear) spk = 71;
            goto l2011;
l9150:
        case 15:			/* 9150 - drink		*/
            if (obj == 0 && liqloc(loc) != water && (liq() != water
                    || !here(bottle)))
                goto l8000;
            if (obj != 0 && obj != water)
                spk = 110;
            if (spk == 110 || liq() != water || !here(bottle))
                goto l2011;
            prop[bottle] = 1;
            place[water] = 0;
            spk = 74;
            goto l2011;
        case 16:			/* 9160: rub		*/
            if (obj != lamp)
                spk = 76;
            goto l2011;
        case 17:			/* 9170: throw		*/
            switch (trtoss()) {
            case 2011:
                goto l2011;
            case 9020:
                goto l9020;
            case 9120:
                goto l9120;
            case 8:
                goto l8;
            case 9210:
                goto l9210;
            default:
                bug(113);
            }
        case 19:
        case 20:		/* 9190: find, invent	*/
            if (at(obj) || (liq() == obj && at(bottle))
                    || k == liqloc(loc))
                spk = 94;
            for (i = 1; i <= 5; i++)
                if (dloc[i] == loc && dflag >= 2 && obj == dwarf)
                    spk = 94;
            if (closed)
                spk = 138;
            if (toting(obj))
                spk = 24;
            goto l2011;
l9210:
        case 21:			/* feed			*/
            switch (trfeed()) {
            case 2011:
                goto l2011;
            default:
                bug(114);
            }
l9220:
        case 22:			/* fill			*/
            switch (trfill()) {
            case 2011:
                goto l2011;
            case 8000:
                goto l8000;
            case 9020:
                goto l9020;
            default:
                bug(115);
            }
l9230:
        case 23:			/* blast		*/
            if (prop[rod2] < 0 || !closed)
                goto l2011;
            bonus = 133;
            if (loc == 115)
                bonus = 134;
            if (here(rod2))
                bonus = 135;
            rspeak(bonus);
            done(2);
l9270:
        case 27:			/* read			*/
            if (dark())
                goto l5190;
            if (obj == magzin)
                spk = 190;
            if (obj == tablet)
                spk = 196;
            if (obj == messag)
                spk = 191;
            if (obj == oyster && hinted[2] && toting(oyster))
                spk = 194;
            if (obj != oyster || hinted[2] || !toting(oyster)
                    || !closed) goto l2011;
            hinted[2] = yes(192, 193, 54);
            goto l2012;
l9280:
        case 28:			/* break		*/
            if (obj == mirror)
                spk = 148;
            if (obj == vase && prop[vase] == 0) {
                spk = 198;
                if (toting(vase))
                    drop(vase, loc);
                prop[vase] = 2;
                fixed[vase] = -1;
                goto l2011;
            }
            if (obj != mirror||!closed)
                goto l2011;
            rspeak(197);
            done(3);
l9290:
        case 29:			/* wake			*/
            if (obj != dwarf||!closed)
                goto l2011;
            rspeak(199);
            done(3);

        default:
            bug(24);
        }

l5000:
        obj = k;
        if (fixed[k] != loc && !here(k))
            goto l5100;
l5010:
        if (wd2[0] != 0)
            goto l2800;
        if (verb != 0)
            goto l4090;
        printf("What do you want to do with the %s?\n", wd1);
        goto l2600;
l5100:
        if (k != grate)
            goto l5110;
        if (loc == 1 || loc == 4 || loc == 7)
            k = dprssn;
        if (loc > 9 && loc < 15)
            k = entrnc;
        if (k != grate)
            goto l8;
l5110:
        if (k != dwarf)
            goto l5120;
        for (i = 1; i <= 5; i++)
            if (dloc[i] == loc && dflag >= 2)
                goto l5010;
l5120:
        if ((liq() == k && here(bottle)) || k == liqloc(loc))
            goto l5010;
        if (obj != plant || !at(plant2) || prop[plant2] == 0)
            goto l5130;
        obj = plant2;
        goto l5010;
l5130:
        if (obj != knife || knfloc != loc)
            goto l5140;
        knfloc = -1;
        spk = 116;
        goto l2011;
l5140:
        if (obj != rod || !here(rod2))
            goto l5190;
        obj = rod2;
        goto l5010;
l5190:
        if ((verb == find || verb == invent) && wd2[0] == 0)
            goto l5010;
        printf("I see no %s here\n", wd1);
        goto l2012;
    }
}
Esempio n. 18
0
int     main(int argc, char **argv)
{
    SESSION *session;
    char   *host;
    char   *port;
    char   *path;
    int     path_len;
    int     sessions = 1;
    int     ch;
    int     i;
    char   *buf;
    const char *parse_err;
    struct addrinfo *res;
    int     aierr;
    const char *protocols = INET_PROTO_NAME_ALL;
    INET_PROTO_INFO *proto_info;
    char   *message_file = 0;

    /*
     * Fingerprint executables and core dumps.
     */
    MAIL_VERSION_STAMP_ALLOCATE;

    signal(SIGPIPE, SIG_IGN);
    msg_vstream_init(argv[0], VSTREAM_ERR);

    /*
     * Parse JCL.
     */
    while ((ch = GETOPT(argc, argv, "46AcC:df:F:l:Lm:M:Nor:R:s:S:t:T:vw:")) > 0) {
        switch (ch) {
        case '4':
            protocols = INET_PROTO_NAME_IPV4;
            break;
        case '6':
            protocols = INET_PROTO_NAME_IPV6;
            break;
        case 'A':
            allow_reject = 1;
            break;
        case 'c':
            count++;
            break;
        case 'C':
            if ((connect_count = atoi(optarg)) <= 0)
                msg_fatal("bad connection count: %s", optarg);
            break;
        case 'd':
            disconnect = 0;
            break;
        case 'f':
            sender = optarg;
            break;
        case 'F':
            if (message_file == 0 && message_length > 0)
                msg_fatal("-l option cannot be used with -F");
            message_file = optarg;
            break;
        case 'l':
            if (message_file != 0)
                msg_fatal("-l option cannot be used with -F");
            if ((message_length = atoi(optarg)) <= 0)
                msg_fatal("bad message length: %s", optarg);
            break;
        case 'L':
            talk_lmtp = 1;
            break;
        case 'm':
            if ((message_count = atoi(optarg)) <= 0)
                msg_fatal("bad message count: %s", optarg);
            break;
        case 'M':
            if (*optarg == '[') {
                if (!valid_mailhost_literal(optarg, DO_GRIPE))
                    msg_fatal("bad address literal: %s", optarg);
            } else {
                if (!valid_hostname(optarg, DO_GRIPE))
                    msg_fatal("bad hostname: %s", optarg);
            }
            var_myhostname = optarg;
            break;
        case 'N':
            number_rcpts = 1;
            break;
        case 'o':
            send_helo_first = 0;
            send_headers = 0;
            break;
        case 'r':
            if ((recipients = atoi(optarg)) <= 0)
                msg_fatal("bad recipient count: %s", optarg);
            break;
        case 'R':
            if (fixed_delay > 0)
                msg_fatal("do not use -w and -R options at the same time");
            if ((random_delay = atoi(optarg)) <= 0)
                msg_fatal("bad random delay: %s", optarg);
            break;
        case 's':
            if ((sessions = atoi(optarg)) <= 0)
                msg_fatal("bad session count: %s", optarg);
            break;
        case 'S':
            subject = optarg;
            break;
        case 't':
            recipient = optarg;
            break;
        case 'T':
            if ((inet_windowsize = atoi(optarg)) <= 0)
                msg_fatal("bad TCP window size: %s", optarg);
            break;
        case 'v':
            msg_verbose++;
            break;
        case 'w':
            if (random_delay > 0)
                msg_fatal("do not use -w and -R options at the same time");
            if ((fixed_delay = atoi(optarg)) <= 0)
                msg_fatal("bad fixed delay: %s", optarg);
            break;
        default:
            usage(argv[0]);
        }
    }
    if (argc - optind != 1)
        usage(argv[0]);

    if (random_delay > 0)
        srand(getpid());

    /*
     * Initialize the message content, SMTP encoded. smtp_fputs() will append
     * another \r\n but we don't care.
     */
    if (message_file != 0) {
        VSTREAM *fp;
        VSTRING *buf = vstring_alloc(100);
        VSTRING *msg = vstring_alloc(100);

        if ((fp = vstream_fopen(message_file, O_RDONLY, 0)) == 0)
            msg_fatal("open %s: %m", message_file);
        while (vstring_get_nonl(buf, fp) != VSTREAM_EOF) {
            if (*vstring_str(buf) == '.')
                VSTRING_ADDCH(msg, '.');
            vstring_memcat(msg, vstring_str(buf), VSTRING_LEN(buf));
            vstring_memcat(msg, "\r\n", 2);
        }
        if (vstream_ferror(fp))
            msg_fatal("read %s: %m", message_file);
        vstream_fclose(fp);
        vstring_free(buf);
        message_length = VSTRING_LEN(msg);
        message_data = vstring_export(msg);
        send_headers = 0;
    } else if (message_length > 0) {
        message_data = mymalloc(message_length);
        memset(message_data, 'X', message_length);
        for (i = 80; i < message_length; i += 80) {
            message_data[i - 80] = "0123456789"[(i / 80) % 10];
            message_data[i - 2] = '\r';
            message_data[i - 1] = '\n';
        }
    }

    /*
     * Translate endpoint address to internal form.
     */
    proto_info = inet_proto_init("protocols", protocols);
    if (strncmp(argv[optind], "unix:", 5) == 0) {
        path = argv[optind] + 5;
        path_len = strlen(path);
        if (path_len >= (int) sizeof(sun.sun_path))
            msg_fatal("unix-domain name too long: %s", path);
        memset((char *) &sun, 0, sizeof(sun));
        sun.sun_family = AF_UNIX;
#ifdef HAS_SUN_LEN
        sun.sun_len = path_len + 1;
#endif
        memcpy(sun.sun_path, path, path_len);
        sa = (struct sockaddr *) & sun;
        sa_length = sizeof(sun);
    } else {
        if (strncmp(argv[optind], "inet:", 5) == 0)
            argv[optind] += 5;
        buf = mystrdup(argv[optind]);
        if ((parse_err = host_port(buf, &host, (char *) 0, &port, "smtp")) != 0)
            msg_fatal("%s: %s", argv[optind], parse_err);
        if ((aierr = hostname_to_sockaddr(host, port, SOCK_STREAM, &res)) != 0)
            msg_fatal("%s: %s", argv[optind], MAI_STRERROR(aierr));
        myfree(buf);
        sa = (struct sockaddr *) & ss;
        if (res->ai_addrlen > sizeof(ss))
            msg_fatal("address length %d > buffer length %d",
                      (int) res->ai_addrlen, (int) sizeof(ss));
        memcpy((char *) sa, res->ai_addr, res->ai_addrlen);
        sa_length = res->ai_addrlen;
#ifdef HAS_SA_LEN
        sa->sa_len = sa_length;
#endif
        freeaddrinfo(res);
    }

    /*
     * Make sure the SMTP server cannot run us out of memory by sending
     * never-ending lines of text.
     */
    if (buffer == 0) {
        buffer = vstring_alloc(100);
        vstring_ctl(buffer, VSTRING_CTL_MAXLEN, (ssize_t) var_line_limit, 0);
    }

    /*
     * Make sure we have sender and recipient addresses.
     */
    if (var_myhostname == 0)
        var_myhostname = get_hostname();
    if (sender == 0 || recipient == 0) {
        vstring_sprintf(buffer, "foo@%s", var_myhostname);
        defaddr = mystrdup(vstring_str(buffer));
        if (sender == 0)
            sender = defaddr;
        if (recipient == 0)
            recipient = defaddr;
    }

    /*
     * Start sessions.
     */
    while (sessions-- > 0) {
        session = (SESSION *) mymalloc(sizeof(*session));
        session->stream = 0;
        session->xfer_count = 0;
        session->connect_count = connect_count;
        session->next = 0;
        session_count++;
        startup(session);
    }
    for (;;) {
        event_loop(-1);
        if (session_count <= 0 && message_count <= 0) {
            if (count) {
                VSTREAM_PUTC('\n', VSTREAM_OUT);
                vstream_fflush(VSTREAM_OUT);
            }
            exit(0);
        }
    }
}
Esempio n. 19
0
ExitCode _initAndListen(int listenPort) {
    Client::initThread("initandlisten");

    initWireSpec();
    auto serviceContext = getGlobalServiceContext();

    serviceContext->setFastClockSource(FastClockSourceFactory::create(Milliseconds(10)));
    auto opObserverRegistry = stdx::make_unique<OpObserverRegistry>();
    opObserverRegistry->addObserver(stdx::make_unique<OpObserverShardingImpl>());
    opObserverRegistry->addObserver(stdx::make_unique<UUIDCatalogObserver>());

    if (serverGlobalParams.clusterRole == ClusterRole::ShardServer) {
        opObserverRegistry->addObserver(stdx::make_unique<ShardServerOpObserver>());
    } else if (serverGlobalParams.clusterRole == ClusterRole::ConfigServer) {
        opObserverRegistry->addObserver(stdx::make_unique<ConfigServerOpObserver>());
    }
    setupFreeMonitoringOpObserver(opObserverRegistry.get());


    serviceContext->setOpObserver(std::move(opObserverRegistry));

    DBDirectClientFactory::get(serviceContext).registerImplementation([](OperationContext* opCtx) {
        return std::unique_ptr<DBClientBase>(new DBDirectClient(opCtx));
    });

    const repl::ReplSettings& replSettings =
        repl::ReplicationCoordinator::get(serviceContext)->getSettings();

    {
        ProcessId pid = ProcessId::getCurrent();
        LogstreamBuilder l = log(LogComponent::kControl);
        l << "MongoDB starting : pid=" << pid << " port=" << serverGlobalParams.port
          << " dbpath=" << storageGlobalParams.dbpath;

        const bool is32bit = sizeof(int*) == 4;
        l << (is32bit ? " 32" : " 64") << "-bit host=" << getHostNameCached() << endl;
    }

    DEV log(LogComponent::kControl) << "DEBUG build (which is slower)" << endl;

#if defined(_WIN32)
    VersionInfoInterface::instance().logTargetMinOS();
#endif

    logProcessDetails();

    serviceContext->setServiceEntryPoint(
        stdx::make_unique<ServiceEntryPointMongod>(serviceContext));

    if (!storageGlobalParams.repair) {
        auto tl =
            transport::TransportLayerManager::createWithConfig(&serverGlobalParams, serviceContext);
        auto res = tl->setup();
        if (!res.isOK()) {
            error() << "Failed to set up listener: " << res;
            return EXIT_NET_ERROR;
        }
        serviceContext->setTransportLayer(std::move(tl));
    }

    // Set up the periodic runner for background job execution. This is required to be running
    // before the storage engine is initialized.
    auto runner = makePeriodicRunner(serviceContext);
    runner->startup();
    serviceContext->setPeriodicRunner(std::move(runner));

    initializeStorageEngine(serviceContext, StorageEngineInitFlags::kNone);

#ifdef MONGO_CONFIG_WIREDTIGER_ENABLED
    if (EncryptionHooks::get(serviceContext)->restartRequired()) {
        exitCleanly(EXIT_CLEAN);
    }
#endif

    // Warn if we detect configurations for multiple registered storage engines in the same
    // configuration file/environment.
    if (serverGlobalParams.parsedOpts.hasField("storage")) {
        BSONElement storageElement = serverGlobalParams.parsedOpts.getField("storage");
        invariant(storageElement.isABSONObj());
        for (auto&& e : storageElement.Obj()) {
            // Ignore if field name under "storage" matches current storage engine.
            if (storageGlobalParams.engine == e.fieldName()) {
                continue;
            }

            // Warn if field name matches non-active registered storage engine.
            if (isRegisteredStorageEngine(serviceContext, e.fieldName())) {
                warning() << "Detected configuration for non-active storage engine "
                          << e.fieldName() << " when current storage engine is "
                          << storageGlobalParams.engine;
            }
        }
    }

    // Disallow running a storage engine that doesn't support capped collections with --profile
    if (!serviceContext->getStorageEngine()->supportsCappedCollections() &&
        serverGlobalParams.defaultProfile != 0) {
        log() << "Running " << storageGlobalParams.engine << " with profiling is not supported. "
              << "Make sure you are not using --profile.";
        exitCleanly(EXIT_BADOPTIONS);
    }

    // Disallow running WiredTiger with --nojournal in a replica set
    if (storageGlobalParams.engine == "wiredTiger" && !storageGlobalParams.dur &&
        replSettings.usingReplSets()) {
        log() << "Running wiredTiger without journaling in a replica set is not "
              << "supported. Make sure you are not using --nojournal and that "
              << "storage.journal.enabled is not set to 'false'.";
        exitCleanly(EXIT_BADOPTIONS);
    }

    logMongodStartupWarnings(storageGlobalParams, serverGlobalParams, serviceContext);

#ifdef MONGO_CONFIG_SSL
    if (sslGlobalParams.sslAllowInvalidCertificates &&
        ((serverGlobalParams.clusterAuthMode.load() == ServerGlobalParams::ClusterAuthMode_x509) ||
         sequenceContains(saslGlobalParams.authenticationMechanisms, "MONGODB-X509"))) {
        log() << "** WARNING: While invalid X509 certificates may be used to" << startupWarningsLog;
        log() << "**          connect to this server, they will not be considered"
              << startupWarningsLog;
        log() << "**          permissible for authentication." << startupWarningsLog;
        log() << startupWarningsLog;
    }
#endif

    {
        std::stringstream ss;
        ss << endl;
        ss << "*********************************************************************" << endl;
        ss << " ERROR: dbpath (" << storageGlobalParams.dbpath << ") does not exist." << endl;
        ss << " Create this directory or give existing directory in --dbpath." << endl;
        ss << " See http://dochub.mongodb.org/core/startingandstoppingmongo" << endl;
        ss << "*********************************************************************" << endl;
        uassert(10296, ss.str().c_str(), boost::filesystem::exists(storageGlobalParams.dbpath));
    }

    initializeSNMP();

    if (!storageGlobalParams.readOnly) {
        boost::filesystem::remove_all(storageGlobalParams.dbpath + "/_tmp/");
    }

    if (mongodGlobalParams.scriptingEnabled) {
        ScriptEngine::setup();
    }

    auto startupOpCtx = serviceContext->makeOperationContext(&cc());

    bool canCallFCVSetIfCleanStartup =
        !storageGlobalParams.readOnly && (storageGlobalParams.engine != "devnull");
    if (canCallFCVSetIfCleanStartup && !replSettings.usingReplSets()) {
        Lock::GlobalWrite lk(startupOpCtx.get());
        FeatureCompatibilityVersion::setIfCleanStartup(startupOpCtx.get(),
                                                       repl::StorageInterface::get(serviceContext));
    }

    auto swNonLocalDatabases = repairDatabasesAndCheckVersion(startupOpCtx.get());
    if (!swNonLocalDatabases.isOK()) {
        // SERVER-31611 introduced a return value to `repairDatabasesAndCheckVersion`. Previously,
        // a failing condition would fassert. SERVER-31611 covers a case where the binary (3.6) is
        // refusing to start up because it refuses acknowledgement of FCV 3.2 and requires the
        // user to start up with an older binary. Thus shutting down the server must leave the
        // datafiles in a state that the older binary can start up. This requires going through a
        // clean shutdown.
        //
        // The invariant is *not* a statement that `repairDatabasesAndCheckVersion` must return
        // `MustDowngrade`. Instead, it is meant as a guardrail to protect future developers from
        // accidentally buying into this behavior. New errors that are returned from the method
        // may or may not want to go through a clean shutdown, and they likely won't want the
        // program to return an exit code of `EXIT_NEED_DOWNGRADE`.
        severe(LogComponent::kControl) << "** IMPORTANT: "
                                       << swNonLocalDatabases.getStatus().reason();
        invariant(swNonLocalDatabases == ErrorCodes::MustDowngrade);
        exitCleanly(EXIT_NEED_DOWNGRADE);
    }

    // Assert that the in-memory featureCompatibilityVersion parameter has been explicitly set. If
    // we are part of a replica set and are started up with no data files, we do not set the
    // featureCompatibilityVersion until a primary is chosen. For this case, we expect the in-memory
    // featureCompatibilityVersion parameter to still be uninitialized until after startup.
    if (canCallFCVSetIfCleanStartup &&
        (!replSettings.usingReplSets() || swNonLocalDatabases.getValue())) {
        invariant(serverGlobalParams.featureCompatibility.isVersionInitialized());
    }

    if (storageGlobalParams.upgrade) {
        log() << "finished checking dbs";
        exitCleanly(EXIT_CLEAN);
    }

    // Start up health log writer thread.
    HealthLog::get(startupOpCtx.get()).startup();

    auto const globalAuthzManager = AuthorizationManager::get(serviceContext);
    uassertStatusOK(globalAuthzManager->initialize(startupOpCtx.get()));

    // This is for security on certain platforms (nonce generation)
    srand((unsigned)(curTimeMicros64()) ^ (unsigned(uintptr_t(&startupOpCtx))));

    if (globalAuthzManager->shouldValidateAuthSchemaOnStartup()) {
        Status status = verifySystemIndexes(startupOpCtx.get());
        if (!status.isOK()) {
            log() << redact(status);
            if (status == ErrorCodes::AuthSchemaIncompatible) {
                exitCleanly(EXIT_NEED_UPGRADE);
            } else if (status == ErrorCodes::NotMaster) {
                // Try creating the indexes if we become master.  If we do not become master,
                // the master will create the indexes and we will replicate them.
            } else {
                quickExit(EXIT_FAILURE);
            }
        }

        // SERVER-14090: Verify that auth schema version is schemaVersion26Final.
        int foundSchemaVersion;
        status =
            globalAuthzManager->getAuthorizationVersion(startupOpCtx.get(), &foundSchemaVersion);
        if (!status.isOK()) {
            log() << "Auth schema version is incompatible: "
                  << "User and role management commands require auth data to have "
                  << "at least schema version " << AuthorizationManager::schemaVersion26Final
                  << " but startup could not verify schema version: " << status;
            log() << "To manually repair the 'authSchema' document in the admin.system.version "
                     "collection, start up with --setParameter "
                     "startupAuthSchemaValidation=false to disable validation.";
            exitCleanly(EXIT_NEED_UPGRADE);
        }

        if (foundSchemaVersion <= AuthorizationManager::schemaVersion26Final) {
            log() << "This server is using MONGODB-CR, an authentication mechanism which "
                  << "has been removed from MongoDB 4.0. In order to upgrade the auth schema, "
                  << "first downgrade MongoDB binaries to version 3.6 and then run the "
                  << "authSchemaUpgrade command. "
                  << "See http://dochub.mongodb.org/core/3.0-upgrade-to-scram-sha-1";
            exitCleanly(EXIT_NEED_UPGRADE);
        }
    } else if (globalAuthzManager->isAuthEnabled()) {
        error() << "Auth must be disabled when starting without auth schema validation";
        exitCleanly(EXIT_BADOPTIONS);
    } else {
        // If authSchemaValidation is disabled and server is running without auth,
        // warn the user and continue startup without authSchema metadata checks.
        log() << startupWarningsLog;
        log() << "** WARNING: Startup auth schema validation checks are disabled for the "
                 "database."
              << startupWarningsLog;
        log() << "**          This mode should only be used to manually repair corrupted auth "
                 "data."
              << startupWarningsLog;
    }

    // This function may take the global lock.
    auto shardingInitialized = ShardingInitializationMongoD::get(startupOpCtx.get())
                                   ->initializeShardingAwarenessIfNeeded(startupOpCtx.get());
    if (shardingInitialized) {
        waitForShardRegistryReload(startupOpCtx.get()).transitional_ignore();
    }

    auto storageEngine = serviceContext->getStorageEngine();
    invariant(storageEngine);
    BackupCursorHooks::initialize(serviceContext, storageEngine);

    if (!storageGlobalParams.readOnly) {

        if (storageEngine->supportsCappedCollections()) {
            logStartup(startupOpCtx.get());
        }

        startMongoDFTDC();

        startFreeMonitoring(serviceContext);

        restartInProgressIndexesFromLastShutdown(startupOpCtx.get());

        if (serverGlobalParams.clusterRole == ClusterRole::ShardServer) {
            // Note: For replica sets, ShardingStateRecovery happens on transition to primary.
            if (!repl::ReplicationCoordinator::get(startupOpCtx.get())->isReplEnabled()) {
                if (ShardingState::get(startupOpCtx.get())->enabled()) {
                    uassertStatusOK(ShardingStateRecovery::recover(startupOpCtx.get()));
                }
            }
        } else if (serverGlobalParams.clusterRole == ClusterRole::ConfigServer) {
            initializeGlobalShardingStateForMongoD(startupOpCtx.get(),
                                                   ConnectionString::forLocal(),
                                                   kDistLockProcessIdForConfigServer);

            Balancer::create(startupOpCtx->getServiceContext());

            ShardingCatalogManager::create(
                startupOpCtx->getServiceContext(),
                makeShardingTaskExecutor(executor::makeNetworkInterface("AddShard-TaskExecutor")));

            Grid::get(startupOpCtx.get())->setShardingInitialized();
        } else if (replSettings.usingReplSets()) {  // standalone replica set
            auto keysCollectionClient = stdx::make_unique<KeysCollectionClientDirect>();
            auto keyManager = std::make_shared<KeysCollectionManager>(
                KeysCollectionManager::kKeyManagerPurposeString,
                std::move(keysCollectionClient),
                Seconds(KeysRotationIntervalSec));
            keyManager->startMonitoring(startupOpCtx->getServiceContext());

            LogicalTimeValidator::set(startupOpCtx->getServiceContext(),
                                      stdx::make_unique<LogicalTimeValidator>(keyManager));
        }

        repl::ReplicationCoordinator::get(startupOpCtx.get())->startup(startupOpCtx.get());
        const unsigned long long missingRepl =
            checkIfReplMissingFromCommandLine(startupOpCtx.get());
        if (missingRepl) {
            log() << startupWarningsLog;
            log() << "** WARNING: mongod started without --replSet yet " << missingRepl
                  << " documents are present in local.system.replset." << startupWarningsLog;
            log() << "**          Database contents may appear inconsistent with the oplog and may "
                     "appear to not contain"
                  << startupWarningsLog;
            log() << "**          writes that were visible when this node was running as part of a "
                     "replica set."
                  << startupWarningsLog;
            log() << "**          Restart with --replSet unless you are doing maintenance and no "
                     "other clients are connected."
                  << startupWarningsLog;
            log() << "**          The TTL collection monitor will not start because of this."
                  << startupWarningsLog;
            log() << "**         ";
            log() << " For more info see http://dochub.mongodb.org/core/ttlcollections";
            log() << startupWarningsLog;
        } else {
            startTTLBackgroundJob();
        }

        if (replSettings.usingReplSets() || !internalValidateFeaturesAsMaster) {
            serverGlobalParams.validateFeaturesAsMaster.store(false);
        }
    }

    startClientCursorMonitor();

    PeriodicTask::startRunningPeriodicTasks();

    SessionKiller::set(serviceContext,
                       std::make_shared<SessionKiller>(serviceContext, killSessionsLocal));

    // Start up a background task to periodically check for and kill expired transactions; and a
    // background task to periodically check for and decrease cache pressure by decreasing the
    // target size setting for the storage engine's window of available snapshots.
    //
    // Only do this on storage engines supporting snapshot reads, which hold resources we wish to
    // release periodically in order to avoid storage cache pressure build up.
    if (storageEngine->supportsReadConcernSnapshot()) {
        startPeriodicThreadToAbortExpiredTransactions(serviceContext);
        startPeriodicThreadToDecreaseSnapshotHistoryCachePressure(serviceContext);
    }

    // Set up the logical session cache
    LogicalSessionCacheServer kind = LogicalSessionCacheServer::kStandalone;
    if (serverGlobalParams.clusterRole == ClusterRole::ShardServer) {
        kind = LogicalSessionCacheServer::kSharded;
    } else if (serverGlobalParams.clusterRole == ClusterRole::ConfigServer) {
        kind = LogicalSessionCacheServer::kConfigServer;
    } else if (replSettings.usingReplSets()) {
        kind = LogicalSessionCacheServer::kReplicaSet;
    }

    auto sessionCache = makeLogicalSessionCacheD(kind);
    LogicalSessionCache::set(serviceContext, std::move(sessionCache));

    // MessageServer::run will return when exit code closes its socket and we don't need the
    // operation context anymore
    startupOpCtx.reset();

    auto start = serviceContext->getServiceExecutor()->start();
    if (!start.isOK()) {
        error() << "Failed to start the service executor: " << start;
        return EXIT_NET_ERROR;
    }

    start = serviceContext->getServiceEntryPoint()->start();
    if (!start.isOK()) {
        error() << "Failed to start the service entry point: " << start;
        return EXIT_NET_ERROR;
    }

    if (!storageGlobalParams.repair) {
        start = serviceContext->getTransportLayer()->start();
        if (!start.isOK()) {
            error() << "Failed to start the listener: " << start.toString();
            return EXIT_NET_ERROR;
        }
    }

    serviceContext->notifyStartupComplete();

#ifndef _WIN32
    mongo::signalForkSuccess();
#else
    if (ntservice::shouldStartService()) {
        ntservice::reportStatus(SERVICE_RUNNING);
        log() << "Service running";
    }
#endif

    if (MONGO_FAIL_POINT(shutdownAtStartup)) {
        log() << "starting clean exit via failpoint";
        exitCleanly(EXIT_CLEAN);
    }

    MONGO_IDLE_THREAD_BLOCK;
    return waitForShutdown();
}
Esempio n. 20
0
void
ClusterMgr::threadMain()
{
    startup();

    NdbApiSignal signal(numberToRef(API_CLUSTERMGR, theFacade.ownId()));

    signal.theVerId_signalNumber   = GSN_API_REGREQ;
    signal.theTrace                = 0;
    signal.theLength               = ApiRegReq::SignalLength;

    ApiRegReq * req = CAST_PTR(ApiRegReq, signal.getDataPtrSend());
    req->ref = numberToRef(API_CLUSTERMGR, theFacade.ownId());
    req->version = NDB_VERSION;
    req->mysql_version = NDB_MYSQL_VERSION_D;

    NdbApiSignal nodeFail_signal(numberToRef(API_CLUSTERMGR, getOwnNodeId()));
    nodeFail_signal.theVerId_signalNumber = GSN_NODE_FAILREP;
    nodeFail_signal.theReceiversBlockNumber = API_CLUSTERMGR;
    nodeFail_signal.theTrace  = 0;
    nodeFail_signal.theLength = NodeFailRep::SignalLengthLong;

    NDB_TICKS now = NdbTick_getCurrentTicks();

    while(!theStop)
    {
        /* Sleep 1/5 of minHeartBeatInterval between each check */
        const NDB_TICKS before = now;
        for (Uint32 i = 0; i<5; i++)
        {
            NdbSleep_MilliSleep(minHeartBeatInterval/5);
            {
                /**
                 * start_poll does lock the trp_client and complete_poll
                 * releases this lock. This means that this protects
                 * against concurrent calls to send signals in ArbitMgr.
                 * We do however need to protect also against concurrent
                 * close in doStop, so to avoid this problem we need to
                 * also lock clusterMgrThreadMutex before we start the
                 * poll.
                 */
                Guard g(clusterMgrThreadMutex);
                start_poll();
                do_poll(0);
                complete_poll();
            }
        }
        now = NdbTick_getCurrentTicks();
        const Uint32 timeSlept = (Uint32)NdbTick_Elapsed(before, now).milliSec();

        lock();
        if (m_cluster_state == CS_waiting_for_clean_cache &&
                theFacade.m_globalDictCache)
        {
            if (!global_flag_skip_waiting_for_clean_cache)
            {
                theFacade.m_globalDictCache->lock();
                unsigned sz= theFacade.m_globalDictCache->get_size();
                theFacade.m_globalDictCache->unlock();
                if (sz)
                {
                    unlock();
                    continue;
                }
            }
            m_cluster_state = CS_waiting_for_first_connect;
        }

        NodeFailRep * nodeFailRep = CAST_PTR(NodeFailRep,
                                             nodeFail_signal.getDataPtrSend());
        nodeFailRep->noOfNodes = 0;
        NodeBitmask::clear(nodeFailRep->theAllNodes);

        for (int i = 1; i < MAX_NODES; i++)
        {
            /**
             * Send register request (heartbeat) to all available nodes
             * at specified timing intervals
             */
            const NodeId nodeId = i;
            // Check array bounds + don't allow node 0 to be touched
            assert(nodeId > 0 && nodeId < MAX_NODES);
            Node & cm_node = theNodes[nodeId];
            trp_node & theNode = cm_node;

            if (!theNode.defined)
                continue;

            if (theNode.is_connected() == false) {
                theFacade.doConnect(nodeId);
                continue;
            }

            if (!theNode.compatible) {
                continue;
            }

            if (nodeId == getOwnNodeId())
            {
                /**
                 * Don't send HB to self more than once
                 * (once needed to avoid weird special cases in e.g ConfigManager)
                 */
                if (m_sent_API_REGREQ_to_myself)
                {
                    continue;
                }
            }

            cm_node.hbCounter += timeSlept;
            if (cm_node.hbCounter >= m_max_api_reg_req_interval ||
                    cm_node.hbCounter >= cm_node.hbFrequency)
            {
                /**
                 * It is now time to send a new Heartbeat
                 */
                if (cm_node.hbCounter >= cm_node.hbFrequency)
                {
                    cm_node.hbMissed++;
                    cm_node.hbCounter = 0;
                }

                if (theNode.m_info.m_type != NodeInfo::DB)
                    signal.theReceiversBlockNumber = API_CLUSTERMGR;
                else
                    signal.theReceiversBlockNumber = QMGR;

#ifdef DEBUG_REG
                ndbout_c("ClusterMgr: Sending API_REGREQ to node %d", (int)nodeId);
#endif
                if (nodeId == getOwnNodeId())
                {
                    /* Set flag to ensure we only send once to ourself */
                    m_sent_API_REGREQ_to_myself = true;
                }
                raw_sendSignal(&signal, nodeId);
            }//if

            if (cm_node.hbMissed == 4 && cm_node.hbFrequency > 0)
            {
                nodeFailRep->noOfNodes++;
                NodeBitmask::set(nodeFailRep->theAllNodes, nodeId);
            }
        }
        flush_send_buffers();
        unlock();

        if (nodeFailRep->noOfNodes)
        {
            lock();
            raw_sendSignal(&nodeFail_signal, getOwnNodeId());
            flush_send_buffers();
            unlock();
        }
    }
}
Esempio n. 21
0
 //! Startup with given thread nums.
 void startup(size_t thread_num)
 {
   startup(thread_num, logger_ptr(), 0, true);
 }
Esempio n. 22
0
File: init.c Progetto: Ga-vin/MINIX3
int main(void)
{
  pid_t pid;			/* pid of child process */
  int fd;			/* generally useful */
  int linenr;			/* loop variable */
  int check;			/* check if a new process must be spawned */
  int sn;			/* signal number */
  struct slotent *slotp;	/* slots[] pointer */
  struct ttyent *ttyp;		/* ttytab entry */
  struct sigaction sa;
  struct stat stb;

#define OPENFDS						\
  if (fstat(0, &stb) < 0) {				\
	/* Open standard input, output & error. */	\
	(void) open("/dev/null", O_RDONLY);		\
	(void) open("/dev/log", O_WRONLY);		\
	dup(1);						\
  }

  sigemptyset(&sa.sa_mask);
  sa.sa_flags = 0;

  /* Default: Ignore every signal (except those that follow). */
  sa.sa_handler = SIG_IGN;
  for (sn = 1; sn < _NSIG; sn++) {
      sigaction(sn, &sa, NULL);
  }

  /* Hangup: Reexamine /etc/ttytab for newly enabled terminal lines. */
  sa.sa_handler = onhup;
  sigaction(SIGHUP, &sa, NULL);

  /* Terminate: Stop spawning login processes, shutdown is near. */
  sa.sa_handler = onterm;
  sigaction(SIGTERM, &sa, NULL);

  /* Abort: Sent by the kernel on CTRL-ALT-DEL; shut the system down. */
  sa.sa_handler = onabrt;
  sigaction(SIGABRT, &sa, NULL);

  /* Execute the /etc/rc file. */
  if ((pid = fork()) != 0) {
	/* Parent just waits. */
	while (wait(NULL) != pid) {
		if (gotabrt) reboot(RBT_HALT);
	}
  } else {
#if ! SYS_GETKENV
	struct sysgetenv sysgetenv;
#endif
	char bootopts[16];
	static char *rc_command[] = { "sh", "/etc/rc", NULL, NULL, NULL };
	char **rcp = rc_command + 2;

	/* Get the boot options from the boot environment. */
	sysgetenv.key = "bootopts";
	sysgetenv.keylen = 8+1;
	sysgetenv.val = bootopts;
	sysgetenv.vallen = sizeof(bootopts);
	if (svrctl(PMGETPARAM, &sysgetenv) == 0) *rcp++ = bootopts;
	*rcp = "start";

	execute(rc_command);
	report(2, "sh /etc/rc");
	_exit(1);	/* impossible, we hope */
  }

  OPENFDS;

  /* Clear /etc/utmp if it exists. */
  if ((fd = open(PATH_UTMP, O_WRONLY | O_TRUNC)) >= 0) close(fd);

  /* Log system reboot. */
  wtmp(BOOT_TIME, 0, NULL, 0);

  /* Main loop. If login processes have already been started up, wait for one
   * to terminate, or for a HUP signal to arrive. Start up new login processes
   * for all ttys which don't have them. Note that wait() also returns when
   * somebody's orphan dies, in which case ignore it.  If the TERM signal is
   * sent then stop spawning processes, shutdown time is near.
   */

  check = 1;
  while (1) {
	while ((pid = waitpid(-1, NULL, check ? WNOHANG : 0)) > 0) {
		/* Search to see which line terminated. */
		for (linenr = 0; linenr < PIDSLOTS; linenr++) {
			slotp = &slots[linenr];
			if (slotp->pid == pid) {
				/* Record process exiting. */
				wtmp(DEAD_PROCESS, linenr, NULL, pid);
				slotp->pid = NO_PID;
				check = 1;
			}
		}
	}

	/* If a signal 1 (SIGHUP) is received, simply reset error counts. */
	if (gothup) {
		gothup = 0;
		for (linenr = 0; linenr < PIDSLOTS; linenr++) {
			slots[linenr].errct = 0;
		}
		check = 1;
	}

	/* Shut down on signal 6 (SIGABRT). */
	if (gotabrt) {
		gotabrt = 0;
		startup(0, &TT_REBOOT);
	}

	if (spawn && check) {
		/* See which lines need a login process started up. */
		for (linenr = 0; linenr < PIDSLOTS; linenr++) {
			slotp = &slots[linenr];
			if ((ttyp = getttyent()) == NULL) break;

			if (ttyp->ty_getty != NULL
				/* ty_getty is a string, and TTY_ON is
				 * the way to check for enabled ternimanls. */
				&& (ttyp->ty_status & TTY_ON)
				&& slotp->pid == NO_PID
				&& slotp->errct < ERRCT_DISABLE)
			{
				startup(linenr, ttyp);
			}
		}
		endttyent();
	}
	check = 0;
  }
}
Esempio n. 23
0
 //! Startup with given work_steal opt.
 void startup(asev::work_steal ws)
 {
   startup(std::thread::hardware_concurrency(), logger_ptr(), 0, ws);
 }
Esempio n. 24
0
void Task::updateTask(::TaskManager::TaskChanges changes) {
//	 if (m_type != TaskItem && m_type != GroupItem)
//	 return;

	if (!isValid()) {
		return;
	}

	bool needsUpdate = false;
	bool needsUpdateState = false;
	TaskFlags t_flags = m_flags;

	if (isActive()) {
		t_flags |= TaskHasFocus;
	} 
	else {
		t_flags &= ~TaskHasFocus;
	}

	if (demandsAttention()) {
		t_flags |= TaskWantsAttention;
	}
	else {
		t_flags &= ~TaskWantsAttention;
	}

	if (isMinimized()) {
		t_flags |= TaskIsMinimized;
	}
	else {
		t_flags &= ~TaskIsMinimized;
	}

	if (m_flags != t_flags) {
		needsUpdate = true;
		m_flags = t_flags;
		needsUpdateState = true;
	}

	if (changes & TaskManager::IconChanged) {
		switch (type()) {
		case StartupItem:
			if (!KIcon(startup()->icon()).isNull()) {
				m_icon = KIcon(startup()->icon());
			}
			break;
		case TaskItem:
			if (!KIcon(task()->icon()).isNull()) {
				m_icon = KIcon(task()->icon());
			}
			break;
		case GroupItem:
			if (!KIcon(group()->icon()).isNull()) {
				m_icon = KIcon(group()->icon());
			}
			break;
		case LauncherItem:
			if (!KIcon(launcherItem()->icon()).isNull()) {
				m_icon = KIcon(launcherItem()->icon());
			}
			break;
		case OtherItem:
			break;
		}
		emit updateIcon(m_icon);
		needsUpdate = true;
	}

	if (changes & (TaskManager::NameChanged | TaskManager::StateChanged)) {
		needsUpdate = true;
	}

	if (changes & (TaskManager::StateChanged | TaskManager::DesktopChanged)) {
		emit updateToolTip();
		needsUpdateState = true;
	}
	
	if (changes & (TaskManager::IconChanged | TaskManager::NameChanged)) {
		needsUpdate = true;
	}

	if (needsUpdateState) {
		emit updateState();
	}

	if (needsUpdate) {
		emit update();
	}
}
Esempio n. 25
0
int main (void) {
	
	passedCenterFlag = 0;
	
	configClock ();
	
	PORTE.DIR = 0b11000000;
	PORTF.DIR = 0b00001111;
	
	PMIC.CTRL |= PMIC_HILVLEN_bm;
	PMIC.CTRL |= PMIC_LOLVLEN_bm;
	
	TCF0.CCABUF = STARTUP_PWM;
	TCF0.CCBBUF = STARTUP_PWM;
	TCF0.CCCBUF = STARTUP_PWM;
	TCF0.CCDBUF = STARTUP_PWM;
	
	TCE0.CCABUF = STARTUP_PWM/2;
	TCE0.CCBBUF = STARTUP_PWM/2;
	TCE0.CCCBUF = STARTUP_PWM/2;
	TCE0.CCDBUF = STARTUP_PWM/2;
	
	configPWM (&TCF0, &HIRESF, 5000);
	configHalfPWMTimer (&TCE0, &HIRESE, 5000);
	
	TCF0.CNT = 0;
	TCE0.CNT = 0;
	
	configDelayTimer (&TCC0);
	
	initAdc (&ADCA);
	initAdc (&ADCB);
	
	sei();
	
	startup();
	//~ autoCommutationFlag = 1;
	// float everything
	
	//~ SET_phaseOutputsEHigh(0);
	//~ SET_phaseOutputsEHigh(0);
//~ 
	//~ SET_phaseOutputsELow(0);
	//~ SET_phaseOutputsELow(0);
//~ 
	//~ SET_phaseOutputsFHigh(0);
	//~ SET_phaseOutputsFHigh(0);
//~ 
	//~ SET_phaseOutputsFLow(0);
	//~ SET_phaseOutputsFLow(0);
	//~ 
	//~ PORTE.OUT = 0;
	//~ PORTF.OUT = 0;
	
    _delay_ms(1000);
    _delay_ms(1000);
	TCF0.CCBBUF = 1600;
	TCE0.CCBBUF = 1600/2;

	spiInit ();

	while (1) {}
}
Esempio n. 26
0
void pping_client::startup(SednaUserException& e)
{
    startup(e, false);
}
Esempio n. 27
0
File: sam.c Progetto: deadpixi/sam
int
main(int argc, char *argv[])
{
    int i, o;
    String *t;
    char *arg[argc + 1], **ap;
    int targc = 1;

    ap = &arg[argc];
    arg[0] = "samterm";
    setlocale(LC_ALL, "");

    while ((o = getopt(argc, argv, "efdRr:t:s:")) != -1) {
        switch (o) {
        case 'e':
            arg[targc++] = "-e";
            break;

        case 'f':
            arg[targc++] = "-f";
            break;

        case 'd':
            dflag = true;
            break;

        case 'r':
            machine = optarg;
            rsamname = "rsam";
            arg[targc++] = "-r";
            arg[targc++] = optarg;
            break;

        case 'R':
            Rflag = true;
            break;

        case 't':
            samterm = optarg;
            break;

        case 's':
            rsamname = optarg;
            break;

        default:
            usage();
        }
    }
    argv += optind;
    argc -= optind;
    arg[targc] = NULL;

    Strinit(&cmdstr);
    Strinit0(&lastpat);
    Strinit0(&lastregexp);
    Strinit0(&genstr);
    Strinit0(&rhs);
    Strinit0(&wd);
    Strinit0(&plan9cmd);

    tempfile.listptr = emalloc(0);
    home = getenv("HOME") ? getenv("HOME") : "/";
    shpath = getenv("SHELL") ? getenv("SHELL") : shpath;
    sh = basename(shpath);
    if(!dflag)
        startup(machine, Rflag, arg, ap);
    Fstart();

    signal(SIGINT, SIG_IGN);
    signal(SIGHUP, hup);
    signal(SIGPIPE, SIG_IGN);

    if(argc > 0) {
        for(i=0; i<argc; i++)
            if(!setjmp(mainloop)) {
                t = tmpcstr(argv[i]);
                Straddc(t, '\0');
                Strduplstr(&genstr, t);
                freetmpstr(t);
                Fsetname(newfile(), &genstr);
            }
    } else if(!downloaded)
        newfile()->state = Clean;
    modnum++;
    if(file.nused)
        current(file.filepptr[0]);

    atexit(shutdown);
    setjmp(mainloop);
    cmdloop();

    trytoquit();    /* if we already q'ed, quitok will be true */

    exit(EXIT_SUCCESS);
}
Esempio n. 28
0
void pping_client::startup(SednaUserSoftException& e)
{
    startup(e, true);
}
Esempio n. 29
0
int
main(int argc, char *argv[])
{
	time_t start;
	int ch, onerun, reps;
	const char *config, *home;

	config = NULL;

#ifdef _WIN32
	g.progname = "t_format.exe";
#else
	if ((g.progname = strrchr(argv[0], DIR_DELIM)) == NULL)
		g.progname = argv[0];
	else
		++g.progname;
#endif

#if 0
	/* Configure the GNU malloc for debugging. */
	(void)setenv("MALLOC_CHECK_", "2", 1);
#endif
#if 0
	/* Configure the FreeBSD malloc for debugging. */
	(void)setenv("MALLOC_OPTIONS", "AJ", 1);
#endif

	/* Track progress unless we're re-directing output to a file. */
	g.c_quiet = isatty(1) ? 0 : 1;

	/* Set values from the command line. */
	home = NULL;
	onerun = 0;
	while ((ch = __wt_getopt(
	    g.progname, argc, argv, "1C:c:H:h:Llqrt:")) != EOF)
		switch (ch) {
		case '1':			/* One run */
			onerun = 1;
			break;
		case 'C':			/* wiredtiger_open config */
			g.config_open = __wt_optarg;
			break;
		case 'c':			/* Configuration from a file */
			config = __wt_optarg;
			break;
		case 'H':
			g.helium_mount = __wt_optarg;
			break;
		case 'h':
			home = __wt_optarg;
			break;
		case 'L':			/* Re-direct output to a log */
			/*
			 * The -l option is a superset of -L, ignore -L if we
			 * have already configured logging for operations.
			 */
			if (g.logging == 0)
				g.logging = LOG_FILE;
			break;
		case 'l':			/* Turn on operation logging */
			g.logging = LOG_OPS;
			break;
		case 'q':			/* Quiet */
			g.c_quiet = 1;
			break;
		case 'r':			/* Replay a run */
			g.replay = 1;
			break;
		default:
			usage();
		}
	argc -= __wt_optind;
	argv += __wt_optind;

	/* Initialize the global RNG. */
	testutil_check(__wt_random_init_seed(NULL, &g.rnd));

	/* Set up paths. */
	path_setup(home);

	/* If it's a replay, use the home directory's CONFIG file. */
	if (g.replay) {
		if (config != NULL)
			testutil_die(EINVAL, "-c incompatible with -r");
		if (access(g.home_config, R_OK) != 0)
			testutil_die(ENOENT, "%s", g.home_config);
		config = g.home_config;
	}

	/*
	 * If we weren't given a configuration file, set values from "CONFIG",
	 * if it exists.
	 *
	 * Small hack to ignore any CONFIG file named ".", that just makes it
	 * possible to ignore any local CONFIG file, used when running checks.
	 */
	if (config == NULL && access("CONFIG", R_OK) == 0)
		config = "CONFIG";
	if (config != NULL && strcmp(config, ".") != 0)
		config_file(config);

	/*
	 * The rest of the arguments are individual configurations that modify
	 * the base configuration.
	 */
	for (; *argv != NULL; ++argv)
		config_single(*argv, 1);

	/*
	 * Multithreaded runs can be replayed: it's useful and we'll get the
	 * configuration correct.  Obviously the order of operations changes,
	 * warn the user.
	 */
	if (g.replay && !SINGLETHREADED)
		printf("Warning: replaying a threaded run\n");

	/*
	 * Single-threaded runs historically exited after a single replay, which
	 * makes sense when you're debugging, leave that semantic in place.
	 */
	if (g.replay && SINGLETHREADED)
		g.c_runs = 1;

	/*
	 * Let the command line -1 flag override runs configured from other
	 * sources.
	 */
	if (onerun)
		g.c_runs = 1;

	/*
	 * Initialize locks to single-thread named checkpoints and backups, last
	 * last-record updates, and failures.
	 */
	testutil_check(pthread_rwlock_init(&g.append_lock, NULL));
	testutil_check(pthread_rwlock_init(&g.backup_lock, NULL));
	testutil_check(pthread_rwlock_init(&g.checkpoint_lock, NULL));
	testutil_check(pthread_rwlock_init(&g.death_lock, NULL));

	printf("%s: process %" PRIdMAX "\n", g.progname, (intmax_t)getpid());
	while (++g.run_cnt <= g.c_runs || g.c_runs == 0 ) {
		startup();			/* Start a run */

		config_setup();			/* Run configuration */
		config_print(0);		/* Dump run configuration */
		key_len_setup();		/* Setup keys */

		start = time(NULL);
		track("starting up", 0ULL, NULL);

#ifdef HAVE_BERKELEY_DB
		if (SINGLETHREADED)
			bdb_open();		/* Initial file config */
#endif
		wts_open(g.home, true, &g.wts_conn);
		wts_init();

		wts_load();			/* Load initial records */
		wts_verify("post-bulk verify");	/* Verify */

		/*
		 * If we're not doing any operations, scan the bulk-load, copy
		 * the statistics and we're done. Otherwise, loop reading and
		 * operations, with a verify after each set.
		 */
		if (g.c_timer == 0 && g.c_ops == 0) {
			wts_read_scan();		/* Read scan */
			wts_stats();			/* Statistics */
		} else
			for (reps = 1; reps <= FORMAT_OPERATION_REPS; ++reps) {
				wts_read_scan();	/* Read scan */

							/* Operations */
				wts_ops(reps == FORMAT_OPERATION_REPS);

				/*
				 * Copy out the run's statistics after the last
				 * set of operations.
				 *
				 * XXX
				 * Verify closes the underlying handle and
				 * discards the statistics, read them first.
				 */
				if (reps == FORMAT_OPERATION_REPS)
					wts_stats();

							/* Verify */
				wts_verify("post-ops verify");
			}

		track("shutting down", 0ULL, NULL);
#ifdef HAVE_BERKELEY_DB
		if (SINGLETHREADED)
			bdb_close();
#endif
		wts_close();

		/*
		 * Rebalance testing.
		 */
		wts_rebalance();

		/*
		 * If single-threaded, we can dump and compare the WiredTiger
		 * and Berkeley DB data sets.
		 */
		if (SINGLETHREADED)
			wts_dump("standard", 1);

		/*
		 * Salvage testing.
		 */
		wts_salvage();

		/* Overwrite the progress line with a completion line. */
		if (!g.c_quiet)
			printf("\r%78s\r", " ");
		printf("%4d: %s, %s (%.0f seconds)\n",
		    g.run_cnt, g.c_data_source,
		    g.c_file_type, difftime(time(NULL), start));
		fflush(stdout);
	}

	/* Flush/close any logging information. */
	fclose_and_clear(&g.logfp);
	fclose_and_clear(&g.randfp);

	config_print(0);

	testutil_check(pthread_rwlock_destroy(&g.append_lock));
	testutil_check(pthread_rwlock_destroy(&g.backup_lock));
	testutil_check(pthread_rwlock_destroy(&g.checkpoint_lock));
	testutil_check(pthread_rwlock_destroy(&g.death_lock));

	config_clear();

	return (EXIT_SUCCESS);
}
Esempio n. 30
0
int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nShowCmd)
{
    CONTEXT("WinMain()");

    BOOL any_desktop_running = IsAnyDesktopRunning();

    BOOL startup_desktop;

    // strip extended options from the front of the command line
    String ext_options;

    while(*lpCmdLine == '-') {
        while(*lpCmdLine && !_istspace((unsigned)*lpCmdLine))
            ext_options += *lpCmdLine++;

        while(_istspace((unsigned)*lpCmdLine))
            ++lpCmdLine;
    }

     // command line option "-install" to replace previous shell application with ROS Explorer
    if (_tcsstr(ext_options,TEXT("-install"))) {
        // install ROS Explorer into the registry
        TCHAR path[MAX_PATH];

        int l = GetModuleFileName(0, path, COUNTOF(path));
        if (l) {
            HKEY hkey;

            if (!RegOpenKey(HKEY_LOCAL_MACHINE, TEXT("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon"), &hkey)) {

                ///@todo save previous shell application in config file

                RegSetValueEx(hkey, TEXT("Shell"), 0, REG_SZ, (LPBYTE)path, l*sizeof(TCHAR));
                RegCloseKey(hkey);
            }

            if (!RegOpenKey(HKEY_CURRENT_USER, TEXT("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon"), &hkey)) {

                ///@todo save previous shell application in config file

                RegSetValueEx(hkey, TEXT("Shell"), 0, REG_SZ, (LPBYTE)TEXT(""), l*sizeof(TCHAR));
                RegCloseKey(hkey);
            }
        }

        HWND shellWindow = GetShellWindow();

        if (shellWindow) {
            DWORD pid;

            // terminate shell process for NT like systems
            GetWindowThreadProcessId(shellWindow, &pid);
            HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);

             // On Win 9x it's sufficient to destroy the shell window.
            DestroyWindow(shellWindow);

            if (TerminateProcess(hProcess, 0))
                WaitForSingleObject(hProcess, INFINITE);

            CloseHandle(hProcess);
        }

        startup_desktop = TRUE;
    } else {
         // create desktop window and task bar only, if there is no other shell and we are
         // the first explorer instance
         // MS Explorer looks additionally into the registry entry HKCU\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\shell,
         // to decide wether it is currently configured as shell application.
        startup_desktop = !any_desktop_running;
    }


    bool autostart = !any_desktop_running;

    // disable autostart if the SHIFT key is pressed
    if (GetAsyncKeyState(VK_SHIFT) < 0)
        autostart = false;

#ifdef _DEBUG    //MF: disabled for debugging
    autostart = false;
#endif

    // If there is given the command line option "-desktop", create desktop window anyways
    if (_tcsstr(ext_options,TEXT("-desktop")))
        startup_desktop = TRUE;
#ifndef ROSSHELL
    else if (_tcsstr(ext_options,TEXT("-nodesktop")))
        startup_desktop = FALSE;

    // Don't display cabinet window in desktop mode
    if (startup_desktop && !_tcsstr(ext_options,TEXT("-explorer")))
        nShowCmd = SW_HIDE;
#endif

    if (_tcsstr(ext_options,TEXT("-noautostart")))
        autostart = false;
    else if (_tcsstr(ext_options,TEXT("-autostart")))
        autostart = true;

#ifndef __WINE__
    if (_tcsstr(ext_options,TEXT("-console"))) {
        AllocConsole();

        _dup2(_open_osfhandle((long)GetStdHandle(STD_INPUT_HANDLE), _O_RDONLY), 0);
        _dup2(_open_osfhandle((long)GetStdHandle(STD_OUTPUT_HANDLE), 0), 1);
        _dup2(_open_osfhandle((long)GetStdHandle(STD_ERROR_HANDLE), 0), 2);

        g_Globals._log = _fdopen(1, "w");
        setvbuf(g_Globals._log, 0, _IONBF, 0);

        LOG(TEXT("starting explorer debug log\n"));
    }
#endif


    if (startup_desktop) {
         // hide the XP login screen (Credit to Nicolas Escuder)
         // another undocumented event: "Global\\msgina: ReturnToWelcome"
        if (!SetShellReadyEvent(TEXT("msgina: ShellReadyEvent")))
            SetShellReadyEvent(TEXT("Global\\msgina: ShellReadyEvent"));
    }
#ifdef ROSSHELL
    else
        return 0;    // no shell to launch, so exit immediatelly
#endif


    if (!any_desktop_running) {
        // launch the shell DDE server
        if (g_SHDOCVW_ShellDDEInit)
            (*g_SHDOCVW_ShellDDEInit)(TRUE);
    }


    bool use_gdb_stub = false;    // !IsDebuggerPresent();

    if (_tcsstr(ext_options,TEXT("-debug")))
        use_gdb_stub = true;

    if (_tcsstr(ext_options,TEXT("-break"))) {
        LOG(TEXT("debugger breakpoint"));
        __debugbreak();
    }

#ifdef _M_IX86
    // activate GDB remote debugging stub if no other debugger is running
    if (use_gdb_stub) {
        LOG(TEXT("waiting for debugger connection...\n"));

        initialize_gdb_stub();
    }
#endif

    g_Globals.init(hInstance);

    // initialize COM and OLE before creating the desktop window
    OleInit usingCOM;

    // init common controls library
    CommonControlInit usingCmnCtrl;

    g_Globals.read_persistent();

    if (startup_desktop) {
        WaitCursor wait;

        g_Globals._desktops.init();

        g_Globals._hwndDesktop = DesktopWindow::Create();
#ifdef _USE_HDESK
        g_Globals._desktops.get_current_Desktop()->_hwndDesktop = g_Globals._hwndDesktop;
#endif
    }

    if (_tcsstr(ext_options,TEXT("-?"))) {
        MessageBoxA(g_Globals._hwndDesktop,
            "/e        open cabinet window in explorer mode\r\n"
            "/root        open cabinet window in rooted mode\r\n"
            "/mdi        open cabinet window in MDI mode\r\n"
            "/sdi        open cabinet window in SDI mode\r\n"
            "\r\n"
            "-?        display command line options\r\n"
            "\r\n"
            "-desktop        start in desktop mode regardless of an already running shell\r\n"
            "-nodesktop    disable desktop mode\r\n"
            "-explorer        display cabinet window regardless of enabled desktop mode\r\n"
            "\r\n"
            "-install        replace previous shell application with ROS Explorer\r\n"
            "\r\n"
            "-noautostart    disable autostarts\r\n"
            "-autostart    enable autostarts regardless of debug build\r\n"
            "\r\n"
            "-console        open debug console\r\n"
            "\r\n"
            "-debug        activate GDB remote debugging stub\r\n"
            "-break        activate debugger breakpoint\r\n",
            "ROS Explorer - command line options", MB_OK);
    }

    Thread* pSSOThread = NULL;

    if (startup_desktop) {
        // launch SSO thread to allow message processing independent from the explorer main thread
        pSSOThread = new SSOThread;
        pSSOThread->Start();
    }

    /**TODO launching autostart programs can be moved into a background thread. */
    if (autostart) {
        const char* argv[] = {"", "s"};    // call startup routine in SESSION_START mode
        startup(2, argv);
    }

#ifndef ROSSHELL
    if (g_Globals._hwndDesktop)
        g_Globals._desktop_mode = true;
#endif


    int ret = explorer_main(hInstance, lpCmdLine, nShowCmd);


    // write configuration file
    g_Globals.write_persistent();

    if (pSSOThread) {
        pSSOThread->Stop();
        delete pSSOThread;
    }

    if (!any_desktop_running) {
        // shutdown the shell DDE server
        if (g_SHDOCVW_ShellDDEInit)
            (*g_SHDOCVW_ShellDDEInit)(FALSE);
    }

    return ret;
}