예제 #1
0
int main(int argc, char **argv) {
    int r;

    setlocale(LC_ALL, "");

    parse_opts(argc, argv);

    aug = aug_init(root, loadpath, flags|AUG_NO_ERR_CLOSE);
    if (aug == NULL || aug_error(aug) != AUG_NOERROR) {
        fprintf(stderr, "Failed to initialize Augeas\n");
        if (aug != NULL)
            print_aug_error();
        exit(EXIT_FAILURE);
    }
    add_transforms(transforms, transformslen);
    if (print_version) {
        print_version_info();
        return EXIT_SUCCESS;
    }
    readline_init();
    if (optind < argc) {
        // Accept one command from the command line
        r = run_args(argc - optind, argv+optind);
    } else {
        r = main_loop();
    }
    if (history_file != NULL)
        write_history(history_file);

    return r == 0 ? EXIT_SUCCESS : EXIT_FAILURE;
}
예제 #2
0
파일: cli_infos.c 프로젝트: chrippa/xmms2
cli_infos_t *
cli_infos_init (gint argc, gchar **argv)
{
	cli_infos_t *infos;
	alias_define_t *aliaslist;
	gchar *filename;
	gint i;

	infos = g_new0 (cli_infos_t, 1);

	/* readline_init needs PROMPT */
	filename = configuration_get_filename ();
	infos->config = configuration_init (filename);
	g_free (filename);

	readline_init (infos);

	if (argc == 0) {
		infos->mode = CLI_EXECUTION_MODE_SHELL;
		/* print welcome message before initialising readline */
		if (configuration_get_boolean (infos->config, "SHELL_START_MESSAGE")) {
			g_printf (_("Welcome to the XMMS2 CLI shell!\n"));
			g_printf (_("Type 'help' to list the available commands "
			            "and 'exit' (or CTRL-D) to leave the shell.\n"));
		}
		readline_resume (infos);
	} else {
		infos->mode = CLI_EXECUTION_MODE_INLINE;
	}

	infos->status = CLI_ACTION_STATUS_READY;
	infos->commands = command_trie_alloc ();

	/* Register commands and command names */
	for (i = 0; commandlist[i]; ++i) {
		command_action_t *action = command_action_alloc ();
		commandlist[i] (action);
		if (!register_command (infos->commands, &infos->cmdnames, action)) {
			command_action_free (action);
		}
	}

	/* Register aliases with a default callback */
	aliaslist = alias_list (configuration_get_aliases (infos->config));
	for (i = 0; aliaslist[i].name; ++i) {
		command_action_t *action = command_action_alloc ();
		alias_setup (action, &aliaslist[i]);
		if (!register_command (infos->commands, &infos->aliasnames, action)) {
			command_action_free (action);
		}
	}
	alias_list_free (aliaslist);

	infos->alias_count = 0;
	infos->aliasnames = cmdnames_reverse (infos->aliasnames);
	infos->cmdnames = cmdnames_reverse (infos->cmdnames);
	infos->cache = cli_cache_init ();

	return infos;
}
예제 #3
0
void pyexec_event_repl_init(void) {
    MP_STATE_VM(repl_line) = vstr_new(32);
    repl.cont_line = false;
    readline_init(MP_STATE_VM(repl_line), ">>> ");
    if (pyexec_mode_kind == PYEXEC_MODE_RAW_REPL) {
        pyexec_raw_repl_process_char(CHAR_CTRL_A);
    } else {
        pyexec_friendly_repl_process_char(CHAR_CTRL_B);
    }
}
예제 #4
0
void pyexec_event_repl_init(void) {
    vstr_init(&repl.line, 32);
    repl.cont_line = false;
    readline_init(&repl.line, ">>> ");
    if (pyexec_mode_kind == PYEXEC_MODE_RAW_REPL) {
        pyexec_raw_repl_process_char(CHAR_CTRL_A);
    } else {
        pyexec_friendly_repl_process_char(CHAR_CTRL_B);
    }
}
예제 #5
0
void pyexec_event_repl_init(void) {
    MP_STATE_VM(repl_line) = vstr_new(32);
    repl.cont_line = false;
    // no prompt before printing friendly REPL banner or entering raw REPL
    readline_init(MP_STATE_VM(repl_line), "");
    if (pyexec_mode_kind == PYEXEC_MODE_RAW_REPL) {
        pyexec_raw_repl_process_char(CHAR_CTRL_A);
    } else {
        pyexec_friendly_repl_process_char(CHAR_CTRL_B);
    }
}
예제 #6
0
cli_infos_t *
cli_infos_init (gint argc, gchar **argv)
{
	cli_infos_t *infos;
	alias_define_t *aliaslist;
	gint i;

	infos = g_new0 (cli_infos_t, 1);

	/* readline_init needs PROMPT */
	infos->config = configuration_init (NULL);

	if (argc == 0) {
		infos->mode = CLI_EXECUTION_MODE_SHELL;
		readline_init (infos);
	} else {
		infos->mode = CLI_EXECUTION_MODE_INLINE;
	}

	infos->status = CLI_ACTION_STATUS_READY;
	infos->commands = command_trie_alloc ();

	/* Register commands and command names */
	for (i = 0; commandlist[i]; ++i) {
		command_action_t *action = command_action_alloc ();
		commandlist[i] (action);
		if (!register_command (infos->commands, &infos->cmdnames, action)) {
			command_action_free (action);
		}
	}

	/* Register aliases with a default callback */
	aliaslist = alias_list (configuration_get_aliases (infos->config));
	for (i = 0; aliaslist[i].name; ++i) {
		command_action_t *action = command_action_alloc ();
		alias_setup (action, &aliaslist[i]);
		if (!register_command (infos->commands, &infos->aliasnames, action)) {
			command_action_free (action);
		}
	}
	alias_list_free (aliaslist);

	infos->alias_count = 0;
	infos->aliasnames = cmdnames_reverse (infos->aliasnames);
	infos->cmdnames = cmdnames_reverse (infos->cmdnames);
	infos->cache = cli_cache_init ();

	return infos;
}
예제 #7
0
cli_context_t *
cli_context_init (void)
{
	cli_context_t *ctx;
	alias_define_t *aliaslist;
	gchar *filename;
	gint i;

	ctx = g_new0 (cli_context_t, 1);

	/* readline_init needs PROMPT */
	filename = configuration_get_filename ();
	ctx->config = configuration_init (filename);
	g_free (filename);

	readline_init (ctx);

	ctx->status = CLI_ACTION_STATUS_READY;
	ctx->commands = command_trie_alloc ();

	/* Register commands and command names */
	for (i = 0; commandlist[i]; ++i) {
		command_action_t *action = command_action_alloc ();
		commandlist[i] (action);
		if (!register_command (ctx->commands, &ctx->cmdnames, action)) {
			command_action_free (action);
		}
	}

	/* Register aliases with a default callback */
	aliaslist = alias_list (configuration_get_aliases (ctx->config));
	for (i = 0; aliaslist[i].name; ++i) {
		command_action_t *action = command_action_alloc ();
		alias_setup (action, &aliaslist[i]);
		if (!register_command (ctx->commands, &ctx->aliasnames, action)) {
			command_action_free (action);
		}
	}
	alias_list_free (aliaslist);

	ctx->alias_count = 0;
	ctx->aliasnames = cmdnames_reverse (ctx->aliasnames);
	ctx->cmdnames = cmdnames_reverse (ctx->cmdnames);
	ctx->cache = cli_cache_init ();

	return ctx;
}
예제 #8
0
int main(int argc, char **argv)
{
    poptContext optCon = rpmioInit(argc, argv, optionsTable);
    const char ** av = NULL;
    int ac;
    int r = -1;

_rpmaug_debug = -1;
    if (_rpmaugLoadargv != NULL)
	_rpmaugLoadpath = argvJoin(_rpmaugLoadargv, PATH_SEP_CHAR);

    _rpmaugI = rpmaugNew(_rpmaugRoot, _rpmaugLoadpath, _rpmaugFlags);
    if (_rpmaugI == NULL) {
        fprintf(stderr, "Failed to initialize Augeas\n");
	goto exit;
    }

#if defined(WITH_READLINE)
    readline_init();
#endif

    av = poptGetArgs(optCon);
    ac = argvCount(av);
    if (ac > 0) {	// Accept one command from the command line
	const char * cmd = argvJoin(av, ' ');
	const char *buf;

	buf = NULL;
        r = rpmaugRun(NULL, cmd, &buf);
	cmd = _free(cmd);
	if (buf && *buf)
	    fprintf(stdout, "%s", buf);
    } else {
        r = main_loop();
    }

exit:
    if (_rpmaugLoadargv)
	_rpmaugLoadpath = _free(_rpmaugLoadpath);
    _rpmaugLoadargv = argvFree(_rpmaugLoadargv);
    _rpmaugI = rpmaugFree(_rpmaugI);

    optCon = rpmioFini(optCon);

    return (r == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
}
예제 #9
0
int main(int argc, char *argv[]) {
	char* s, *line;
	
	readline_init();
	printf("enter `?' for help.\n");
	
	while (!done) {
		line = readline(prompt());
		if (!line) break;
		
		s = strtrim(line);
		if (*s) {
			add_history(s);
			execute_line(s);
		}
		free(line);
	}
	return 0;
}
예제 #10
0
/* start a cli with <name> as a prompt, and optionally run the <initscript> file */
void
enter_cli(const char *name, const char *initscript)
{
	global_logfp = NULL;
	//progname = name;	//we use the supplied *name instead.

	readline_init();
	set_init();

	if (initscript != NULL) {
		int rv=command_file(initscript);
		switch (rv) {
			case CMD_OK:
				/* script was succesful, start a normal CLI afterwards */
				break;
			case CMD_FAILED:
				printf("Problem with file %s\n", initscript);
				// fallthrough, yes
			default:
			case CMD_EXIT:
				set_close();
				return;
		}
	} else {
		/* print banner only if running without an initscript */
		printf("%s: %s version %s\n", name, projname, PACKAGE_VERSION);
		printf("%s: Type HELP for a list of commands\n", name);
		printf("%s: Type SCAN to start ODBII Scan\n", name);
		printf("%s: Then use MONITOR to monitor real-time data\n", name);
		printf("%s: **** IMPORTANT : this is beta software ! Use at your own risk.\n", name);
		printf("%s: **** Remember, \"debug all -1\" displays all debugging info.\n", name);
	}

	if (rc_file() != CMD_EXIT) {
		printf("\n");
		/* And go start CLI */
		instream = stdin;
		(void)do_cli(root_cmd_table, name, 0, NULL);
	}
	set_close();

}
예제 #11
0
int main(int argc, char **argv)
{
	struct rls *rls;
	char *p;
	int i;
	
	rls = readline_init(5, 1024);
	readline_tab(my_complete, rls);
	while (rls) {
		p = readline("CLI> ", rls);
		if (p != NULL)
			printf("\nget %s\n", p);
		if (!strcmp(p, "h")) {
			printf("\n");
			for (i = 0; i < rls->hist_total; i++)
				printf("%d: %s\n", i + 1, rls->history[i]);
		}	
		if (strcmp(p, "quit"))
			continue;
		break;
	}
	return 1;
}
예제 #12
0
STATIC int pyexec_friendly_repl_process_char(int c) {
    int ret = readline_process_char(c);

    if (!repl.cont_line) {

        if (ret == CHAR_CTRL_A) {
            // change to raw REPL
            pyexec_mode_kind = PYEXEC_MODE_RAW_REPL;
            mp_hal_stdout_tx_str("\r\n");
            pyexec_raw_repl_process_char(CHAR_CTRL_A);
            return 0;
        } else if (ret == CHAR_CTRL_B) {
            // reset friendly REPL
            mp_hal_stdout_tx_str("\r\n");
            mp_hal_stdout_tx_str("MicroPython " MICROPY_GIT_TAG " on " MICROPY_BUILD_DATE "; " MICROPY_HW_BOARD_NAME " with " MICROPY_HW_MCU_NAME "\r\n");
            #if MICROPY_PY_BUILTINS_HELP
            mp_hal_stdout_tx_str("Type \"help()\" for more information.\r\n");
            #endif
            goto input_restart;
        } else if (ret == CHAR_CTRL_C) {
            // break
            mp_hal_stdout_tx_str("\r\n");
            goto input_restart;
        } else if (ret == CHAR_CTRL_D) {
            // exit for a soft reset
            mp_hal_stdout_tx_str("\r\n");
            vstr_clear(MP_STATE_VM(repl_line));
            return PYEXEC_FORCED_EXIT;
        }

        if (ret < 0) {
            return 0;
        }

        if (!mp_repl_continue_with_input(vstr_null_terminated_str(MP_STATE_VM(repl_line)))) {
            goto exec;
        }

        vstr_add_byte(MP_STATE_VM(repl_line), '\n');
        repl.cont_line = true;
        readline_note_newline("... ");
        return 0;

    } else {

        if (ret == CHAR_CTRL_C) {
           // cancel everything
           mp_hal_stdout_tx_str("\r\n");
           repl.cont_line = false;
           goto input_restart;
        } else if (ret == CHAR_CTRL_D) {
            // stop entering compound statement
            goto exec;
        }

        if (ret < 0) {
            return 0;
        }

        if (mp_repl_continue_with_input(vstr_null_terminated_str(MP_STATE_VM(repl_line)))) {
            vstr_add_byte(MP_STATE_VM(repl_line), '\n');
            readline_note_newline("... ");
            return 0;
        }

exec: ;
        int ret = parse_compile_execute(MP_STATE_VM(repl_line), MP_PARSE_SINGLE_INPUT, EXEC_FLAG_ALLOW_DEBUGGING | EXEC_FLAG_IS_REPL | EXEC_FLAG_SOURCE_IS_VSTR);
        if (ret & PYEXEC_FORCED_EXIT) {
            return ret;
        }

input_restart:
        vstr_reset(MP_STATE_VM(repl_line));
        repl.cont_line = false;
        readline_init(MP_STATE_VM(repl_line), ">>> ");
        return 0;
    }
}
예제 #13
0
파일: qemu-io.c 프로젝트: Aakriti/qemu
int main(int argc, char **argv)
{
    int readonly = 0;
    int growable = 0;
    const char *sopt = "hVc:d:rsnmgkt:T:";
    const struct option lopt[] = {
        { "help", 0, NULL, 'h' },
        { "version", 0, NULL, 'V' },
        { "offset", 1, NULL, 'o' },
        { "cmd", 1, NULL, 'c' },
        { "read-only", 0, NULL, 'r' },
        { "snapshot", 0, NULL, 's' },
        { "nocache", 0, NULL, 'n' },
        { "misalign", 0, NULL, 'm' },
        { "growable", 0, NULL, 'g' },
        { "native-aio", 0, NULL, 'k' },
        { "discard", 1, NULL, 'd' },
        { "cache", 1, NULL, 't' },
        { "trace", 1, NULL, 'T' },
        { NULL, 0, NULL, 0 }
    };
    int c;
    int opt_index = 0;
    int flags = BDRV_O_UNMAP;

#ifdef CONFIG_POSIX
    signal(SIGPIPE, SIG_IGN);
#endif

    progname = basename(argv[0]);

    while ((c = getopt_long(argc, argv, sopt, lopt, &opt_index)) != -1) {
        switch (c) {
        case 's':
            flags |= BDRV_O_SNAPSHOT;
            break;
        case 'n':
            flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
            break;
        case 'd':
            if (bdrv_parse_discard_flags(optarg, &flags) < 0) {
                error_report("Invalid discard option: %s", optarg);
                exit(1);
            }
            break;
        case 'c':
            add_user_command(optarg);
            break;
        case 'r':
            readonly = 1;
            break;
        case 'm':
            qemuio_misalign = 1;
            break;
        case 'g':
            growable = 1;
            break;
        case 'k':
            flags |= BDRV_O_NATIVE_AIO;
            break;
        case 't':
            if (bdrv_parse_cache_flags(optarg, &flags) < 0) {
                error_report("Invalid cache option: %s", optarg);
                exit(1);
            }
            break;
        case 'T':
            if (!trace_backend_init(optarg, NULL)) {
                exit(1); /* error message will have been printed */
            }
            break;
        case 'V':
            printf("%s version %s\n", progname, QEMU_VERSION);
            exit(0);
        case 'h':
            usage(progname);
            exit(0);
        default:
            usage(progname);
            exit(1);
        }
    }

    if ((argc - optind) > 1) {
        usage(progname);
        exit(1);
    }

    qemu_init_main_loop();
    bdrv_init();

    /* initialize commands */
    qemuio_add_command(&quit_cmd);
    qemuio_add_command(&open_cmd);
    qemuio_add_command(&close_cmd);

    if (isatty(STDIN_FILENO)) {
        readline_state = readline_init(readline_printf_func,
                                       readline_flush_func,
                                       NULL,
                                       readline_completion_func);
        qemu_set_tty_echo(STDIN_FILENO, false);
        atexit(reenable_tty_echo);
    }

    /* open the device */
    if (!readonly) {
        flags |= BDRV_O_RDWR;
    }

    if ((argc - optind) == 1) {
        openfile(argv[optind], flags, growable, NULL);
    }
    command_loop();

    /*
     * Make sure all outstanding requests complete before the program exits.
     */
    bdrv_drain_all();

    if (qemuio_bs) {
        bdrv_unref(qemuio_bs);
    }
    g_free(readline_state);
    return 0;
}
예제 #14
0
파일: hv.c 프로젝트: dlintott/vpcs
int 
main(int argc, char **argv, char** envp)
{	
	
	if (argc == 3 && !strcmp(argv[1], "-H")) {
		hvport = atoi(argv[2]);
		if (hvport < 1024 || hvport > 65000) {
			printf("Invalid port\n");
			exit(1);
		}
		/* keep program name for vpcs */
#ifdef cygwin
		/* using windows native API to get 'real' path */
		if (GetModuleFileName(NULL, prgname, PATH_MAX) == 0) {
#else			
		if (!getpath(argv[0])) {
#endif
		    	printf("Can not get file path\n");
		    	return 1;
		}
		return hypervisor(hvport);
	}

	/* go to vpcs */
 	return vpcs(argc, argv);
}
	
int 
hypervisor(int port)
{
	struct sockaddr_in serv;
	int on = 1;
	
	setsid();
#if 1
	if (daemon(1, 1)) {
		perror("Daemonize fail");
		goto ret;
	}
#endif	

	memset(vpcs_list, 0, MAX_DAEMONS * sizeof(struct list));
	
	if (openpty(&ptyfdm, &ptyfds, NULL, NULL, NULL)) {
		perror("Create pseudo-terminal");
		goto ret;
	}

	signal(SIGCHLD, SIG_IGN);
	signal(SIGPIPE, SIG_IGN);

	fptys = fdopen(ptyfds, "w");
	
	rls = readline_init(50, 128);
	rls->fdin = ptyfds;
	rls->fdout = ptyfds;

	if ((sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) >= 0) {
		(void) setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
		    (char *)&on, sizeof(on));
		
		//fcntl(sock, F_SETFD, fcntl(sock, F_GETFD) | FD_CLOEXEC);
		
		bzero((char *) &serv, sizeof(serv));
		serv.sin_family = AF_INET;
		serv.sin_addr.s_addr = htonl(INADDR_ANY);
		serv.sin_port = htons(port);
		
		if (bind(sock, (struct sockaddr *) &serv, sizeof(serv)) < 0) {
			perror("Daemon bind port");
			goto ret;
		}
		if (listen(sock, 5) < 0) {
			perror("Daemon listen");
			goto ret;
		}
	
		loop();
		close(sock);
	}
ret:	
	if (rls)
		readline_free(rls);
	return 1;		
	
}

static void* 
pty_master(void *arg)
{
	int i;
	u_char buf[128];
	
	while (!cmd_quit) {
		memset(buf, 0, sizeof(buf));
		i = read(ptyfdm, buf, sizeof(buf));
		if (i > 0 && write(sock_cli, buf, i))
			;
	}
	return NULL;
}
예제 #15
0
파일: prompt.c 프로젝트: gonzus/tig
void
prompt_init(void)
{
	readline_init();
}
예제 #16
0
void pyexec_friendly_repl_reset() {
    repl.cont_line = false;
    vstr_reset(&repl.line);
    readline_init(&repl.line);
}
예제 #17
0
void pyexec_friendly_repl_init(void) {
    vstr_init(&repl.line, 32);
    repl.cont_line = false;
    readline_init(&repl.line);
    mp_hal_stdout_tx_str(">>> ");
}
예제 #18
0
파일: main.c 프로젝트: aitjcize/micropython
int main(void) {
    // TODO disable JTAG

    /* STM32F4xx HAL library initialization:
         - Configure the Flash prefetch, instruction and Data caches
         - Configure the Systick to generate an interrupt each 1 msec
         - Set NVIC Group Priority to 4
         - Global MSP (MCU Support Package) initialization
       */
    HAL_Init();

    // set the system clock to be HSE
    SystemClock_Config();

    // enable GPIO clocks
    __GPIOA_CLK_ENABLE();
    __GPIOB_CLK_ENABLE();
    __GPIOC_CLK_ENABLE();
    __GPIOD_CLK_ENABLE();

    // enable the CCM RAM
    __CCMDATARAMEN_CLK_ENABLE();

#if 0
#if defined(NETDUINO_PLUS_2)
    {
        GPIO_InitTypeDef GPIO_InitStructure;
        GPIO_InitStructure.GPIO_Speed = GPIO_Speed_25MHz;
        GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
        GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
        GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;

#if MICROPY_HW_HAS_SDCARD
        // Turn on the power enable for the sdcard (PB1)
        GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1;
        GPIO_Init(GPIOB, &GPIO_InitStructure);
        GPIO_WriteBit(GPIOB, GPIO_Pin_1, Bit_SET);
#endif

        // Turn on the power for the 5V on the expansion header (PB2)
        GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;
        GPIO_Init(GPIOB, &GPIO_InitStructure);
        GPIO_WriteBit(GPIOB, GPIO_Pin_2, Bit_SET);
    }
#endif
#endif

    // basic sub-system init
    pendsv_init();
    timer_tim3_init();
    led_init();
    switch_init0();

    int first_soft_reset = true;

soft_reset:

    // check if user switch held to select the reset mode
    led_state(1, 0);
    led_state(2, 1);
    led_state(3, 0);
    led_state(4, 0);
    uint reset_mode = 1;

#if MICROPY_HW_HAS_SWITCH
    if (switch_get()) {
        for (uint i = 0; i < 3000; i++) {
            if (!switch_get()) {
                break;
            }
            HAL_Delay(20);
            if (i % 30 == 29) {
                if (++reset_mode > 3) {
                    reset_mode = 1;
                }
                led_state(2, reset_mode & 1);
                led_state(3, reset_mode & 2);
                led_state(4, reset_mode & 4);
            }
        }
        // flash the selected reset mode
        for (uint i = 0; i < 6; i++) {
            led_state(2, 0);
            led_state(3, 0);
            led_state(4, 0);
            HAL_Delay(50);
            led_state(2, reset_mode & 1);
            led_state(3, reset_mode & 2);
            led_state(4, reset_mode & 4);
            HAL_Delay(50);
        }
        HAL_Delay(400);
    }
#endif

#if MICROPY_HW_ENABLE_RTC
    if (first_soft_reset) {
        rtc_init();
    }
#endif

    // more sub-system init
#if MICROPY_HW_HAS_SDCARD
    if (first_soft_reset) {
        sdcard_init();
    }
#endif
    if (first_soft_reset) {
        storage_init();
    }

    // GC init
    gc_init(&_heap_start, &_heap_end);

    // Change #if 0 to #if 1 if you want REPL on USART_6 (or another usart)
    // as well as on USB VCP
#if 0
    pyb_usart_global_debug = pyb_Usart(MP_OBJ_NEW_SMALL_INT(PYB_USART_YA),
                                       MP_OBJ_NEW_SMALL_INT(115200));
#else
    pyb_usart_global_debug = NULL;
#endif

    // Micro Python init
    qstr_init();
    mp_init();
    mp_obj_list_init(mp_sys_path, 0);
    mp_obj_list_append(mp_sys_path, MP_OBJ_NEW_QSTR(MP_QSTR_0_colon__slash_));
    mp_obj_list_append(mp_sys_path, MP_OBJ_NEW_QSTR(MP_QSTR_0_colon__slash_lib));
    mp_obj_list_init(mp_sys_argv, 0);

    readline_init();

    exti_init();

#if MICROPY_HW_HAS_SWITCH
    // must come after exti_init
    switch_init();
#endif

#if MICROPY_HW_HAS_LCD
    // LCD init (just creates class, init hardware by calling LCD())
    lcd_init();
#endif

    pin_map_init();

    // local filesystem init
    {
        // try to mount the flash
        FRESULT res = f_mount(&fatfs0, "0:", 1);
        if (reset_mode == 3 || res == FR_NO_FILESYSTEM) {
            // no filesystem, or asked to reset it, so create a fresh one

            // LED on to indicate creation of LFS
            led_state(PYB_LED_R2, 1);
            uint32_t start_tick = HAL_GetTick();

            res = f_mkfs("0:", 0, 0);
            if (res == FR_OK) {
                // success creating fresh LFS
            } else {
                __fatal_error("could not create LFS");
            }

            // create empty main.py
            FIL fp;
            f_open(&fp, "0:/main.py", FA_WRITE | FA_CREATE_ALWAYS);
            UINT n;
            f_write(&fp, fresh_main_py, sizeof(fresh_main_py) - 1 /* don't count null terminator */, &n);
            // TODO check we could write n bytes
            f_close(&fp);

            // create .inf driver file
            f_open(&fp, "0:/pybcdc.inf", FA_WRITE | FA_CREATE_ALWAYS);
            f_write(&fp, fresh_pybcdc_inf, sizeof(fresh_pybcdc_inf) - 1 /* don't count null terminator */, &n);
            f_close(&fp);

            // keep LED on for at least 200ms
            sys_tick_wait_at_least(start_tick, 200);
            led_state(PYB_LED_R2, 0);
        } else if (res == FR_OK) {
            // mount sucessful
        } else {
            __fatal_error("could not access LFS");
        }
    }

    // make sure we have a 0:/boot.py
    {
        FILINFO fno;
#if _USE_LFN
        fno.lfname = NULL;
        fno.lfsize = 0;
#endif
        FRESULT res = f_stat("0:/boot.py", &fno);
        if (res == FR_OK) {
            if (fno.fattrib & AM_DIR) {
                // exists as a directory
                // TODO handle this case
                // see http://elm-chan.org/fsw/ff/img/app2.c for a "rm -rf" implementation
            } else {
                // exists as a file, good!
            }
        } else {
            // doesn't exist, create fresh file

            // LED on to indicate creation of boot.py
            led_state(PYB_LED_R2, 1);
            uint32_t start_tick = HAL_GetTick();

            FIL fp;
            f_open(&fp, "0:/boot.py", FA_WRITE | FA_CREATE_ALWAYS);
            UINT n;
            f_write(&fp, fresh_boot_py, sizeof(fresh_boot_py) - 1 /* don't count null terminator */, &n);
            // TODO check we could write n bytes
            f_close(&fp);

            // keep LED on for at least 200ms
            sys_tick_wait_at_least(start_tick, 200);
            led_state(PYB_LED_R2, 0);
        }
    }

    // root device defaults to internal flash filesystem
    uint root_device = 0;

#if defined(USE_DEVICE_MODE)
    usb_storage_medium_t usb_medium = USB_STORAGE_MEDIUM_FLASH;
#endif

#if MICROPY_HW_HAS_SDCARD
    // if an SD card is present then mount it on 1:/
    if (reset_mode == 1 && sdcard_is_present()) {
        FRESULT res = f_mount(&fatfs1, "1:", 1);
        if (res != FR_OK) {
            printf("[SD] could not mount SD card\n");
        } else {
            // use SD card as root device
            root_device = 1;

            if (first_soft_reset) {
                // use SD card as medium for the USB MSD
#if defined(USE_DEVICE_MODE)
                usb_medium = USB_STORAGE_MEDIUM_SDCARD;
#endif
            }
        }
    }
#else
    // Get rid of compiler warning if no SDCARD is configured.
    (void)first_soft_reset;
#endif

    // run <root>:/boot.py, if it exists
    if (reset_mode == 1) {
        const char *boot_file;
        if (root_device == 0) {
            boot_file = "0:/boot.py";
        } else {
            boot_file = "1:/boot.py";
        }
        FRESULT res = f_stat(boot_file, NULL);
        if (res == FR_OK) {
            if (!pyexec_file(boot_file)) {
                flash_error(4);
            }
        }
    }

    // turn boot-up LEDs off
    led_state(2, 0);
    led_state(3, 0);
    led_state(4, 0);

#if defined(USE_HOST_MODE)
    // USB host
    pyb_usb_host_init();
#elif defined(USE_DEVICE_MODE)
    // USB device
    if (reset_mode == 1) {
        usb_device_mode_t usb_mode = USB_DEVICE_MODE_CDC_MSC;
        if (pyb_config_usb_mode != MP_OBJ_NULL) {
            if (strcmp(mp_obj_str_get_str(pyb_config_usb_mode), "CDC+HID") == 0) {
                usb_mode = USB_DEVICE_MODE_CDC_HID;
            }
        }
        pyb_usb_dev_init(usb_mode, usb_medium);
    } else {
        pyb_usb_dev_init(USB_DEVICE_MODE_CDC_MSC, usb_medium);
    }
#endif

#if MICROPY_HW_ENABLE_RNG
    // RNG
    rng_init();
#endif

#if MICROPY_HW_ENABLE_TIMER
    // timer
    //timer_init();
#endif

    // I2C
    i2c_init();

#if MICROPY_HW_HAS_MMA7660
    // MMA accel: init and reset
    accel_init();
#endif

#if MICROPY_HW_ENABLE_SERVO
    // servo
    servo_init();
#endif

#if MICROPY_HW_ENABLE_DAC
    // DAC
    dac_init();
#endif

    // now that everything is initialised, run main script
    if (reset_mode == 1 && pyexec_mode_kind == PYEXEC_MODE_FRIENDLY_REPL) {
        vstr_t *vstr = vstr_new();
        vstr_printf(vstr, "%d:/", root_device);
        if (pyb_config_main == MP_OBJ_NULL) {
            vstr_add_str(vstr, "main.py");
        } else {
            vstr_add_str(vstr, mp_obj_str_get_str(pyb_config_main));
        }
        FRESULT res = f_stat(vstr_str(vstr), NULL);
        if (res == FR_OK) {
            if (!pyexec_file(vstr_str(vstr))) {
                flash_error(3);
            }
        }
        vstr_free(vstr);
    }

#if 0
#if MICROPY_HW_HAS_WLAN
    // wifi
    pyb_wlan_init();
    pyb_wlan_start();
#endif
#endif

    // enter REPL
    // REPL mode can change, or it can request a soft reset
    for (;;) {
        if (pyexec_mode_kind == PYEXEC_MODE_RAW_REPL) {
            if (pyexec_raw_repl() != 0) {
                break;
            }
        } else {
            if (pyexec_friendly_repl() != 0) {
                break;
            }
        }
    }

    printf("PYB: sync filesystems\n");
    storage_flush();

    printf("PYB: soft reboot\n");

    first_soft_reset = false;
    goto soft_reset;
}