void HyphenateHD_Text( zCPCHAR cpcText, zPCHAR pchReturn, zLONG lMaxLth, zLONG lIdx ) { zBOOL bGoodBreak = FALSE; zLONG k; strcpy_s( pchReturn, lMaxLth, cpcText ); // if ( zstrcmp( cpcText, "M_InsertTextKeywordTitleDU" ) == 0 ) // TraceLineS( "HyphenateCheck ", cpcText ); while ( lIdx > 5 && lIdx > (zLONG) (zstrlen( cpcText ) / 2) ) // purist's goto { zPCHAR pchTemp; zPCHAR pch; // check for lowercase/uppercase change k = lIdx + 1; while ( k > lIdx - 5 ) { if ( pchReturn[ k ] == '_' || (isupper( pchReturn[ k ] ) && islower( pchReturn[ k - 1 ] )) ) { if ( k <= lIdx ) { bGoodBreak = TRUE; if ( pchReturn[ k ] == '_' ) lIdx = k; else lIdx = k - 1; break; } } k--; } if ( k > lIdx - 5 ) break; // we found a good place to break // check for standard endings that would make a good place to break the text pchTemp = pchReturn + lIdx - 5; if ( (pch = zstrstr( pchTemp, "ing" )) != 0 || (pch = zstrstr( pchTemp, "able" )) != 0 || (pch = zstrstr( pchTemp, "tion" )) != 0 || (pch = zstrstr( pchTemp, "bute" )) != 0 || (pch = zstrstr( pchTemp, "er" )) != 0 ) { if ( pch < pchReturn + lIdx ) { k = pchReturn + lIdx - pch; lIdx -= k; } } break; // get out of purist's goto (while) } k = ++lIdx; if ( bGoodBreak == FALSE ) pchReturn[ lIdx++ ] = '-'; pchReturn[ lIdx++ ] = '\n'; strcpy_s( pchReturn + lIdx, lMaxLth - lIdx, cpcText + k ); }
MX_EXPORT mx_status_type mxd_dg645_pulser_open( MX_RECORD *record ) { static const char fname[] = "mxd_dg645_pulser_open()"; MX_PULSE_GENERATOR *pulser; MX_DG645_PULSER *dg645_pulser = NULL; MX_DG645 *dg645 = NULL; size_t i, length; int c; char *output_name; mx_status_type mx_status; if ( record == (MX_RECORD *) NULL ) { return mx_error( MXE_NULL_ARGUMENT, fname, "The MX_RECORD pointer passed was NULL." ); } pulser = (MX_PULSE_GENERATOR *) record->record_class_struct; mx_status = mxd_dg645_pulser_get_pointers( pulser, &dg645_pulser, &dg645, fname ); if ( mx_status.code != MXE_SUCCESS ) return mx_status; output_name = dg645_pulser->output_name; length = strlen( output_name ); if ( length != 2 ) { return mx_error( MXE_ILLEGAL_ARGUMENT, fname, "Invalid output name '%s'. " "Output names for '%s' should be 2 characters long.", output_name, record->name ); } /* Force the output_name field to upper case. */ for ( i = 0; i < length; i++ ) { c = output_name[i]; if ( islower(c) ) { output_name[i] = toupper(c); } } /* Figure out the output number for this channel as used by * delay and output commands. */ if ( strcmp( "T0", output_name ) == 0 ) { dg645_pulser->output_number = 0; } else if ( strcmp( "AB", output_name ) == 0 ) { dg645_pulser->output_number = 1; } else if ( strcmp( "CD", output_name ) == 0 ) { dg645_pulser->output_number = 2; } else if ( strcmp( "EF", output_name ) == 0 ) { dg645_pulser->output_number = 3; } else if ( strcmp( "GH", output_name ) == 0 ) { dg645_pulser->output_number = 4; } else { return mx_error( MXE_ILLEGAL_ARGUMENT, fname, "Illegal output name '%s' requested for pulser '%s'. " "The allowed names are 'T0', 'AB', 'CD', 'EF', and 'GH'.", output_name, record->name ); } /* Call setup() to put the pulser into the state configured in * the MX configuration file. */ mx_status = mx_pulse_generator_setup( record, pulser->pulse_period, pulser->pulse_width, pulser->num_pulses, pulser->pulse_delay, pulser->function_mode, pulser->trigger_mode ); return mx_status; }
/*-------------------------------------------------------------------*/ DLL_EXPORT int impl(int argc, char *argv[]) { char *cfgfile; /* -> Configuration filename */ char pathname[MAX_PATH]; /* work area for filenames */ #if defined ( OPTION_LOCK_CONFIG_FILE ) int fd_cfg = -1; /* fd for config file */ #if !defined ( _MSVC_ ) struct flock fl_cfg; /* file lock for conf file */ #endif #endif int c; /* Work area for getopt */ int arg_error = 0; /* 1=Invalid arguments */ char *msgbuf; /* */ int msgnum; /* */ int msgcnt; /* */ TID rctid; /* RC file thread identifier */ TID logcbtid; /* RC file thread identifier */ int rc; #if defined(EXTERNALGUI) int e_gui = FALSE; /* EXTERNALGUI parm */ #endif #if defined(OPTION_DYNAMIC_LOAD) #define MAX_DLL_TO_LOAD 50 char *dll_load[MAX_DLL_TO_LOAD]; /* Pointers to modnames */ int dll_count; /* index into array */ #endif /* Seed the pseudo-random number generator */ srand( time(NULL) ); /* Clear the system configuration block */ memset( &sysblk, 0, sizeof( SYSBLK ) ); VERIFY( MLOCK( &sysblk, sizeof( SYSBLK )) == 0); #if defined (_MSVC_) _setmaxstdio(2048); #endif /* Initialize EYE-CATCHERS for SYSBLK */ memset(&sysblk.blknam,SPACE,sizeof(sysblk.blknam)); memset(&sysblk.blkver,SPACE,sizeof(sysblk.blkver)); memset(&sysblk.blkend,SPACE,sizeof(sysblk.blkend)); sysblk.blkloc = swap_byte_U64((U64)((uintptr_t)&sysblk)); memcpy(sysblk.blknam,HDL_NAME_SYSBLK,strlen(HDL_NAME_SYSBLK)); memcpy(sysblk.blkver,HDL_VERS_SYSBLK,strlen(HDL_VERS_SYSBLK)); sysblk.blksiz = swap_byte_U32((U32)sizeof(SYSBLK)); { char buf[32]; MSGBUF( buf, "END%13.13s", HDL_NAME_SYSBLK ); memcpy(sysblk.blkend, buf, sizeof(sysblk.blkend)); } /* Initialize SETMODE and set user authority */ SETMODE(INIT); #if defined(OPTION_DYNAMIC_LOAD) for ( dll_count = 0; dll_count < MAX_DLL_TO_LOAD; dll_count++ ) dll_load[dll_count] = NULL; dll_count = -1; #endif SET_THREAD_NAME("impl"); /* Initialize 'hostinfo' BEFORE display_version is called */ init_hostinfo( &hostinfo ); #ifdef _MSVC_ /* Initialize sockets package */ VERIFY( socket_init() == 0 ); #endif /* Ensure hdl_shut is called in case of shutdown hdl_shut will ensure entries are only called once */ atexit(hdl_shut); if ( argc > 0 ) { int i,len; for (len = 0, i = 0; i < argc; i++ ) len += (int)strlen( (char *)argv[i] ) + 1; sysblk.hercules_cmdline = (char *)malloc( len ); strlcpy( sysblk.hercules_cmdline, argv[0], len ); for ( i = 1; i < argc; i++ ) { strlcat( sysblk.hercules_cmdline, " ", len ); strlcat( sysblk.hercules_cmdline, argv[i], len ); } } /* Set program name */ if ( argc > 0 ) { if ( strlen(argv[0]) == 0 ) { sysblk.hercules_pgmname = strdup("hercules"); sysblk.hercules_pgmpath = strdup(""); } else { char path[MAX_PATH]; #if defined( _MSVC_ ) GetModuleFileName( NULL, path, MAX_PATH ); #else strncpy(path,argv[0],sizeof(path)-1); #endif sysblk.hercules_pgmname = strdup(basename(path)); #if !defined( _MSVC_ ) strncpy(path,argv[0],sizeof(path)-1); #endif sysblk.hercules_pgmpath = strdup(dirname(path)); } } else { sysblk.hercules_pgmname = strdup("hercules"); sysblk.hercules_pgmpath = strdup(""); } #if defined( OPTION_CONFIG_SYMBOLS ) /* These were moved from console.c to make them available sooner */ set_symbol( "VERSION", VERSION); set_symbol( "BDATE", __DATE__ ); set_symbol( "BTIME", __TIME__ ); { char num_procs[64]; if ( hostinfo.num_packages != 0 && hostinfo.num_physical_cpu != 0 && hostinfo.num_logical_cpu != 0 ) { MSGBUF( num_procs, "LP=%d, Cores=%d, CPUs=%d", hostinfo.num_logical_cpu, hostinfo.num_physical_cpu, hostinfo.num_packages ); } else { if ( hostinfo.num_procs > 1 ) MSGBUF( num_procs, "MP=%d", hostinfo.num_procs ); else if ( hostinfo.num_procs == 1 ) strlcpy( num_procs, "UP", sizeof(num_procs) ); else strlcpy( num_procs, "", sizeof(num_procs) ); } set_symbol( "HOSTNAME", hostinfo.nodename ); set_symbol( "HOSTOS", hostinfo.sysname ); set_symbol( "HOSTOSREL", hostinfo.release ); set_symbol( "HOSTOSVER", hostinfo.version ); set_symbol( "HOSTARCH", hostinfo.machine ); set_symbol( "HOSTNUMCPUS", num_procs ); } set_symbol( "MODNAME", sysblk.hercules_pgmname ); set_symbol( "MODPATH", sysblk.hercules_pgmpath ); #endif // defined( OPTION_CONFIG_SYMBOLS ) sysblk.sysgroup = DEFAULT_SYSGROUP; sysblk.msglvl = DEFAULT_MLVL; /* Defaults to TERSE and DEVICES */ /* set default console port address */ sysblk.cnslport = strdup("3270"); /* set default tape autoinit value to OFF */ sysblk.noautoinit = TRUE; /* default for system dasd cache is on */ sysblk.dasdcache = TRUE; #if defined(OPTION_MSGCLR) || defined(OPTION_MSGHLD) /* set default error message display (emsg) */ sysblk.emsg = EMSG_ON; #endif #if defined( OPTION_SHUTDOWN_CONFIRMATION ) /* set default quit timeout value (also ssd) */ sysblk.quitmout = QUITTIME_PERIOD; #endif /* Default command separator to off (NULL) */ sysblk.cmdsep = NULL; #if defined(_FEATURE_SYSTEM_CONSOLE) /* set default for scpecho to TRUE */ sysblk.scpecho = TRUE; /* set fault for scpimply to FALSE */ sysblk.scpimply = FALSE; #endif /* set default system state to reset */ sysblk.sys_reset = TRUE; /* set default SHCMDOPT enabled */ sysblk.shcmdopt = SHCMDOPT_ENABLE + SHCMDOPT_DIAG8; /* Save process ID */ sysblk.hercules_pid = getpid(); /* Save thread ID of main program */ sysblk.impltid = thread_id(); /* Save TOD of when we were first IMPL'ed */ time( &sysblk.impltime ); /* Set to LPAR mode with LPAR 1, LPAR ID of 01, and CPUIDFMT 0 */ sysblk.lparmode = 1; /* LPARNUM 1 # LPAR ID 01 */ sysblk.lparnum = 1; /* ... */ sysblk.cpuidfmt = 0; /* CPUIDFMT 0 */ sysblk.operation_mode = om_mif; /* Default to MIF operaitons */ /* set default CPU identifier */ sysblk.cpumodel = 0x0586; sysblk.cpuversion = 0xFD; sysblk.cpuserial = 0x000001; sysblk.cpuid = createCpuId(sysblk.cpumodel, sysblk.cpuversion, sysblk.cpuserial, 0); /* set default Program Interrupt Trace to NONE */ sysblk.pgminttr = OS_NONE; sysblk.timerint = DEF_TOD_UPDATE_USECS; /* set default thread priorities */ sysblk.hercprio = DEFAULT_HERCPRIO; sysblk.todprio = DEFAULT_TOD_PRIO; sysblk.cpuprio = DEFAULT_CPU_PRIO; sysblk.devprio = DEFAULT_DEV_PRIO; sysblk.srvprio = DEFAULT_SRV_PRIO; /* Cap the default priorities at zero if setuid not available */ #if !defined( _MSVC_ ) #if !defined(NO_SETUID) if (sysblk.suid) #endif { if (sysblk.hercprio < 0) sysblk.hercprio = 0; if (sysblk.todprio < 0) sysblk.todprio = 0; if (sysblk.cpuprio < 0) sysblk.cpuprio = 0; if (sysblk.devprio < 0) sysblk.devprio = 0; if (sysblk.srvprio < 0) sysblk.srvprio = 0; } #endif /* set default console keep alive values */ sysblk.kaidle = KEEPALIVE_IDLE_TIME; sysblk.kaintv = KEEPALIVE_PROBE_INTERVAL; sysblk.kacnt = KEEPALIVE_PROBE_COUNT; #if defined(_FEATURE_ECPSVM) sysblk.ecpsvm.available = 0; sysblk.ecpsvm.level = 20; #endif #ifdef PANEL_REFRESH_RATE sysblk.panrate = PANEL_REFRESH_RATE_SLOW; #endif #if defined( OPTION_SHUTDOWN_CONFIRMATION ) /* Set the quitmout value */ sysblk.quitmout = QUITTIME_PERIOD; /* quit timeout value */ #endif #if defined(OPTION_SHARED_DEVICES) sysblk.shrdport = 0; #endif #ifdef OPTION_MSGHLD /* Set the default timeout value */ sysblk.keep_timeout_secs = 120; #endif #if defined(OPTION_CONFIG_SYMBOLS) && defined(OPTION_BUILTIN_SYMBOLS) /* setup defaults for BUILTIN symbols */ { char buf[8]; set_symbol("LPARNAME", str_lparname()); set_symbol("LPARNUM", "1"); set_symbol("CPUIDFMT", "0"); MSGBUF( buf, "%06X", sysblk.cpuserial ); set_symbol( "CPUSERIAL", buf ); MSGBUF( buf, "%04X", sysblk.cpumodel ); set_symbol( "CPUMODEL", buf ); } #endif /* defined(OPTION_CONFIG_SYMBOLS) && defined(OPTION_BUILTIN_SYMBOLS */ #if defined(_FEATURE_CMPSC_ENHANCEMENT_FACILITY) sysblk.zpbits = DEF_CMPSC_ZP_BITS; #endif /* Initialize locks, conditions, and attributes */ initialize_lock (&sysblk.config); initialize_lock (&sysblk.todlock); initialize_lock (&sysblk.mainlock); sysblk.mainowner = LOCK_OWNER_NONE; initialize_lock (&sysblk.intlock); initialize_lock (&sysblk.iointqlk); sysblk.intowner = LOCK_OWNER_NONE; initialize_lock (&sysblk.sigplock); initialize_lock (&sysblk.mntlock); initialize_lock (&sysblk.scrlock); initialize_lock (&sysblk.crwlock); initialize_lock (&sysblk.ioqlock); initialize_condition (&sysblk.ioqcond); #if defined(OPTION_CMDSER) initialize_lock (&sysblk.cmdlock); initialize_condition (&sysblk.cmdcond); #endif /*defined(OPTION_CMDSER)*/ #ifdef FEATURE_MESSAGE_SECURITY_ASSIST_EXTENSION_3 /* Initialize the wrapping key registers lock */ initialize_rwlock(&sysblk.wklock); #endif /* Initialize thread creation attributes so all of hercules can use them at any time when they need to create_thread */ initialize_detach_attr (DETACHED); initialize_join_attr (JOINABLE); initialize_condition (&sysblk.cpucond); { int i; for (i = 0; i < MAX_CPU_ENGINES; i++) initialize_lock (&sysblk.cpulock[i]); } initialize_condition (&sysblk.sync_cond); initialize_condition (&sysblk.sync_bc_cond); /* Copy length for regs */ sysblk.regs_copy_len = (int)((uintptr_t)&sysblk.dummyregs.regs_copy_end - (uintptr_t)&sysblk.dummyregs); /* Set the daemon_mode flag indicating whether we running in background/daemon mode or not (meaning both stdout/stderr are redirected to a non-tty device). Note that this flag needs to be set before logger_init gets called since the logger_logfile_write function relies on its setting. */ sysblk.daemon_mode = !isatty(STDERR_FILENO) && !isatty(STDOUT_FILENO); /* Initialize the logmsg pipe and associated logger thread. This causes all subsequent logmsg's to be redirected to the logger facility for handling by virtue of stdout/stderr being redirected to the logger facility. */ logger_init(); /* Setup the initial codepage */ set_codepage(NULL); /* Now display the version information again after logger_init has been called so that either the panel display thread or the external gui can see the version which was previously possibly only displayed to the actual physical screen the first time we did it further above (depending on whether we're running in daemon_mode (external gui mode) or not). This it the call that the panel thread or the one the external gui actually "sees". The first call further above wasn't seen by either since it was issued before logger_init was called and thus got written directly to the physical screen whereas this one will be inter- cepted and handled by the logger facility thereby allowing the panel thread or external gui to "see" it and thus display it. */ display_version (stdout, "Hercules", TRUE); #ifdef EXTERNALGUI if (argc >= 1 && strncmp(argv[argc-1],"EXTERNALGUI",11) == 0) { e_gui = TRUE; argc--; } #endif #if !defined(WIN32) && !defined(HAVE_STRERROR_R) strerror_r_init(); #endif #if defined(OPTION_SCSI_TAPE) initialize_lock ( &sysblk.stape_lock ); initialize_condition ( &sysblk.stape_getstat_cond ); InitializeListHead ( &sysblk.stape_mount_link ); InitializeListHead ( &sysblk.stape_status_link ); #endif /* defined(OPTION_SCSI_TAPE) */ /* Get name of configuration file or default to hercules.cnf */ if(!(cfgfile = getenv("HERCULES_CNF"))) cfgfile = "hercules.cnf"; /* Process the command line options */ { #define HERCULES_BASE_OPTS "hf:r:db:v" #define HERCULES_SYM_OPTS "" #define HERCULES_HDL_OPTS "" #if defined(OPTION_CONFIG_SYMBOLS) #undef HERCULES_SYM_OPTS #define HERCULES_SYM_OPTS "s:" #endif #if defined(OPTION_DYNAMIC_LOAD) #undef HERCULES_HDL_OPTS #define HERCULES_HDL_OPTS "p:l:" #endif #define HERCULES_OPTS_STRING HERCULES_BASE_OPTS HERCULES_SYM_OPTS HERCULES_HDL_OPTS #if defined(HAVE_GETOPT_LONG) static struct option longopts[] = { { "help", no_argument, NULL, 'h' }, { "config", required_argument, NULL, 'f' }, { "rcfile", required_argument, NULL, 'r' }, { "daemon", no_argument, NULL, 'd' }, { "herclogo", required_argument, NULL, 'b' }, { "verbose", no_argument, NULL, 'v' }, #if defined(OPTION_CONFIG_SYMBOLS) { "defsym", required_argument, NULL, 's' }, #endif #if defined(OPTION_DYNAMIC_LOAD) { "modpath", required_argument, NULL, 'p' }, { "ldmod", required_argument, NULL, 'l' }, #endif { NULL, 0, NULL, 0 } }; while ((c = getopt_long( argc, argv, HERCULES_OPTS_STRING, longopts, NULL )) != EOF) #else while ((c = getopt( argc, argv, HERCULES_OPTS_STRING )) != EOF) #endif { switch (c) { case 'h': arg_error = 1; break; case 'f': cfgfile = optarg; break; case 'r': rcname = optarg; break; #if defined(OPTION_CONFIG_SYMBOLS) case 's': { char *sym = NULL; char *value = NULL; char *strtok_str = NULL; if ( strlen( optarg ) >= 3 ) { sym = strtok_r( optarg, "=", &strtok_str); value = strtok_r( NULL, "=", &strtok_str); if ( sym != NULL && value != NULL ) { int j; for( j = 0; j < (int)strlen( sym ); j++ ) if ( islower( sym[j] ) ) { sym[j] = toupper( sym[j] ); } set_symbol(sym, value); } else WRMSG(HHC01419, "E" ); } else WRMSG(HHC01419, "E"); } break; #endif /* defined(OPTION_CONFIG_SYMBOLS) */ #if defined(OPTION_DYNAMIC_LOAD) case 'p': if(optarg) hdl_setpath(strdup(optarg), FALSE); break; case 'l': { char *dllname, *strtok_str = NULL; for(dllname = strtok_r(optarg,", ",&strtok_str); dllname; dllname = strtok_r(NULL,", ",&strtok_str)) { if (dll_count < MAX_DLL_TO_LOAD - 1) dll_load[++dll_count] = strdup(dllname); else { WRMSG(HHC01406, "W", MAX_DLL_TO_LOAD); break; } } } break; #endif /* defined(OPTION_DYNAMIC_LOAD) */ case 'b': sysblk.logofile = optarg; break; case 'v': sysblk.msglvl |= MLVL_VERBOSE; break; case 'd': sysblk.daemon_mode = 1; break; default: arg_error = 1; } /* end switch(c) */ } /* end while */ } /* end Process the command line options */ /* Treat filename None as special */ if(!strcasecmp(cfgfile,"None")) cfgfile = NULL; if (optind < argc) arg_error = 1; /* Terminate if invalid arguments were detected */ if (arg_error) { char pgm[MAX_PATH]; char* strtok_str = NULL; strncpy(pgm, sysblk.hercules_pgmname, sizeof(pgm)); /* Show them all of our command-line arguments... */ WRMSG (HHC01414, "S", ""); // (blank line) WRMSG (HHC01414, "S", ""); // (blank line) #if defined(OPTION_DYNAMIC_LOAD) // "Usage: %s [-f config-filename] [-d] [-b logo-filename] [-s sym=val]%s [> logfile]" WRMSG (HHC01407, "S", strtok_r(pgm,".",&strtok_str), " [-p dyn-load-dir] [[-l dynmod-to-load]...]"); #else WRMSG (HHC01407, "S", strtok_r(pgm,".", &strtok_str), ""); #endif /* defined(OPTION_DYNAMIC_LOAD) */ WRMSG (HHC01414, "S", ""); // (blank line) WRMSG (HHC01414, "S", ""); // (blank line) fflush(stderr); fflush(stdout); usleep(100000); return(1); } /* Initialize runtime opcode tables */ init_opcode_tables(); #if defined(OPTION_DYNAMIC_LOAD) /* Initialize the hercules dynamic loader */ hdl_main(); /* Load modules requested at startup */ if (dll_count >= 0) { int hl_err = FALSE; for ( dll_count = 0; dll_count < MAX_DLL_TO_LOAD; dll_count++ ) { if (dll_load[dll_count] != NULL) { if (hdl_load(dll_load[dll_count], HDL_LOAD_DEFAULT) != 0) { hl_err = TRUE; } free(dll_load[dll_count]); } else break; } if (hl_err) { usleep(10000); // give logger time to issue error message WRMSG(HHC01408, "S"); delayed_exit(-1); return(1); } } #endif /* defined(OPTION_DYNAMIC_LOAD) */ #ifdef EXTERNALGUI /* Set GUI flag if specified as final argument */ if (e_gui) { #if defined(OPTION_DYNAMIC_LOAD) if (hdl_load("dyngui",HDL_LOAD_DEFAULT) != 0) { usleep(10000); /* (give logger thread time to issue preceding HHC01516E message) */ WRMSG(HHC01409, "S"); delayed_exit(-1); return(1); } #endif /* defined(OPTION_DYNAMIC_LOAD) */ } #endif /*EXTERNALGUI*/ /* Register the SIGINT handler */ if ( signal (SIGINT, sigint_handler) == SIG_ERR ) { WRMSG(HHC01410, "S", "SIGINT", strerror(errno)); delayed_exit(-1); return(1); } /* Register the SIGTERM handler */ if ( signal (SIGTERM, sigterm_handler) == SIG_ERR ) { WRMSG(HHC01410, "S", "SIGTERM", strerror(errno)); delayed_exit(-1); return(1); } #if defined( _MSVC_ ) /* Register the Window console ctrl handlers */ if (!IsDebuggerPresent()) { if (!SetConsoleCtrlHandler( console_ctrl_handler, TRUE )) { WRMSG( HHC01410, "S", "Console-ctrl", strerror( errno )); delayed_exit(-1); return(1); } } #endif #if defined(HAVE_DECL_SIGPIPE) && HAVE_DECL_SIGPIPE /* Ignore the SIGPIPE signal, otherwise Hercules may terminate with Broken Pipe error if the printer driver writes to a closed pipe */ if ( signal (SIGPIPE, SIG_IGN) == SIG_ERR ) { WRMSG(HHC01411, "E", strerror(errno)); } #endif { int fds[2]; initialize_lock(&sysblk.cnslpipe_lock); initialize_lock(&sysblk.sockpipe_lock); sysblk.cnslpipe_flag=0; sysblk.sockpipe_flag=0; VERIFY( create_pipe(fds) >= 0 ); sysblk.cnslwpipe=fds[1]; sysblk.cnslrpipe=fds[0]; VERIFY( create_pipe(fds) >= 0 ); sysblk.sockwpipe=fds[1]; sysblk.sockrpipe=fds[0]; } #if !defined(NO_SIGABEND_HANDLER) { struct sigaction sa; sa.sa_sigaction = (void*)&sigabend_handler; #ifdef SA_NODEFER sa.sa_flags = SA_NODEFER; #else sa.sa_flags = 0; #endif if( sigaction(SIGILL, &sa, NULL) || sigaction(SIGFPE, &sa, NULL) || sigaction(SIGSEGV, &sa, NULL) || sigaction(SIGBUS, &sa, NULL) || sigaction(SIGUSR1, &sa, NULL) || sigaction(SIGUSR2, &sa, NULL) ) { WRMSG(HHC01410, "S", "SIGILL/FPE/SEGV/BUS/USR", strerror(errno)); delayed_exit(-1); return(1); } } #endif /*!defined(NO_SIGABEND_HANDLER)*/ if(cfgfile) { /* attempt to get lock on config file */ hostpath(pathname, cfgfile, sizeof(pathname)); #if defined( OPTION_LOCK_CONFIG_FILE ) /* Test that we can get a read the file */ if ( ( fd_cfg = HOPEN( pathname, O_RDONLY, S_IRUSR | S_IRGRP ) ) < 0 ) { if ( errno == EACCES ) { WRMSG( HHC01453, "S", cfgfile, strerror( errno ) ); delayed_exit(-1); return(1); } } else { if ( lseek(fd_cfg, 0L, 2) < 0 ) { if ( errno == EACCES ) { WRMSG( HHC01453, "S", cfgfile, strerror( errno ) ); delayed_exit(-1); return(1); } } close( fd_cfg ); } /* File was not lock, therefore we can proceed */ #endif // OPTION_LOCK_CONFIG_FILE } /* System initialisation time */ sysblk.todstart = hw_clock() << 8; #if !defined(NO_SIGABEND_HANDLER) /* Start the watchdog */ rc = create_thread (&sysblk.wdtid, DETACHED, watchdog_thread, NULL, "watchdog_thread"); if (rc) { WRMSG(HHC00102, "E", strerror(rc)); delayed_exit(-1); return(1); } #endif /*!defined(NO_SIGABEND_HANDLER)*/ if(log_callback) { // 'herclin' called us. IT'S in charge. Create its requested // logmsg intercept callback function and return back to it. rc = create_thread(&logcbtid,DETACHED, log_do_callback,NULL,"log_do_callback"); if (rc) WRMSG(HHC00102, "E", strerror(rc)); return(0); } hdl_adsc("release_config", release_config, NULL); /* Build system configuration */ if ( build_config (cfgfile) ) { delayed_exit(-1); return(1); } /* Start up the RC file processing thread */ rc = create_thread(&rctid,DETACHED, process_rc_file,NULL,"process_rc_file"); if (rc) WRMSG(HHC00102, "E", strerror(rc)); #if defined( OPTION_LOCK_CONFIG_FILE ) if(cfgfile) { if ( ( fd_cfg = HOPEN( pathname, O_RDONLY, S_IRUSR | S_IRGRP ) ) < 0 ) { WRMSG( HHC01432, "S", pathname, "open()", strerror( errno ) ); delayed_exit(-1); return(1); } else { #if defined( _MSVC_ ) if( ( rc = _locking( fd_cfg, _LK_NBRLCK, 1L ) ) < 0 ) { int rc = errno; WRMSG( HHC01454, "S", pathname, "_locking()", strerror( errno ) ); delayed_exit(-1); return(1); } #else fl_cfg.l_type = F_RDLCK; fl_cfg.l_whence = SEEK_SET; fl_cfg.l_start = 0; fl_cfg.l_len = 1; if ( fcntl(fd_cfg, F_SETLK, &fl_cfg) == -1 ) { if (errno == EACCES || errno == EAGAIN) { WRMSG( HHC01432, "S", pathname, "fcntl()", strerror( errno ) ); delayed_exit(-1); return(1); } } #endif } } #endif // OPTION_LOCK_CONFIG_FILE //--------------------------------------------------------------- // The below functions will not return until Hercules is shutdown //--------------------------------------------------------------- /* Activate the control panel */ if(!sysblk.daemon_mode) panel_display (); else { #if defined(OPTION_DYNAMIC_LOAD) if(daemon_task) daemon_task (); else #endif /* defined(OPTION_DYNAMIC_LOAD) */ { /* Tell RC file and HAO threads they may now proceed */ sysblk.panel_init = 1; /* Retrieve messages from logger and write to stderr */ while (1) if((msgcnt = log_read(&msgbuf, &msgnum, LOG_BLOCK))) if(isatty(STDERR_FILENO)) fwrite(msgbuf,msgcnt,1,stderr); } } // ----------------------------------------------------- // *** Hercules has been shutdown (PAST tense) *** // ----------------------------------------------------- #if defined( OPTION_LOCK_CONFIG_FILE ) if(cfgfile) close( fd_cfg ); // release config file lock #endif // OPTION_LOCK_CONFIG_FILE ASSERT( sysblk.shutdown ); // (why else would we be here?!) #ifdef _MSVC_ SetConsoleCtrlHandler(console_ctrl_handler, FALSE); socket_deinit(); #endif #if defined(OPTION_MSGCLR) || defined(OPTION_MSGHLD) if ( sysblk.emsg & EMSG_TEXT ) fprintf(stdout, HHC01412 ); else #endif fprintf(stdout, MSG(HHC01412, "I")); fflush(stdout); usleep(10000); return 0; } /* end function impl */
char upcase(char ch){ if(islower(ch)) ch -= 'a' - 'A'; return ch; }
int main(int argc, char* argv[]) { // set some variables, others worked properly further on string cypher; int cypher_len; int i, counter; bool cypher_valid = false; // make sure user entered only a single argument at the command line if (argc != 2) { // yell at user to follow the directions printf("Please try again with only one alphabetical entry.\n"); return 1; } else { cypher = argv[1]; cypher_len = strlen(argv[1]); // iterate the following over the length of the entered cypher: for (i = 0; i < cypher_len; i++) { if (!isalpha(argv[1][i])) // yell at user to follow the directions { printf("Please try again with only one alphabetical entry.\n"); return 1; } else { // validate the cypher since no violations occurred cypher_valid = true; } } } // double check to make sure cypher was validated if (cypher_valid == true) { // prompt for the secret message that will be encrypted char* smsg = GetString(); // set more variables related to the secret message, yay! size_t smsg_len = strlen(smsg); char smsg_encrypt[smsg_len]; int element = 0; counter = 0; // iterate the following over the length of the secret message: for (i = 0; i < smsg_len; i++) { // encrypt upper/lowercase letters in secret message if (isalpha(smsg[i])) { element = counter % cypher_len; if (islower(smsg[i])) { if (islower(cypher[element])) { smsg_encrypt[i] = ((((smsg[i] - 97) + cypher[element] - 97) % 26) + 97); } else { smsg_encrypt[i] = ((((smsg[i] - 97) + cypher[element] - 65) % 26) + 97); } } } if (isupper(smsg[i])) { if (islower(cypher[element])) { smsg_encrypt[i] = ((((smsg[i] - 65) + cypher[element] - 97) % 26) + 65); } else { smsg_encrypt[i] = ((((smsg[i] - 65) + cypher[element] - 65) % 26) + 65); } } counter++; } // print the encrypted message! Crap... not quite rght, but I'm out of time! So close! printf("%s\n", smsg_encrypt); } }
/* * Do format conversion placing the output in buffer */ API_EXPORT(int) ap_vformatter(int (*flush_func)(ap_vformatter_buff *), ap_vformatter_buff *vbuff, const char *fmt, va_list ap) { register char *sp; register char *bep; register int cc = 0; register int i; register char *s = NULL; char *q; int s_len; register int min_width = 0; int precision = 0; enum { LEFT, RIGHT } adjust; char pad_char; char prefix_char; double fp_num; wide_int i_num = (wide_int) 0; u_wide_int ui_num; char num_buf[NUM_BUF_SIZE]; char char_buf[2]; /* for printing %% and %<unknown> */ /* * Flag variables */ boolean_e is_long; boolean_e alternate_form; boolean_e print_sign; boolean_e print_blank; boolean_e adjust_precision; boolean_e adjust_width; bool_int is_negative; sp = vbuff->curpos; bep = vbuff->endpos; while (*fmt) { if (*fmt != '%') { INS_CHAR(*fmt, sp, bep, cc); } else { /* * Default variable settings */ adjust = RIGHT; alternate_form = print_sign = print_blank = NO; pad_char = ' '; prefix_char = NUL; fmt++; /* * Try to avoid checking for flags, width or precision */ if (isascii(*fmt) && !islower(*fmt)) { /* * Recognize flags: -, #, BLANK, + */ for (;; fmt++) { if (*fmt == '-') adjust = LEFT; else if (*fmt == '+') print_sign = YES; else if (*fmt == '#') alternate_form = YES; else if (*fmt == ' ') print_blank = YES; else if (*fmt == '0') pad_char = '0'; else break; } /* * Check if a width was specified */ if (isdigit(*fmt)) { STR_TO_DEC(fmt, min_width); adjust_width = YES; } else if (*fmt == '*') { min_width = va_arg(ap, int); fmt++; adjust_width = YES; if (min_width < 0) { adjust = LEFT; min_width = -min_width; } } else adjust_width = NO; /* * Check if a precision was specified * * XXX: an unreasonable amount of precision may be specified * resulting in overflow of num_buf. Currently we * ignore this possibility. */ if (*fmt == '.') { adjust_precision = YES; fmt++; if (isdigit(*fmt)) { STR_TO_DEC(fmt, precision); } else if (*fmt == '*') { precision = va_arg(ap, int); fmt++; if (precision < 0) precision = 0; } else
/* * routine to read in a string with string-build characters * used for search, tag, file name operations * returns 0 if empty string entered, nonzero otherwise * * lbuff - addr of q-reg header */ int build_string(struct qh *lbuff) { int count; /* char count */ struct buffcell *tp; /* pointer to temporary string */ char c; /* temp character */ /* read terminator */ term_char = (atflag) ? getcmdc(trace_sw) : ESC; count = atflag = 0; /* initialize char count */ /* if string is not empty */ if (!peekcmdc(term_char)) { /* * Create a temporary string and read chars into * it until the terminator */ for (tp = bb.p = get_bcell(), bb.c = 0; (c = getcmdc(trace_sw)) != term_char; ) { /* read next char as CTL */ if ((c == '^') && !(ed_val & ED_CARET)) { if ((c = getcmdc(trace_sw)) == term_char) { ERROR(msp <= &mstack[0] ? E_UTC : E_UTM); } c &= 0x1f; } /* if a control char */ if ((c &= 0177) < ' ') { switch (c) { /* take next char literally */ case CTL('Q'): case CTL('R'): if ((c = getcmdc(trace_sw)) == term_char) { ERROR((msp <= &mstack[0]) ? E_UTC : E_UTM); } /* fetch character and go store */ break; /* take next char as lower case */ case CTL('V'): if (getcmdc(trace_sw) == term_char) { ERROR((msp <= &mstack[0]) ? E_UTC : E_UTM); } c = mapch_l[cmdc & 0xFF]; break; /* take next char as upper case */ case CTL('W'): if ((c = getcmdc(trace_sw)) == term_char) { ERROR((msp <= &mstack[0]) ? E_UTC : E_UTM); } if (islower(c)) { c = toupper(c); } break; /* expanded constructs */ case CTL('E'): if (getcmdc(trace_sw) == term_char) { ERROR((msp <= &mstack[0]) ? E_UTC : E_UTM); } switch (mapch_l[cmdc & 0xFF]) { /* use char in q-reg */ case 'u': if (getcmdc(trace_sw) == term_char) ERROR((msp <= &mstack[0]) ? E_UTC : E_UTM); c = qreg[getqspec(1, cmdc)].v & 0x7f; break; /* use string in q-reg */ case 'q': if (getcmdc(trace_sw) == term_char) { ERROR((msp <= &mstack[0]) ? E_UTC : E_UTM); } /* read the reg spec */ ll = getqspec(1, cmdc); /* set a pointer to it */ aa.p = qreg[ll].f; aa.c = 0; for (mm = 0; mm < qreg[ll].z; mm++) { /* store char */ bb.p->ch[bb.c] = aa.p->ch[aa.c]; /* store next char */ fwdcx(&bb); fwdc(&aa); ++count; } /* * Repeat loop without * storing */ continue; default: /* not special: store the ^E */ bb.p->ch[bb.c] = CTL('E'); fwdcx(&bb); ++count; /* * And go store the following * char */ c = cmdc; break; } } } /* store character */ bb.p->ch[bb.c] = c; /* advance pointer */ fwdcx(&bb); /* count characters */ ++count; } free_blist(lbuff->f); /* return old buffer */ lbuff->f = tp; /* put in new one */ lbuff->f->b = (struct buffcell *) lbuff; /* store count of chars in string */ lbuff->z = count; } else { /* empty string: consume terminator */ getcmdc(trace_sw); } /* return char count */ return(count); }
string capitalFirst(string s) { if (!s.empty() && islower(s[0])) s[0] = toupper(s[0]); return s; }
ULONG MyInetAddr( IN LPWSTR String, OUT LPWSTR * Terminator ) /*++ Routine Description: This function interprets the character string specified by the cp parameter. This string represents a numeric Internet address expressed in the Internet standard ".'' notation. The value returned is a number suitable for use as an Internet address. All Internet addresses are returned in network order (bytes ordered from left to right). Internet Addresses Values specified using the "." notation take one of the following forms: a.b.c.d a.b.c a.b a When four parts are specified, each is interpreted as a byte of data and assigned, from left to right, to the four bytes of an Internet address. Note that when an Internet address is viewed as a 32-bit integer quantity on the Intel architecture, the bytes referred to above appear as "d.c.b.a''. That is, the bytes on an Intel processor are ordered from right to left. Note: The following notations are only used by Berkeley, and nowhere else on the Internet. In the interests of compatibility with their software, they are supported as specified. When a three part address is specified, the last part is interpreted as a 16-bit quantity and placed in the right most two bytes of the network address. This makes the three part address format convenient for specifying Class B network addresses as "128.net.host''. When a two part address is specified, the last part is interpreted as a 24-bit quantity and placed in the right most three bytes of the network address. This makes the two part address format convenient for specifying Class A network addresses as "net.host''. When only one part is given, the value is stored directly in the network address without any byte rearrangement. Arguments: String - A character string representing a number expressed in the Internet standard "." notation. Terminator - Receives a pointer to the character that terminated the conversion. Return Value: If no error occurs, inet_addr() returns an in_addr structure containing a suitable binary representation of the Internet address given. Otherwise, it returns the value INADDR_NONE. --*/ { ULONG val, base, n; WCHAR c; ULONG parts[4], *pp = parts; again: /* * Collect number up to ``.''. * Values are specified as for C: * 0x=hex, 0=octal, other=decimal. */ val = 0; base = 10; if (*String == L'0') { base = 8, String++; if (*String == L'x' || *String == L'X') base = 16, String++; } while (c = *String) { if (iswdigit(c)) { val = (val * base) + (c - L'0'); String++; continue; } if (base == 16 && iswxdigit(c)) { val = (val << 4) + (c + 10 - (islower(c) ? L'a' : L'A')); String++; continue; } break; } if (*String == L'.') { /* * Internet format: * a.b.c.d * a.b.c (with c treated as 16-bits) * a.b (with b treated as 24 bits) */ /* GSS - next line was corrected on 8/5/89, was 'parts + 4' */ if (pp >= parts + 3) { *Terminator = String; return ((ULONG) -1); } *pp++ = val, String++; goto again; } /* * Check for trailing characters. */ if (*String && !iswspace(*String) && (*String != L':')) { *Terminator = String; return (INADDR_NONE); } *pp++ = val; /* * Concoct the address according to * the number of parts specified. */ n = pp - parts; switch ((int) n) { case 1: /* a -- 32 bits */ val = parts[0]; break; case 2: /* a.b -- 8.24 bits */ if ((parts[0] > 0xff) || (parts[1] > 0xffffff)) { *Terminator = String; return(INADDR_NONE); } val = (parts[0] << 24) | (parts[1] & 0xffffff); break; case 3: /* a.b.c -- 8.8.16 bits */ if ((parts[0] > 0xff) || (parts[1] > 0xff) || (parts[2] > 0xffff)) { *Terminator = String; return(INADDR_NONE); } val = (parts[0] << 24) | ((parts[1] & 0xff) << 16) | (parts[2] & 0xffff); break; case 4: /* a.b.c.d -- 8.8.8.8 bits */ if ((parts[0] > 0xff) || (parts[1] > 0xff) || (parts[2] > 0xff) || (parts[3] > 0xff)) { *Terminator = String; return(INADDR_NONE); } val = (parts[0] << 24) | ((parts[1] & 0xff) << 16) | ((parts[2] & 0xff) << 8) | (parts[3] & 0xff); break; default: *Terminator = String; return (INADDR_NONE); } val = SWAP_LONG(val); *Terminator = String; return (val); }
static inline void axis_calc( const char* axis_name, double step_size_, double d, double double_s, double* ramp_d, double a, double* v, double* dwell_d, uint32_t* c0, uint32_t* cmin, double* recipr_t_acc, double* recipr_t_move) { if (d != 0.0) { char aname = *axis_name; if (islower( aname)) { aname = toupper( aname); } if (DEBUG_TRAJECT && (debug_flags & DEBUG_TRAJECT)) { printf( "%c move : ", aname); } if (d < double_s) { /* * Move length is too short to reach full speed. * Recalculate new (lower) top speed and remove the dwell. * * Ramp length becomes half the move length. */ if (DEBUG_TRAJECT && (debug_flags & DEBUG_TRAJECT)) { printf( "(can't reach full speed) "); } *v = sqrt( a * d); *ramp_d = 0.5 * d; *dwell_d = 0.0; *recipr_t_acc = *v / *ramp_d; } else { /* * Move has ramp up, constant velocity and ramp down phases */ *ramp_d = 0.5 * double_s; *dwell_d = d - double_s; } /* * Update the time it takes for the entire move to complete. * (All axes will generate the same duration). */ if (*recipr_t_move == 0.0) { *recipr_t_move = *v / (4 * *ramp_d + *dwell_d); if (DEBUG_TRAJECT && (debug_flags & DEBUG_TRAJECT)) { printf( "(set move duration to %1.3lf [ms]) ", SI2MS( RECIPR( *recipr_t_move))); } } if (d < step_size_) { /* * A move smaller than step_size will not always generate a step, * that depends on the current position and happens inside the PRU. * Moves much smaller than step_size will rarely step, but once * in a while, if a step border is crossed, a step pulse is generated. * This (full) step pulse however then runs at such a low velocity * that it comes late and with a cycle much larger than the complete * move. This manifests itself as a pause in gcode execution (the * single step that is made is very hard to detect). * The solution: If this (single) step is generated, it's best generated * in the center of the complete move. This result can be obtained * by raising the velocity so that the stepcycle takes exactly the * same amount of time as the complete move does. */ if (DEBUG_TRAJECT && (debug_flags & DEBUG_TRAJECT)) { printf( "(changed speed of possible single step) "); } *ramp_d = 0.0; *dwell_d = d; *v = step_size_ * *recipr_t_move; if (DEBUG_TRAJECT && (debug_flags & DEBUG_TRAJECT)) { printf( "\n no ramps, dwell= %3.6lf [mm], velocity= %3.3lf [mm/s], duration= %1.3lf [ms]\n", SI2MM( *dwell_d), SI2MM( *v), SI2MS( RECIPR( *recipr_t_move))); } *cmin = fclk * step_size_ / *v ; *c0 = *cmin; } else if (*ramp_d < step_size_) { /* * Replace a move with ramps that are too short to execute by * a single constant (slightly lower) velocity move. */ if (DEBUG_TRAJECT && (debug_flags & DEBUG_TRAJECT)) { printf( "(removed ramps smaller than stepsize) "); } *ramp_d = 0.0; *dwell_d = d; *v = *dwell_d * *recipr_t_move; if (DEBUG_TRAJECT && (debug_flags & DEBUG_TRAJECT)) { printf( "\n no ramps, dwell= %3.6lf [mm], velocity= %3.3lf [mm/s], duration= %1.3lf [ms]\n", SI2MM( *dwell_d), SI2MM( *v), SI2MS( RECIPR( *recipr_t_move))); } *cmin = fclk * step_size_ / *v ; *c0 = *cmin; } else { if (DEBUG_TRAJECT && (debug_flags & DEBUG_TRAJECT)) { printf( "\n ramp= %3.6lf [mm], dwell= %3.6lf [mm], velocity= %3.3lf [mm/s], duration= %1.3lf [ms]\n", SI2MM( *ramp_d), SI2MM( *dwell_d), SI2MM( *v), SI2MS( (4 * *ramp_d + *dwell_d) / *v)); } *cmin = fclk * step_size_ / *v ; *c0 = (uint32_t) (c_acc * sqrt( step_size_ / a)); if (*c0 < *cmin) { /* * Does this really happen? */ if (DEBUG_TRAJECT && (debug_flags & DEBUG_TRAJECT)) { printf( " *** motor can start at dwell speed, no acceleration needed (setting c0 to cmin)\n"); } *ramp_d = 0.0; *dwell_d = d; *v = *dwell_d * *recipr_t_move; if (DEBUG_TRAJECT && (debug_flags & DEBUG_TRAJECT)) { printf( " ramp: %3.6lf [mm], dwell: %3.6lf [mm], velocity: %3.3lf [mm/s], duration: %1.3lf [ms]\n", SI2MM( *ramp_d), SI2MM( *dwell_d), SI2MM( *v), SI2MS( (4 * *ramp_d + *dwell_d) / *v)); } *cmin = fclk * step_size_ / *v ; *c0 = *cmin; } } } else { /* * NOP */ *ramp_d = 0.0; *dwell_d = 0.0; *cmin = 0; *c0 = 0; } }
/* * Do format conversion placing the output in buffer */ static void xbuf_format_converter(smart_str *xbuf, const char *fmt, va_list ap) /* {{{ */ { char *s = NULL; int s_len, free_zcopy; zval *zvp, zcopy; int min_width = 0; int precision = 0; enum { LEFT, RIGHT } adjust; char pad_char; char prefix_char; double fp_num; wide_int i_num = (wide_int) 0; u_wide_int ui_num = (u_wide_int) 0; char num_buf[NUM_BUF_SIZE]; char char_buf[2]; /* for printing %% and %<unknown> */ #ifdef HAVE_LOCALE_H struct lconv *lconv = NULL; #endif /* * Flag variables */ length_modifier_e modifier; boolean_e alternate_form; boolean_e print_sign; boolean_e print_blank; boolean_e adjust_precision; boolean_e adjust_width; bool_int is_negative; while (*fmt) { if (*fmt != '%') { INS_CHAR(xbuf, *fmt); } else { /* * Default variable settings */ adjust = RIGHT; alternate_form = print_sign = print_blank = NO; pad_char = ' '; prefix_char = NUL; free_zcopy = 0; fmt++; /* * Try to avoid checking for flags, width or precision */ if (isascii((int)*fmt) && !islower((int)*fmt)) { /* * Recognize flags: -, #, BLANK, + */ for (;; fmt++) { if (*fmt == '-') adjust = LEFT; else if (*fmt == '+') print_sign = YES; else if (*fmt == '#') alternate_form = YES; else if (*fmt == ' ') print_blank = YES; else if (*fmt == '0') pad_char = '0'; else break; } /* * Check if a width was specified */ if (isdigit((int)*fmt)) { STR_TO_DEC(fmt, min_width); adjust_width = YES; } else if (*fmt == '*') { min_width = va_arg(ap, int); fmt++; adjust_width = YES; if (min_width < 0) { adjust = LEFT; min_width = -min_width; } } else adjust_width = NO; /* * Check if a precision was specified */ if (*fmt == '.') { adjust_precision = YES; fmt++; if (isdigit((int)*fmt)) { STR_TO_DEC(fmt, precision); } else if (*fmt == '*') { precision = va_arg(ap, int); fmt++; if (precision < 0) precision = 0; } else
/****************************************************************************** Interpret the command line and scan the given GIF file. ******************************************************************************/ int main(int argc, char **argv) { unsigned int Ratio; int i, l, LevelWidth, LogNumLevels, ErrorCode, Count = 0; bool Error, FlipDir, DoAllMaximum = false, DirectionFlag = false, LevelsFlag = false, ColorFlag = false, MinFlag = false, MaxFlag = false, SizeFlag = false, HelpFlag = false; GifPixelType Color; char *DirectionStr = DEFAULT_DIR; GifRowType Line; ColorMapObject *ColorMap; GifFileType *GifFile; if ((Error = GAGetArgs(argc, argv, CtrlStr, &GifNoisyPrint, &DirectionFlag, &DirectionStr, &LevelsFlag, &NumLevels, &ColorFlag, &RedColor, &GreenColor, &BlueColor, &MinFlag, &MinimumIntensity, &MaxFlag, &MaximumIntensity, &SizeFlag, &ImageWidth, &ImageHeight, &HelpFlag)) != false) { GAPrintErrMsg(Error); GAPrintHowTo(CtrlStr); exit(EXIT_FAILURE); } if (HelpFlag) { (void)fprintf(stderr, VersionStr, GIFLIB_MAJOR, GIFLIB_MINOR); GAPrintHowTo(CtrlStr); exit(EXIT_SUCCESS); } /* Make sure intensities are in the right range: */ if (MinimumIntensity < 0 || MinimumIntensity > 100 || MaximumIntensity < 0 || MaximumIntensity > 100) GIF_EXIT("Intensities (-m or -M options) are not in [0..100] range (percent)."); /* Convert DirectionStr to our local representation: */ Direction = DIR_NONE; FlipDir = false; /* Make sure it's upper case. */ for (i = 0; i < (int)strlen(DirectionStr); i++) if (islower(DirectionStr[i])) DirectionStr[i] = toupper(DirectionStr[i]); switch(DirectionStr[0]) { case 'T': /* Top or North */ case 'N': if (strlen(DirectionStr) < 2) Direction = DIR_TOP; else switch(DirectionStr[1]) { case 'R': case 'E': Direction = DIR_TOP_RIGHT; break; case 'L': case 'W': Direction = DIR_TOP_LEFT; FlipDir = true; break; } break; case 'R': /* Right or East */ case 'E': Direction = DIR_RIGHT; break; case 'B': /* Bottom or South */ case 'S': if (strlen(DirectionStr) < 2) { Direction = DIR_BOT; FlipDir = true; } else switch(DirectionStr[1]) { case 'R': case 'E': Direction = DIR_BOT_RIGHT; break; case 'L': case 'W': Direction = DIR_BOT_LEFT; FlipDir = true; break; } break; case 'L': /* Left or West */ case 'W': Direction = DIR_LEFT; FlipDir = true; break; } if (Direction == DIR_NONE) GIF_EXIT("Direction requested (-d option) is wierd!"); /* We are going to handle only TOP, TOP_RIGHT, RIGHT, BOT_RIGHT so flip */ /* the complement cases (TOP <-> BOT for example) by flipping the */ /* Color i with color (NumLevels - i - 1). */ if (FlipDir) { switch (Direction) { case DIR_BOT: Direction = DIR_TOP; break; case DIR_BOT_LEFT: Direction = DIR_TOP_RIGHT; break; case DIR_LEFT: Direction = DIR_RIGHT; break; case DIR_TOP_LEFT: Direction = DIR_BOT_RIGHT; break; } } /* If binary mask is requested (special case): */ if (MinimumIntensity == 100 && MaximumIntensity == 100 && NumLevels == 2) { MinimumIntensity = 0; DoAllMaximum = true; Direction = DIR_RIGHT; } /* Make sure colors are in the right range: */ if (RedColor > 255 || GreenColor > 255 || BlueColor > 255) GIF_EXIT("Colors are not in the ragne [0..255]."); /* Make sure number of levels is power of 2 (up to 8 bits per pixel). */ for (i = 1; i < 8; i++) if (NumLevels == (1 << i)) break; if (i == 8) GIF_EXIT("#Lvls (-l option) is not power of 2."); LogNumLevels = i; /* Open stdout for the output file: */ if ((GifFile = EGifOpenFileHandle(1, &ErrorCode)) == NULL) { PrintGifError(ErrorCode); exit(EXIT_FAILURE); } /* Dump out screen description with given size and generated color map: */ if ((ColorMap = GifMakeMapObject(NumLevels, NULL)) == NULL) GIF_EXIT("Failed to allocate memory required, aborted."); for (i = 1; i <= NumLevels; i++) { /* Ratio will be in the range of 0..100 for required intensity: */ Ratio = (MaximumIntensity * (i * (256 / NumLevels)) + MinimumIntensity * ((NumLevels - i) * (256 / NumLevels))) / 256; ColorMap->Colors[i-1].Red = (RedColor * Ratio) / 100; ColorMap->Colors[i-1].Green = (GreenColor * Ratio) / 100; ColorMap->Colors[i-1].Blue = (BlueColor * Ratio) / 100; } if (EGifPutScreenDesc(GifFile, ImageWidth, ImageHeight, LogNumLevels, 0, ColorMap) == GIF_ERROR) QuitGifError(GifFile); /* Dump out the image descriptor: */ if (EGifPutImageDesc(GifFile, 0, 0, ImageWidth, ImageHeight, false, NULL) == GIF_ERROR) QuitGifError(GifFile); GifQprintf("\n%s: Image 1 at (%d, %d) [%dx%d]: ", PROGRAM_NAME, GifFile->Image.Left, GifFile->Image.Top, GifFile->Image.Width, GifFile->Image.Height); /* Allocate one scan line twice as big as image is, as we are going to */ /* shift along it, while we dump the scan lines: */ if ((Line = (GifRowType) malloc(sizeof(GifPixelType) * ImageWidth * 2)) == NULL) GIF_EXIT("Failed to allocate memory required, aborted."); if (Direction == DIR_TOP) { int LevelHeight; /* We must evaluate the line each time level is changing: */ LevelHeight = ImageHeight / NumLevels; for (Color = NumLevels, i = l = 0; i < ImageHeight; i++) { if (i == l) { int j; /* Time to update the line to next color level: */ if (Color != 0) Color--; for (j = 0; j < ImageWidth; j++) Line[j] = (FlipDir ? NumLevels - Color - 1 : Color); l += LevelHeight; } if (EGifPutLine(GifFile, Line, ImageWidth) == GIF_ERROR) QuitGifError(GifFile); GifQprintf("\b\b\b\b%-4d", Count++); } } else if (Direction == DIR_RIGHT) { /* We pre-prepare the scan lines as going from color zero to maximum */ /* color and dump the same scan line Height times: */ /* Note this case should handle the Boolean Mask special case. */ LevelWidth = ImageWidth / NumLevels; if (DoAllMaximum) { /* Special case - do all in maximum color: */ for (i = 0; i < ImageWidth; i++) Line[i] = 1; } else { for (Color = i = 0, l = LevelWidth; i < ImageWidth; i++, l--) { if (l == 0) { l = LevelWidth; if (Color < NumLevels - 1) Color++; } Line[i] = (FlipDir ? NumLevels - Color - 1 : Color); } } for (i = 0; i < ImageHeight; i++) { /* coverity[uninit_use_in_call] */ if (EGifPutLine(GifFile, Line, ImageWidth) == GIF_ERROR) QuitGifError(GifFile); GifQprintf("\b\b\b\b%-4d", Count++); } } else { int Accumulator, StartX, StepX; /* We are in one of the TOP_RIGHT, BOT_RIGHT cases: we will */ /* initialize the Line with its double ImageWidth length from the */ /* minimum intensity to the maximum intensity and shift along it */ /* while we go along the image height. */ LevelWidth = ImageWidth * 2 / NumLevels; for (Color = i = 0, l = LevelWidth; i < ImageWidth * 2; i++, l--) { if (l == 0) { l = LevelWidth; if (Color < NumLevels - 1) Color++; } Line[i] = (FlipDir ? NumLevels - Color - 1 : Color); } /* We need to implement a DDA to know how much to shift Line while */ /* we go down along image height. we set the parameters for it now: */ Accumulator = 0; switch(Direction) { case DIR_TOP_RIGHT: StartX = ImageWidth; StepX = -1; break; case DIR_BOT_RIGHT: default: StartX = 0; StepX = 1; break; } /* Time to dump information out: */ for (i = 0; i < ImageHeight; i++) { if (EGifPutLine(GifFile, &Line[StartX], ImageWidth) == GIF_ERROR) QuitGifError(GifFile); GifQprintf("\b\b\b\b%-4d", Count++); if ((Accumulator += ImageWidth) > ImageHeight) { while (Accumulator > ImageHeight) { Accumulator -= ImageHeight; StartX += StepX; } if (Direction < 0) Direction = 0; if (Direction > ImageWidth) Direction = ImageWidth; } } } if (EGifCloseFile(GifFile, &ErrorCode) == GIF_ERROR) { PrintGifError(ErrorCode); if (GifFile != NULL) { EGifCloseFile(GifFile, NULL); } exit(EXIT_FAILURE); } return 0; }
u_long xatoi(const char *cp) { u_long val; char base; char c; /* * 0x=hex * 0=octal * isdigit=decimal */ c = *cp; if (!isdigit(c)) return 0; val = 0; base = 10; if (c == '0') { c = *++cp; if (c == 'x' || c == 'X') { base = 16; c = *++cp; } else base = 8; } for (;;) { #if 0 if (isascii(c) && isdigit(c)) { #else if (isdigit(c)) { #endif val = (val * base) + (c - '0'); c = *++cp; #if 0 } else if (base == 16 && isascii(c) && isxdigit(c)) { #else } else if (base == 16 && isxdigit(c)) { #endif val = (val << 4) | (c + 10 - (islower(c) ? 'a' : 'A')); c = *++cp; } else break; } return val; } void MemDump(void *mem, u_long len, u_char wordAccess) { u_long memaddr = (u_long)mem; u_long addr; u_long i = 0; u_char line[17]; /* character display buffer */ u_char j, k, l; u_char even = 1; u_short w = 0; SYS_DECL_LOCK; if (wordAccess) { memaddr &= ~0x1; /* make even */ len <<= 1; /* make double */ } memset(line, 0, sizeof(line)); l = 0; addr = memaddr & ~0x0f; if (len <= 0) return; SYS_LOCK(); /* not non-reentrant code but for clean display */ do { if ((addr & 0x0f) == 0) printf("%08lx ", addr); if (addr < memaddr) { printf(" "); line[l++] = ' '; } else { u_char b; if (wordAccess) { if (even) { w = *((u_short *)addr); b = (u_char)((w >> 8) & 0xff); even = 0; } else { b = (u_char)(w & 0xff); even = 1; } } else b = *((u_char *)addr); printf("%02x", (int)b); i++; //line[l++] =isspace(b) ? ' ' : (isprint(b) ? b : '.'); line[l++] = (b >= 0x20 && b <= 0x7e) ? b : '.'; }
const unsigned char * pcre_maketables(void) { unsigned char *yield, *p; int i; #ifndef DFTABLES yield = (unsigned char*)(pcre_malloc)(tables_length); #else yield = (unsigned char*)malloc(tables_length); #endif if (yield == NULL) return NULL; p = yield; /* First comes the lower casing table */ for (i = 0; i < 256; i++) *p++ = tolower(i); /* Next the case-flipping table */ for (i = 0; i < 256; i++) *p++ = islower(i)? toupper(i) : tolower(i); /* Then the character class tables. Don't try to be clever and save effort on exclusive ones - in some locales things may be different. Note that the table for "space" includes everything "isspace" gives, including VT in the default locale. This makes it work for the POSIX class [:space:]. Note also that it is possible for a character to be alnum or alpha without being lower or upper, such as "male and female ordinals" (\xAA and \xBA) in the fr_FR locale (at least under Debian Linux's locales as of 12/2005). So we must test for alnum specially. */ memset(p, 0, cbit_length); for (i = 0; i < 256; i++) { if (isdigit(i)) p[cbit_digit + i/8] |= 1 << (i&7); if (isupper(i)) p[cbit_upper + i/8] |= 1 << (i&7); if (islower(i)) p[cbit_lower + i/8] |= 1 << (i&7); if (isalnum(i)) p[cbit_word + i/8] |= 1 << (i&7); if (i == '_') p[cbit_word + i/8] |= 1 << (i&7); if (isspace(i)) p[cbit_space + i/8] |= 1 << (i&7); if (isxdigit(i))p[cbit_xdigit + i/8] |= 1 << (i&7); if (isgraph(i)) p[cbit_graph + i/8] |= 1 << (i&7); if (isprint(i)) p[cbit_print + i/8] |= 1 << (i&7); if (ispunct(i)) p[cbit_punct + i/8] |= 1 << (i&7); if (iscntrl(i)) p[cbit_cntrl + i/8] |= 1 << (i&7); } p += cbit_length; /* Finally, the character type table. In this, we exclude VT from the white space chars, because Perl doesn't recognize it as such for \s and for comments within regexes. */ for (i = 0; i < 256; i++) { int x = 0; if (i != 0x0b && isspace(i)) x += ctype_space; if (isalpha(i)) x += ctype_letter; if (isdigit(i)) x += ctype_digit; if (isxdigit(i)) x += ctype_xdigit; if (isalnum(i) || i == '_') x += ctype_word; /* Note: strchr includes the terminating zero in the characters it considers. In this instance, that is ok because we want binary zero to be flagged as a meta-character, which in this sense is any character that terminates a run of data characters. */ if (strchr("\\*+?{^.$|()[", i) != 0) x += ctype_meta; *p++ = x; } return yield; }
bool OnGossipSelectCode(Player* pPlayer, Creature* pCreature, uint32 uiSender, uint32 uiAction, const char * code) { pPlayer->PlayerTalkClass->ClearMenus(); if ( uiSender == GOSSIP_SENDER_MAIN ) { if(islower(code[0])) toupper(code[0]); if(passChecks(pPlayer, code)) { Player * pBounty = sObjectAccessor->FindPlayerByName(code); switch (uiAction) { case GOSSIP_ACTION_INFO_DEF+5: { if(hasCurrency(pPlayer, BOUNTY_PRICE_1, SET_CURRENCY)) { #if SET_CURRENCY != 2 CharacterDatabase.PExecute("INSERT INTO bounties VALUES('%u','20', '1')", pBounty->GetGUID()); #else CharacterDatabase.PExecute("INSERT INTO bounties VALUES('%u','1', '1')", pBounty->GetGUID()); #endif alertServer(code, 1); flagPlayer(code); pPlayer->CLOSE_GOSSIP_MENU(); } break; } case GOSSIP_ACTION_INFO_DEF+6: { if(hasCurrency(pPlayer, BOUNTY_PRICE_2, SET_CURRENCY)) { #if SET_CURRENCY != 2 CharacterDatabase.PExecute("INSERT INTO bounties VALUES('%u', '40', '2')", pBounty->GetGUID()); #else CharacterDatabase.PExecute("INSERT INTO bounties VALUES('%u', '3', '2')", pBounty->GetGUID()); #endif alertServer(code, 1); flagPlayer(code); pPlayer->CLOSE_GOSSIP_MENU(); } break; } case GOSSIP_ACTION_INFO_DEF+7: { if(hasCurrency(pPlayer, BOUNTY_PRICE_3, SET_CURRENCY)) { #if SET_CURRENCY != 2 CharacterDatabase.PExecute("INSERT INTO bounties VALUES('%u', '100', '3')", pBounty->GetGUID()); #else CharacterDatabase.PExecute("INSERT INTO bounties VALUES('%u', '5', '3')", pBounty->GetGUID()); #endif alertServer(code, 1); flagPlayer(code); pPlayer->CLOSE_GOSSIP_MENU(); } break; } case GOSSIP_ACTION_INFO_DEF+8: { if(hasCurrency(pPlayer, BOUNTY_PRICE_4, SET_CURRENCY)) { #if SET_CURRENCY != 2 CharacterDatabase.PExecute("INSERT INTO bounties VALUES('%u', '200', '4')", pBounty->GetGUID()); #else CharacterDatabase.PExecute("INSERT INTO bounties VALUES('%u', '10', '3')", pBounty->GetGUID()); #endif alertServer(code, 1); flagPlayer(code); pPlayer->CLOSE_GOSSIP_MENU(); } break; } } } else { pPlayer->CLOSE_GOSSIP_MENU(); } } return true; }
int iswlower(wint_t wc) { return islower(wc); }
/* * sam_create_file * Common code to create file in a SAM-FS filesystem. */ static int sam_create_file(char *path, int type, struct sam_stat *s_buf, size_t bufsize) { int copy; int fd; struct sam_perm_inode inode; struct sam_ioctl_idrestore idrestore; if (bufsize < sizeof (struct sam_stat)) { errno = EINVAL; return (-6); } memset(&idrestore, 0, sizeof (idrestore)); memset(&inode, 0, sizeof (inode)); inode.di.version = 1; inode.di.mode = ((s_buf->st_mode & S_IAMB) | S_IFREG); inode.di.uid = s_buf->st_uid; inode.di.gid = s_buf->st_gid; inode.di.rm.size = s_buf->st_size; inode.di.access_time.tv_sec = s_buf->st_atime; inode.di.modify_time.tv_sec = s_buf->st_mtime; inode.di.change_time.tv_sec = s_buf->st_ctime; inode.di.creation_time = (s_buf->creation_time == 0) ? time(NULL) : s_buf->creation_time; inode.di.attribute_time = time(NULL); inode.di.residence_time = time(NULL); /* Fill in archive information for each copy if any */ for (copy = 0; copy < MAX_ARCHIVE; copy++) { struct sam_copy_s *stat_ar_copy; sam_archive_info_t *ar; stat_ar_copy = &s_buf->copy[copy]; ar = &inode.ar.image[copy]; /* Verify valid media type */ if (type == SAM_MIGRATE_FILE) { if (stat_ar_copy->media[3] == '\0') { continue; } if (!(islower(stat_ar_copy->media[2]) || isdigit(stat_ar_copy->media[2]))) { errno = EINVAL; return (-2); } if (!(islower(stat_ar_copy->media[3]) || isdigit(stat_ar_copy->media[3]))) { errno = EINVAL; return (-2); } inode.di.media[copy] = (DT_THIRD_PARTY | (stat_ar_copy->media[3] & 0xff)); } else if (type == SAM_RESTORE_FILE) { int media; if (stat_ar_copy->vsn[0] == '\0') { continue; } ar->arch_flags |= SAR_size_block; media = nm_to_device(stat_ar_copy->media); if (media <= 0) { errno = EINVAL; return (-2); } inode.di.media[copy] = (media_t)media; if (media == DT_DISK) { ar->arch_flags |= SAR_diskarch; } } ar->file_offset = stat_ar_copy->offset; ar->n_vsns = 1; ar->creation_time = (stat_ar_copy->creation_time == 0) ? time(NULL) : stat_ar_copy->creation_time; ar->position_u = stat_ar_copy->position >> 32; ar->position = stat_ar_copy->position & 0xffffffff; if ((stat_ar_copy->vsn[0] == '\0') || strlen(stat_ar_copy->vsn) > (sizeof (vsn_t) -1)) { errno = EINVAL; return (-3); } memccpy(ar->vsn, stat_ar_copy->vsn, '\0', sizeof (vsn_t) - 1); inode.di.arch_status |= (1 << copy); } inode.di.status.b.archdone = TRUE; inode.di.status.b.offline = TRUE; if ((fd = open(path, O_CREAT | O_EXCL, s_buf->st_mode)) < 0) { return (-5); } idrestore.dp.ptr = &inode; if (ioctl(fd, F_IDRESTORE, &idrestore) < 0) { (void) close(fd); (void) unlink(path); return (-6); } (void) close(fd); return (0); }
int get_spell(int *sn, cptr p, cptr prompt, int *bn, bool known) { int i, num = 0; bool flag, redraw; char choice; event_type ke; char out_val[160]; int book = (*bn); int book_over = 0; int book_start = book; /* HACK -- spellcasting mode -- spell already selected */ if (spellcasting_spell > -1) { (*sn) = spellcasting_spell; spellcasting = FALSE; spellcasting_spell = -1; return (TRUE); } /* Assume no spells available */ (*sn) = -2; /* Check for available spells */ num = count_spells_in_book(book, &book_over); /* No "okay" spells */ if (!num) return (FALSE); /* Assume cancelled */ (*sn) = -1; /* Nothing chosen yet */ flag = FALSE; /* No redraw yet */ redraw = FALSE; /* Show the list */ if (auto_showlist) { /* Show list */ redraw = TRUE; /* Save the screen */ Term_save(); /* Display a list of spells */ print_spells(book); } /* Build a prompt (accept all spells) */ strnfmt(out_val, 78, "(%s %c-%c, *=List, ESC=exit) %s", p, I2A(0), I2A(num - 1), prompt); /* Get a spell from the user */ while (!flag && get_com_ex(out_val, &choice, &ke)) { /* Hack -- mouse */ if (choice == '\xff' && ke.index == 1) { choice = 'a' + ke.mousey - 2; } /* Enter by name */ if (choice == '@' || choice == '"') { int _sn, _bn; if (choice == '"') prompt_quote_hack = TRUE; /* XXX Lookup item by name */ if (get_spell_by_name(&_bn, &_sn, TRUE, FALSE, FALSE)) { book = _bn; i = _sn; flag = TRUE; } else { bell(); } continue; } /* Flip page */ if (choice == '/') { int book_new = book; int tmp = 0; /* End of list */ if (!(num = count_spells_in_book(book + book_over, &tmp))) { /* Set 0 */ book_new = book_start; tmp = 0; num = count_spells_in_book(book_new, &tmp); book_over = tmp; } /* Next book available */ else { /* Advance */ book_new = book + book_over; book_over = tmp; } /* Notice flip! */ if (book_new != book) { /* Set */ book = book_new; /* Re-Build a prompt (accept all spells) */ strnfmt(out_val, 78, "(%s %c-%c, *=List, ESC=exit) %s", p, I2A(0), I2A(num - 1), prompt); /* Must redraw list */ if (redraw) { /* Restore the screen */ Term_load(); Term_save(); /* Display a list of spells */ print_spells(book); } } /* Ask again */ continue; } /* Request redraw */ if ((choice == ' ') || (choice == '*') || (choice == '?')) { /* Show the list */ if (!redraw) { /* Show list */ redraw = TRUE; /* Save the screen */ Term_save(); /* Display a list of spells */ print_spells(book); } /* Hide the list */ else { /* Hide list */ redraw = FALSE; /* Restore the screen */ Term_load(); /* The screen is OK now */ section_icky_row = 0; section_icky_col = 0; /* Flush any events */ Flush_queue(); } /* Ask again */ continue; } /* hack for CAPITAL prayers (heal other) */ if (isupper(choice)) { i = (choice - 'A'); if (i >= num) i = -1; else if (!(spell_flag[(book * SPELLS_PER_BOOK + i)] & PY_SPELL_PROJECT)) i = -1; if (i != -1) i += SPELL_PROJECTED; } /* lowercase */ else if (islower(choice)) { i = A2I(choice); if (i >= num) i = -1; } /* not a letter */ else i = -1; /* Totally Illegal */ if (i < 0) { bell(); continue; } /* Stop the loop */ flag = TRUE; } /* Restore the screen */ if (redraw) { Term_load(); /* The screen is OK now */ section_icky_row = 0; section_icky_col = 0; /* Flush any events */ Flush_queue(); } /* Abort if needed */ if (!flag) return (FALSE); /* Save the choice */ (*sn) = i; (*bn) = book; /* Success */ return (TRUE); }
/** * Check whether "cp" is a valid ascii representation * of an IPv6 address and convert to a binary address. * Returns 1 if the address is valid, 0 if not. * * @param cp IPv6 address in ascii representation (e.g. "FF01::1") * @param addr pointer to which to save the ip address in network order * @return 1 if cp could be converted to addr, 0 on failure */ int ip6addr_aton(const char *cp, ip6_addr_t *addr) { u32_t addr_index, zero_blocks, current_block_index, current_block_value; const char *s; /* Count the number of colons, to count the number of blocks in a "::" sequence zero_blocks may be 1 even if there are no :: sequences */ zero_blocks = 8; for (s = cp; *s != 0; s++) { if (*s == ':') { zero_blocks--; } else if (!isxdigit(*s)) { break; } } /* parse each block */ addr_index = 0; current_block_index = 0; current_block_value = 0; for (s = cp; *s != 0; s++) { if (*s == ':') { if (addr) { if (current_block_index & 0x1) { addr->addr[addr_index++] |= current_block_value; } else { addr->addr[addr_index] = current_block_value << 16; } } current_block_index++; current_block_value = 0; if (current_block_index > 7) { /* address too long! */ return 0; } if (s[1] == ':') { if (s[2] == ':') { /* invalid format: three successive colons */ return 0; } s++; /* "::" found, set zeros */ while (zero_blocks > 0) { zero_blocks--; if (current_block_index & 0x1) { addr_index++; } else { if (addr) { addr->addr[addr_index] = 0; } } current_block_index++; if (current_block_index > 7) { /* address too long! */ return 0; } } } } else if (isxdigit(*s)) { /* add current digit */ current_block_value = (current_block_value << 4) + (isdigit(*s) ? *s - '0' : 10 + (islower(*s) ? *s - 'a' : *s - 'A')); } else { /* unexpected digit, space? CRLF? */ break; } } if (addr) { if (current_block_index & 0x1) { addr->addr[addr_index++] |= current_block_value; } else { addr->addr[addr_index] = current_block_value << 16; } } /* convert to network byte order. */ if (addr) { for (addr_index = 0; addr_index < 4; addr_index++) { addr->addr[addr_index] = htonl(addr->addr[addr_index]); } } if (current_block_index != 7) { return 0; } return 1; }
static inline int fnlower(int c) { return islower(c); }
/* * expanded search comparison * returns 1 if match, 0 if not */ static int srch_cmp(void) { int tq; /* q-reg name for ^EGq */ struct qp tqp; /* pointer to read q reg */ /* what is search character */ switch (mapch_l[sm.p->ch[sm.c & 0xFF] & 0xFF]) { /* match anything but following construct */ case CTL('N'): /* don't read past end of string */ if (sm.dot >= sm.z) { ERROR(E_ISS); } /* skip the ^N */ fwdc(&sm); return(!srch_cmp()); /* match any character */ case CTL('X'): return(1); /* take next char literally */ case CTL('Q'): case CTL('R'): /* don't read past end of string */ if (sm.dot >= sm.z) { ERROR(E_ISS); } /* skip the ^Q */ fwdc(&sm); return(*(pmap + sb.p->ch[sb.c]) == *(pmap + sm.p->ch[sm.c])); /* match any nonalphanumeric */ case CTL('S'): return(!isalnum(sb.p->ch[sb.c])); case CTL('E'): /* don't read past end of string */ if (sm.dot >= sm.z) ERROR(E_ISS); /* skip the ^E */ fwdc(&sm); switch (mapch_l[sm.p->ch[sm.c & 0xFF] & 0xFF]) { /* match any alpha */ case 'a': return(isalpha(sb.p->ch[sb.c])); /* match any nonalpha */ case 'b': return(!isalnum(sb.p->ch[sb.c])); /* rad50 symbol constituent */ case 'c': return(!isalnum(sb.p->ch[sb.c]) || (sb.p->ch[sb.c] == '$') || (sb.p->ch[sb.c] == '.')); /* digit */ case 'd': return(isdigit(sb.p->ch[sb.c])); /* line terminator LF, VT, FF, CR */ case 'l': return((sb.p->ch[sb.c] == LF) || (sb.p->ch[sb.c] == FF) || (sb.p->ch[sb.c] == CR) || (sb.p->ch[sb.c] == VT)); /* alphanumeric */ case 'r': return(isalnum(sb.p->ch[sb.c])); /* lower case */ case 'v': return(islower(sb.p->ch[sb.c])); /* upper case */ case 'w': return(isupper(sb.p->ch[sb.c])); /* any non-null string of spaces or tabs */ case 's': /* failure */ if (((sb.p->ch[sb.c]&0177) != ' ') && ((sb.p->ch[sb.c]&0177) != TAB)) { return(0); } /* skip remaining spaces or tabs */ for ( fwdc(&sb); ((sb.p->ch[sb.c]&0177) == ' ') || ((sb.p->ch[sb.c]&0177) == TAB); fwdc(&sb) ) { ; } /* * Back up one char (calling routine will * skip it) */ backc(&sb); return(1); /* success */ /* any char in specified q register */ case 'g': /* don't read past end of string */ if (sm.dot >= sm.z) { ERROR(E_ISS); } /* get to the next char */ fwdc(&sm); /* read q-reg spec */ tq = getqspec(1, sm.p->ch[sm.c]); for (tqp.dot = tqp.c = 0, tqp.p = qreg[tq].f; tqp.dot < qreg[tq].z; fwdc(&tqp)) { /* match */ if (*(pmap + tqp.p->ch[tqp.c]) == *(pmap + sb.p->ch[sb.c])) { return(1); } } return(0); /* fail */ default: ERROR(E_ISS); } default: return(*(pmap + sb.p->ch[sb.c]) == *(pmap + sm.p->ch[sm.c])); } }
static void prt_ctp(char *name) { int idx, i, mem; int first = 1; static const char *reg_names[] = { "upper", "lower", "alpha", "digit", "space", "cntrl", "punct", "graph", "print", "xdigit", "blank", NULL }; for (idx = 0; reg_names[idx] != NULL; idx++) { if (strcmp(name, reg_names[idx]) == 0) { break; } } if (reg_names[idx] == NULL) { return; } for (i = 0; i < CSSIZE; i++) { mem = 0; switch (idx) { case 0: mem = isupper(i); break; case 1: mem = islower(i); break; case 2: mem = isalpha(i); break; case 3: mem = isdigit(i); break; case 4: mem = isspace(i); break; case 5: mem = iscntrl(i); break; case 6: mem = ispunct(i); break; case 7: mem = isgraph(i); break; case 8: mem = isprint(i); break; case 9: mem = isxdigit(i); break; case 10: mem = isblank(i); break; } if (mem) { if (!first) { (void) putchar(';'); } first = 0; (void) printf("\""); outchar(i); (void) printf("\""); } } }
/* * Run an external script. * ask = 1 if first ask for confirmation. * s = scriptname, l=loginname, p=password. */ void runscript(int ask, const char *s, const char *l, const char *p) { int status; int n, i; int pipefd[2]; char buf[81]; char scr_lines[5]; char cmdline[128]; struct pollfd fds[2]; char *translated_cmdline; char *ptr; WIN *w; int done = 0; char *msg = _("Same as last"); char *username = _(" A - Username :"******" B - Password :"******" C - Name of script :"), *question = _("Change which setting? (Return to run, ESC to stop)"); if (ask) { w = mc_wopen(10, 5, 70, 10, BDOUBLE, stdattr, mfcolor, mbcolor, 0, 0, 1); mc_wtitle(w, TMID, _("Run a script")); mc_wputs(w, "\n"); mc_wprintf(w, "%s %s\n", username, scr_user[0] ? msg : ""); mc_wprintf(w, "%s %s\n", password, scr_passwd[0] ? msg : ""); mc_wprintf(w, "%s %s\n", name_of_script, scr_name); mc_wlocate(w, 4, 5); mc_wputs(w, question); mc_wredraw(w, 1); while (!done) { mc_wlocate(w, mbslen (question) + 5, 5); n = wxgetch(); if (islower(n)) n = toupper(n); switch (n) { case '\r': case '\n': if (scr_name[0] == '\0') { mc_wbell(); break; } mc_wclose(w, 1); done = 1; break; case 27: /* ESC */ mc_wclose(w, 1); return; case 'A': mc_wlocate(w, mbslen (username) + 1, 1); mc_wclreol(w); scr_user[0] = 0; mc_wgets(w, scr_user, 32, 32); break; case 'B': mc_wlocate(w, mbslen (password) + 1, 2); mc_wclreol(w); scr_passwd[0] = 0; mc_wgets(w, scr_passwd, 32, 32); break; case 'C': mc_wlocate(w, mbslen (name_of_script) + 1, 3); mc_wgets(w, scr_name, 32, 32); break; default: break; } } } else { strncpy(scr_user, l, sizeof(scr_user)); strncpy(scr_name, s, sizeof(scr_name)); strncpy(scr_passwd, p, sizeof(scr_passwd)); } sprintf(scr_lines, "%d", (int) lines); /* jl 13.09.97 */ /* Throw away status line if temporary */ if (tempst) { mc_wclose(st, 1); tempst = 0; st = NULL; } scriptname(scr_name); pipe(pipefd); if (mcd(P_SCRIPTDIR) < 0) return; snprintf(cmdline, sizeof(cmdline), "%s %s %s %s", P_SCRIPTPROG, scr_name, logfname, logfname[0]==0? "": homedir); switch (udpid = fork()) { case -1: werror(_("Out of memory: could not fork()")); close(pipefd[0]); close(pipefd[1]); mcd(""); return; case 0: /* Child */ dup2(portfd, 0); dup2(portfd, 1); dup2(pipefd[1], 2); close(pipefd[0]); close(pipefd[1]); for (n = 1; n < _NSIG; n++) signal(n, SIG_DFL); mc_setenv("LOGIN", scr_user); mc_setenv("PASS", scr_passwd); mc_setenv("TERMLIN", scr_lines); /* jl 13.09.97 */ translated_cmdline = translate(cmdline); if (translated_cmdline != NULL) { fastexec(translated_cmdline); free(translated_cmdline); } exit(1); default: /* Parent */ break; } setcbreak(1); /* Cbreak, no echo */ enab_sig(1, 0); /* But enable SIGINT */ signal(SIGINT, udcatch); close(pipefd[1]); /* pipe output from "runscript" program to terminal emulator */ fds[0].fd = pipefd[0]; /* runscript */ fds[0].events = POLLIN; fds[1].fd = STDIN_FILENO; /* stdin */ fds[1].events = POLLIN; script_running = 1; while (script_running && poll(fds, 2, -1) > 0) for (i = 0; i < 2; i++) { if (fds[i].revents & (POLLERR | POLLHUP | POLLNVAL)) script_running = 0; else if ((fds[i].revents & POLLIN) && (n = read(fds[i].fd, buf, sizeof(buf)-1)) > 0) { ptr = buf; while (n--) if (i) vt_send(*ptr++); else vt_out(*ptr++); timer_update(); mc_wflush(); } } /* Collect status, and clean up. */ m_wait(&status); enab_sig(0, 0); signal(SIGINT, SIG_IGN); setcbreak(2); /* Raw, no echo */ close(pipefd[0]); scriptname(""); mcd(""); }
void AsMixedCaseToUnderscores ( char *Buffer, char *Filename) { UINT32 Length; char *SubBuffer = Buffer; char *TokenEnd; char *TokenStart = NULL; char *SubString; UINT32 LineNumber = 1; UINT32 Count; /* * Examine the entire buffer (contains the entire file) * We are only interested in these tokens: * Escape sequences - ignore entire sequence * Single-quoted constants - ignore * Quoted strings - ignore entire string * Translation escape - starts with /,*,! * Decimal and hex numeric constants - ignore entire token * Entire uppercase token - ignore, it is a macro or define * Starts with underscore, then a lowercase or digit: convert */ while (*SubBuffer) { if (*SubBuffer == '\n') { LineNumber++; SubBuffer++; continue; } /* Ignore standard escape sequences (\n, \r, etc.) Not Hex or Octal escapes */ if (*SubBuffer == '\\') { SubBuffer += 2; continue; } /* Ignore single-quoted characters */ if (*SubBuffer == '\'') { SubBuffer += 3; continue; } /* Ignore standard double-quoted strings */ if (*SubBuffer == '"') { SubBuffer++; Count = 0; while (*SubBuffer != '"') { Count++; if ((!*SubBuffer) || (Count > 8192)) { printf ("Found an unterminated quoted string!, line %u: %s\n", LineNumber, Filename); return; } /* Handle escape sequences */ if (*SubBuffer == '\\') { SubBuffer++; } SubBuffer++; } SubBuffer++; continue; } /* * Check for translation escape string. It means to ignore * blocks of code during this code conversion. */ if ((SubBuffer[0] == '/') && (SubBuffer[1] == '*') && (SubBuffer[2] == '!')) { SubBuffer = strstr (SubBuffer, "!*/"); if (!SubBuffer) { printf ("Found an unterminated translation escape!, line %u: %s\n", LineNumber, Filename); return; } continue; } /* Ignore anything that starts with a number (0-9) */ if (isdigit ((int) *SubBuffer)) { /* Ignore hex constants */ if ((SubBuffer[0] == '0') && ((SubBuffer[1] == 'x') || (SubBuffer[1] == 'X'))) { SubBuffer += 2; } /* Skip over all digits, both decimal and hex */ while (isxdigit ((int) *SubBuffer)) { SubBuffer++; } TokenStart = NULL; continue; } /* * Check for fully upper case identifiers. These are usually macros * or defines. Allow decimal digits and embedded underscores. */ if (isupper ((int) *SubBuffer)) { SubString = SubBuffer + 1; while ((isupper ((int) *SubString)) || (isdigit ((int) *SubString)) || (*SubString == '_')) { SubString++; } /* * For the next character, anything other than a lower case * means that the identifier has terminated, and contains * exclusively Uppers/Digits/Underscores. Ignore the entire * identifier. */ if (!islower ((int) *SubString)) { SubBuffer = SubString + 1; continue; } } /* * These forms may indicate an identifier that can be converted: * <UpperCase><LowerCase> (Ax) * <UpperCase><Number> (An) */ if (isupper ((int) SubBuffer[0]) && ((islower ((int) SubBuffer[1])) || isdigit ((int) SubBuffer[1]))) { TokenStart = SubBuffer; SubBuffer++; while (1) { /* Walk over the lower case letters and decimal digits */ while (islower ((int) *SubBuffer) || isdigit ((int) *SubBuffer)) { SubBuffer++; } /* Check for end of line or end of token */ if (*SubBuffer == '\n') { LineNumber++; break; } if (*SubBuffer == ' ') { /* Check for form "Axx - " in a parameter header description */ while (*SubBuffer == ' ') { SubBuffer++; } SubBuffer--; if ((SubBuffer[1] == '-') && (SubBuffer[2] == ' ')) { if (TokenStart) { *TokenStart = (char) tolower ((int) *TokenStart); } } break; } /* * Ignore these combinations: * <Letter><Digit><UpperCase> * <Digit><Digit><UpperCase> * <Underscore><Digit><UpperCase> */ if (isdigit ((int) *SubBuffer)) { if (isalnum ((int) *(SubBuffer-1)) || *(SubBuffer-1) == '_') { break; } } /* Ignore token if next character is not uppercase or digit */ if (!isupper ((int) *SubBuffer) && !isdigit ((int) *SubBuffer)) { break; } /* * Form <UpperCase><LowerCaseLetters><UpperCase> (AxxB): * Convert leading character of the token to lower case */ if (TokenStart) { *TokenStart = (char) tolower ((int) *TokenStart); TokenStart = NULL; } /* Find the end of this identifier (token) */ TokenEnd = SubBuffer - 1; while ((isalnum ((int) *TokenEnd)) || (*TokenEnd == '_')) { TokenEnd++; } SubString = TokenEnd; Length = 0; while (*SubString != '\n') { /* * If we have at least two trailing spaces, we can get rid of * one to make up for the newly inserted underscore. This will * help preserve the alignment of the text */ if ((SubString[0] == ' ') && (SubString[1] == ' ')) { Length = SubString - SubBuffer - 1; break; } SubString++; } if (!Length) { Length = strlen (&SubBuffer[0]); } /* * Within this identifier, convert this pair of letters that * matches the form: * * <LowerCase><UpperCase> * to * <LowerCase><Underscore><LowerCase> */ Gbl_MadeChanges = TRUE; /* Insert the underscore */ memmove (&SubBuffer[1], &SubBuffer[0], Length + 1); SubBuffer[0] = '_'; /* * If we have <UpperCase><UpperCase>, leave them as-is * Enables transforms like: * LocalFADT -> local_FADT */ if (isupper ((int) SubBuffer[2])) { SubBuffer += 1; break; } /* Lower case the original upper case letter */ SubBuffer[1] = (char) tolower ((int) SubBuffer[1]); SubBuffer += 2; } } SubBuffer++; } }
char *expand_format (char c, int quote) { WPanel *panel; char *(*quote_func)(const char *, int); if (quote) quote_func = name_quote; else quote_func = fake_name_quote; if (c == '%') return strdup ("%"); if (islower (c)) panel = cpanel; else { if (get_other_type () == view_listing){ panel = other_panel; } else return strdup (""); } if (!panel) panel = cpanel; c = tolower (c); switch (c){ case 'f': case 'p': return (*quote_func) (panel->dir.list [panel->selected].fname, 0); case 'b': return strip_ext((*quote_func) (panel->dir.list [panel->selected].fname, 0)); case 'd': return (*quote_func) (panel->cwd, 0); case 's': if (!panel->marked) return (*quote_func) (panel->dir.list [panel->selected].fname, 0); /* Fall through */ case 't': case 'u': { int length = 2, i; char *block, *tmp; for (i = 0; i < panel->count; i++) if (panel->dir.list [i].f.marked) length += strlen (panel->dir.list [i].fname) + 1; block = xmalloc (length*2+1, "expand_format"); *block = 0; for (i = 0; i < panel->count; i++) if (panel->dir.list [i].f.marked){ strcat (block, tmp = (*quote_func) (panel->dir.list [i].fname, 0)); free (tmp); strcat (block, " "); if (c == 'u') do_file_mark (panel, i, 0); } return block; } /* sub case block */ } /* switch */ return strdup (""); }
void AsLowerCaseIdentifiers ( char *Buffer) { char *SubBuffer = Buffer; while (*SubBuffer) { /* * Check for translation escape string -- means to ignore * blocks of code while replacing */ if ((SubBuffer[0] == '/') && (SubBuffer[1] == '*') && (SubBuffer[2] == '!')) { SubBuffer = strstr (SubBuffer, "!*/"); if (!SubBuffer) { return; } } /* Ignore comments */ if ((SubBuffer[0] == '/') && (SubBuffer[1] == '*')) { SubBuffer = strstr (SubBuffer, "*/"); if (!SubBuffer) { return; } SubBuffer += 2; } /* Ignore quoted strings */ if ((SubBuffer[0] == '\"') && (SubBuffer[1] != '\'')) { SubBuffer++; /* Find the closing quote */ while (SubBuffer[0]) { /* Ignore escaped quote characters */ if (SubBuffer[0] == '\\') { SubBuffer++; } else if (SubBuffer[0] == '\"') { SubBuffer++; break; } SubBuffer++; } } if (!SubBuffer[0]) { return; } /* * Only lower case if we have an upper followed by a lower * This leaves the all-uppercase things (macros, etc.) intact */ if ((isupper ((int) SubBuffer[0])) && (islower ((int) SubBuffer[1]))) { Gbl_MadeChanges = TRUE; *SubBuffer = (char) tolower ((int) *SubBuffer); } SubBuffer++; } }
static boolean change_spell_order(const char *op, boolean checkonly) { char buf[52]; int i, b = 0; const char *c; char d; int state; /* 0 = starting state */ /* 1 = got letter */ /* 2 = got '-' */ char last; /* Can't use strchr() since buf[] isn't null terminated. */ #define sporder_append_nodup(ch) \ do { \ for (i = 0; i < b; i++) \ if ((ch) == buf[i]) break; \ if (i == b) \ buf[b++] = (ch); \ } while (0) /* spellorder can accept letters and letter ranges e.g. "a-zA-Z" */ /* Ranges can also overlap or go backwards, but must be the same case. */ state = 0; last = '\0'; for (c = op; *c && b < 52; c++) { const char cur = *c; if (('a' <= cur && cur <= 'z') || ('A' <= cur && cur <= 'Z')) { if (state == 0) { last = cur; state = 1; } else if (state == 1) { sporder_append_nodup(last); c--; /* redo this letter */ state = 0; } else if (state == 2) { char tmp; if ((isupper((uchar)cur) && islower((uchar)last)) || (islower((uchar)cur) && isupper((uchar)last))) return FALSE; if (cur >= last) { for (tmp = last; tmp <= cur; tmp++) sporder_append_nodup(tmp); } else { for (tmp = last; tmp >= cur; tmp--) sporder_append_nodup(tmp); } state = 0; } } else if (cur == '-') { if (state == 1) state = 2; else return FALSE; } else { return FALSE; } } if (state == 1) sporder_append_nodup(last); else if (state != 0) return FALSE; /* fill the rest with default letters, lowercase then uppercase */ for (d = 'a'; d <= 'z' && b < 52; d++) sporder_append_nodup(d); for (d = 'A'; d <= 'Z' && b < 52; d++) sporder_append_nodup(d); #undef sporder_append_nodup if (!checkonly) { for (i = 0; i < 52; i++) flags.spell_order[i] = buf[i]; } return TRUE; }
void AsUppercaseTokens ( char *Buffer, char *PrefixString) { char *SubBuffer; char *TokenEnd; char *SubString; int i; UINT32 Length; SubBuffer = Buffer; while (SubBuffer) { SubBuffer = strstr (SubBuffer, PrefixString); if (SubBuffer) { TokenEnd = SubBuffer; while ((isalnum ((int) *TokenEnd)) || (*TokenEnd == '_')) { TokenEnd++; } for (i = 0; i < (TokenEnd - SubBuffer); i++) { if ((islower ((int) SubBuffer[i])) && (isupper ((int) SubBuffer[i+1]))) { SubString = TokenEnd; Length = 0; while (*SubString != '\n') { if ((SubString[0] == ' ') && (SubString[1] == ' ')) { Length = SubString - &SubBuffer[i] - 2; break; } SubString++; } if (!Length) { Length = strlen (&SubBuffer[i+1]); } memmove (&SubBuffer[i+2], &SubBuffer[i+1], (Length+1)); SubBuffer[i+1] = '_'; i +=2; TokenEnd++; } } for (i = 0; i < (TokenEnd - SubBuffer); i++) { SubBuffer[i] = (char) toupper ((int) SubBuffer[i]); } SubBuffer = TokenEnd; } } }
/* * Let the user select an item, save its "index" * * Return TRUE only if an acceptable item was chosen by the user. * * The selected item must satisfy the "item_tester_hook()" function, * if that hook is set, and the "item_tester_tval", if that value is set. * * All "item_tester" restrictions are cleared before this function returns. * * The user is allowed to choose acceptable items from the equipment, * inventory, or floor, respectively, if the proper flag was given, * and there are any acceptable items in that location. * * The equipment or inventory are displayed (even if no acceptable * items are in that location) if the proper flag was given. * * If there are no acceptable items available anywhere, and "str" is * not NULL, then it will be used as the text of a warning message * before the function returns. * * Note that the user must press "-" to specify the item on the floor, * and there is no way to "examine" the item on the floor, while the * use of "capital" letters will "examine" an inventory/equipment item, * and prompt for its use. * * If a legal item is selected from the inventory, we save it in "cp" * directly (0 to 35), and return TRUE. * * If a legal item is selected from the floor, we save it in "cp" as * a negative (-1 to -511), and return TRUE. * * If no item is available, we do nothing to "cp", and we display a * warning message, using "str" if available, and return FALSE. * * If no item is selected, we do nothing to "cp", and return FALSE. * * Global "p_ptr->command_wrk" is used to choose between equip/inven/floor * listings. It is equal to USE_INVEN or USE_EQUIP or USE_FLOOR, except * when this function is first called, when it is equal to zero, which will * cause it to be set to USE_INVEN. * * We always erase the prompt when we are done, leaving a blank line, * or a warning message, if appropriate, if no items are available. * * Note that only "acceptable" floor objects get indexes, so between two * commands, the indexes of floor objects may change. XXX XXX XXX */ bool get_item(int *cp, cptr pmt, cptr str, cmd_code cmd, int mode) { int py = p_ptr->py; int px = p_ptr->px; unsigned char cmdkey = cmd_lookup_key(cmd); ui_event_data which; int j, k; int i1, i2; int e1, e2; int f1, f2; bool done, item; bool oops = FALSE; bool use_inven = ((mode & USE_INVEN) ? TRUE : FALSE); bool use_equip = ((mode & USE_EQUIP) ? TRUE : FALSE); bool use_floor = ((mode & USE_FLOOR) ? TRUE : FALSE); bool use_quiver = ((mode & QUIVER_TAGS) ? TRUE : FALSE); bool is_harmless = ((mode & IS_HARMLESS) ? TRUE : FALSE); bool quiver_tags = ((mode & QUIVER_TAGS) ? TRUE : FALSE); olist_detail_t olist_mode = 0; bool allow_inven = FALSE; bool allow_equip = FALSE; bool allow_floor = FALSE; bool toggle = FALSE; char tmp_val[160]; char out_val[160]; int floor_list[MAX_FLOOR_STACK]; int floor_num; bool show_list = TRUE; /* Object list display modes */ if (mode & SHOW_FAIL) olist_mode |= (OLIST_FAIL); else olist_mode |= (OLIST_WEIGHT); if (mode & SHOW_PRICES) olist_mode |= (OLIST_PRICE); /* Paranoia XXX XXX XXX */ message_flush(); /* Not done */ done = FALSE; /* No item selected */ item = FALSE; /* Full inventory */ i1 = 0; i2 = INVEN_PACK - 1; /* Forbid inventory */ if (!use_inven) i2 = -1; /* Restrict inventory indexes */ while ((i1 <= i2) && (!get_item_okay(i1))) i1++; while ((i1 <= i2) && (!get_item_okay(i2))) i2--; /* Accept inventory */ if (i1 <= i2) allow_inven = TRUE; /* Full equipment */ e1 = INVEN_WIELD; e2 = ALL_INVEN_TOTAL - 1; /* Forbid equipment */ if (!use_equip) e2 = -1; /* Restrict equipment indexes */ while ((e1 <= e2) && (!get_item_okay(e1))) e1++; while ((e1 <= e2) && (!get_item_okay(e2))) e2--; /* Accept equipment */ if (e1 <= e2) allow_equip = TRUE; /* Scan all non-gold objects in the grid */ floor_num = scan_floor(floor_list, N_ELEMENTS(floor_list), py, px, 0x03); /* Full floor */ f1 = 0; f2 = floor_num - 1; /* Forbid floor */ if (!use_floor) f2 = -1; /* Restrict floor indexes */ while ((f1 <= f2) && (!get_item_okay(0 - floor_list[f1]))) f1++; while ((f1 <= f2) && (!get_item_okay(0 - floor_list[f2]))) f2--; /* Accept floor */ if (f1 <= f2) allow_floor = TRUE; /* Require at least one legal choice */ if (!allow_inven && !allow_equip && !allow_floor) { /* Oops */ oops = TRUE; done = TRUE; } /* Analyze choices */ else { /* Hack -- Start on equipment if requested */ if ((p_ptr->command_wrk == USE_EQUIP) && use_equip) p_ptr->command_wrk = USE_EQUIP; /* If we are using the quiver then start on equipment */ else if (use_quiver) p_ptr->command_wrk = USE_EQUIP; /* Use inventory if allowed */ else if (use_inven) p_ptr->command_wrk = USE_INVEN; /* Use equipment if allowed */ else if (use_equip) p_ptr->command_wrk = USE_EQUIP; /* Use floor if allowed */ else if (use_floor) p_ptr->command_wrk = USE_FLOOR; /* Hack -- Use (empty) inventory */ else p_ptr->command_wrk = USE_INVEN; } /* Start out in "display" mode */ if (show_list) { /* Save screen */ screen_save(); } /* Repeat until done */ while (!done) { int ni = 0; int ne = 0; /* Scan windows */ for (j = 0; j < REPOSBAND_TERM_MAX; j++) { /* Unused */ if (!reposband_term[j]) continue; /* Count windows displaying inven */ if (op_ptr->window_flag[j] & (PW_INVEN)) ni++; /* Count windows displaying equip */ if (op_ptr->window_flag[j] & (PW_EQUIP)) ne++; } /* Toggle if needed */ if (((p_ptr->command_wrk == USE_EQUIP) && ni && !ne) || ((p_ptr->command_wrk == USE_INVEN) && !ni && ne)) { /* Toggle */ toggle_inven_equip(); /* Track toggles */ toggle = !toggle; } /* Redraw */ p_ptr->redraw |= (PR_INVEN | PR_EQUIP); /* Redraw windows */ redraw_stuff(); /* Viewing inventory */ if (p_ptr->command_wrk == USE_INVEN) { /* Redraw if needed */ if (show_list) show_inven(olist_mode); /* Begin the prompt */ strnfmt(out_val, sizeof(out_val), "Inven:"); /* List choices */ if (i1 <= i2) { /* Build the prompt */ strnfmt(tmp_val, sizeof(tmp_val), " %c-%c,", index_to_label(i1), index_to_label(i2)); /* Append */ my_strcat(out_val, tmp_val, sizeof(out_val)); } /* Indicate ability to "view" */ if (!show_list) { my_strcat(out_val, " * to see,", sizeof(out_val)); button_add("[*]", '*'); } /* Indicate legality of "toggle" */ if (use_equip) { my_strcat(out_val, " / for Equip,", sizeof(out_val)); button_add("[/]", '/'); } /* Indicate legality of the "floor" */ if (allow_floor) { my_strcat(out_val, " - for floor,", sizeof(out_val)); button_add("[-]", '-'); } } /* Viewing equipment */ else if (p_ptr->command_wrk == USE_EQUIP) { /* Redraw if needed */ if (show_list) show_equip(olist_mode); /* Begin the prompt */ strnfmt(out_val, sizeof(out_val), "Equip:"); /* List choices */ if (e1 <= e2) { /* Build the prompt */ strnfmt(tmp_val, sizeof(tmp_val), " %c-%c,", index_to_label(e1), index_to_label(e2)); /* Append */ my_strcat(out_val, tmp_val, sizeof(out_val)); } /* Indicate ability to "view" */ if (!show_list) { my_strcat(out_val, " * to see,", sizeof(out_val)); button_add("[*]", '*'); } /* Indicate legality of "toggle" */ if (use_inven) { my_strcat(out_val, " / for Inven,", sizeof(out_val)); button_add("[/]", '/'); } /* Indicate legality of the "floor" */ if (allow_floor) { my_strcat(out_val, " - for floor,", sizeof(out_val)); button_add("[!]", '!'); } } /* Viewing floor */ else { /* Redraw if needed */ if (show_list) show_floor(floor_list, floor_num, olist_mode); /* Begin the prompt */ strnfmt(out_val, sizeof(out_val), "Floor:"); /* List choices */ if (f1 <= f2) { /* Build the prompt */ strnfmt(tmp_val, sizeof(tmp_val), " %c-%c,", I2A(f1), I2A(f2)); /* Append */ my_strcat(out_val, tmp_val, sizeof(out_val)); } /* Indicate ability to "view" */ if (!show_list) { my_strcat(out_val, " * to see,", sizeof(out_val)); button_add("[*]", '*'); } /* Append */ if (use_inven) { my_strcat(out_val, " / for Inven,", sizeof(out_val)); button_add("[/]", '/'); } /* Append */ else if (use_equip) { my_strcat(out_val, " / for Equip,", sizeof(out_val)); button_add("[/]", '/'); } } redraw_stuff(); /* Finish the prompt */ my_strcat(out_val, " ESC", sizeof(out_val)); /* Build the prompt */ strnfmt(tmp_val, sizeof(tmp_val), "(%s) %s", out_val, pmt); /* Show the prompt */ prt(tmp_val, 0, 0); /* Get a key */ which = inkey_ex(); /* Parse it */ switch (which.key) { case ESCAPE: { done = TRUE; break; } case '/': { /* Toggle to inventory */ if (use_inven && (p_ptr->command_wrk != USE_INVEN)) { p_ptr->command_wrk = USE_INVEN; } /* Toggle to equipment */ else if (use_equip && (p_ptr->command_wrk != USE_EQUIP)) { p_ptr->command_wrk = USE_EQUIP; } /* No toggle allowed */ else { bell("Cannot switch item selector!"); break; } /* Hack -- Fix screen */ if (show_list) { /* Load screen */ screen_load(); /* Save screen */ screen_save(); } /* Need to redraw */ break; } case '-': { /* Paranoia */ if (!allow_floor) { bell("Cannot select floor!"); break; } /* There is only one item */ if (floor_num == 1) { /* Auto-select */ if (p_ptr->command_wrk == (USE_FLOOR)) { /* Special index */ k = 0 - floor_list[0]; /* Allow player to "refuse" certain actions */ if (!get_item_allow(k, cmdkey, is_harmless)) { done = TRUE; break; } /* Accept that choice */ (*cp) = k; item = TRUE; done = TRUE; break; } } /* Hack -- Fix screen */ if (show_list) { /* Load screen */ screen_load(); /* Save screen */ screen_save(); } p_ptr->command_wrk = (USE_FLOOR); #if 0 /* Check each legal object */ for (i = 0; i < floor_num; ++i) { /* Special index */ k = 0 - floor_list[i]; /* Skip non-okay objects */ if (!get_item_okay(k)) continue; /* Allow player to "refuse" certain actions */ if (!get_item_allow(k, cmdkey, is_harmless)) continue; /* Accept that choice */ (*cp) = k; item = TRUE; done = TRUE; break; } #endif break; } case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { /* Look up the tag */ if (!get_tag(&k, which.key, cmd, quiver_tags)) { bell("Illegal object choice (tag)!"); break; } /* Hack -- Validate the item */ if ((k < INVEN_WIELD) ? !allow_inven : !allow_equip) { bell("Illegal object choice (tag)!"); break; } /* Validate the item */ if (!get_item_okay(k)) { bell("Illegal object choice (tag)!"); break; } /* Allow player to "refuse" certain actions */ if (!get_item_allow(k, cmdkey, is_harmless)) { done = TRUE; break; } /* Accept that choice */ (*cp) = k; item = TRUE; done = TRUE; break; } case '\n': case '\r': { /* Choose "default" inventory item */ if (p_ptr->command_wrk == USE_INVEN) { if (i1 != i2) { bell("Illegal object choice (default)!"); break; } k = i1; } /* Choose the "default" slot (0) of the quiver */ else if (quiver_tags) k = e1; /* Choose "default" equipment item */ else if (p_ptr->command_wrk == USE_EQUIP) { if (e1 != e2) { bell("Illegal object choice (default)!"); break; } k = e1; } /* Choose "default" floor item */ else { if (f1 != f2) { bell("Illegal object choice (default)!"); break; } k = 0 - floor_list[f1]; } /* Validate the item */ if (!get_item_okay(k)) { bell("Illegal object choice (default)!"); break; } /* Allow player to "refuse" certain actions */ if (!get_item_allow(k, cmdkey, is_harmless)) { done = TRUE; break; } /* Accept that choice */ (*cp) = k; item = TRUE; done = TRUE; break; } default: { bool verify; /* Note verify */ verify = (isupper((unsigned char)which.key) ? TRUE : FALSE); /* Lowercase */ which.key = tolower((unsigned char)which.key); /* Convert letter to inventory index */ if (p_ptr->command_wrk == USE_INVEN) { k = label_to_inven(which.key); if (k < 0) { bell("Illegal object choice (inven)!"); break; } } /* Convert letter to equipment index */ else if (p_ptr->command_wrk == USE_EQUIP) { k = label_to_equip(which.key); if (k < 0) { bell("Illegal object choice (equip)!"); break; } } /* Convert letter to floor index */ else { k = (islower((unsigned char)which.key) ? A2I(which.key) : -1); if (k < 0 || k >= floor_num) { bell("Illegal object choice (floor)!"); break; } /* Special index */ k = 0 - floor_list[k]; } /* Validate the item */ if (!get_item_okay(k)) { bell("Illegal object choice (normal)!"); break; } /* Verify the item */ if (verify && !verify_item("Try", k)) { done = TRUE; break; } /* Allow player to "refuse" certain actions */ if (!get_item_allow(k, cmdkey, is_harmless)) { done = TRUE; break; } /* Accept that choice */ (*cp) = k; item = TRUE; done = TRUE; break; } } } /* Fix the screen if necessary */ if (show_list) { /* Load screen */ screen_load(); /* Hack -- Cancel "display" */ show_list = FALSE; } /* Kill buttons */ button_kill('*'); button_kill('/'); button_kill('-'); button_kill('!'); redraw_stuff(); /* Forget the item_tester_tval restriction */ item_tester_tval = 0; /* Forget the item_tester_hook restriction */ item_tester_hook = NULL; /* Toggle again if needed */ if (toggle) toggle_inven_equip(); /* Update */ p_ptr->redraw |= (PR_INVEN | PR_EQUIP); redraw_stuff(); /* Clear the prompt line */ prt("", 0, 0); /* Warning if needed */ if (oops && str) msg_print(str); /* Result */ return (item); }
static void pa_ip( char *str) { char *s; const char *args; char c; unsigned long i; struct pa_opcode *insn; char *argsStart; unsigned long opcode; int match = FALSE; int comma = 0; int reg,reg1,reg2,s2,s3; unsigned int im21,im14,im11,im5; int m,a,u,f; int cmpltr,nullif, flag; int sfu, cond; char *name; char *save_s, *p; short reference; reference = 0; #ifdef PA_DEBUG fprintf(stderr,"STATEMENT: \"%s\"\n",str); #endif for (s = str; isupper(*s) || islower(*s) || (*s >= '0' && *s <= '3'); ++s) ; switch (*s) { case '\0': break; case ',': comma = 1; /*FALLTHROUGH*/ case ' ': *s++ = '\0'; break; default: as_bad("Unknown opcode: `%s'", str); exit(1); } save_s = str; while ( *save_s ) { if ( isupper(*save_s) ) *save_s = tolower(*save_s); save_s++; } if ((insn = (struct pa_opcode *) hash_find(op_hash, str)) == NULL) { as_bad("Unknown opcode: `%s'", str); return; } if (comma) { *--s = ','; } argsStart = s; for (;;) { opcode = insn->match; memset(&the_insn, '\0', sizeof(the_insn)); the_insn.reloc = NO_RELOC; /* USV */ /* * Build the opcode, checking as we go to make * sure that the operands match */ for (args = insn->args; ; ++args) { switch (*args) { case '\0': /* end of args */ if (*s == '\0') { match = TRUE; } break; case '(': /* these must match exactly */ case ')': case ',': case ' ': if (*s++ == *args) continue; break; case 'b': /* 5 bit register field at 10 */ reg = pa_parse_number(&s); if ( reg < 32 && reg >= 0 ) { opcode |= reg << 21; continue; } break; case 'x': /* 5 bit register field at 15 */ reg = pa_parse_number(&s); if ( reg < 32 && reg >= 0 ) { opcode |= reg << 16; continue; } break; case 't': /* 5 bit register field at 31 */ reg = pa_parse_number(&s); if ( reg < 32 && reg >= 0 ) { opcode |= reg; continue; } break; case 'T': /* 5 bit field length at 31 (encoded as 32-T) */ /* reg = pa_parse_number(&s); */ getAbsoluteExpression(s); if ( the_insn.exp.X_seg == SEG_ABSOLUTE ) { reg = the_insn.exp.X_add_number; if ( reg <= 32 && reg > 0 ) { opcode |= 32 - reg; s = expr_end; continue; } } break; case '5': /* 5 bit immediate at 15 */ getAbsoluteExpression(s); /** PJH: The following 2 calls to as_bad() might eventually **/ /** want to end up as as_warn(). **/ if ( the_insn.exp.X_add_number > 15 ) { as_bad("5 bit immediate: %lld" " > 15. Set to 15", the_insn.exp.X_add_number); the_insn.exp.X_add_number = 15; } else if ( the_insn.exp.X_add_number < -16 ) { as_bad("5 bit immediate: " "%lld < -16. Set to -16", the_insn.exp.X_add_number); the_insn.exp.X_add_number = -16; } im5 = low_sign_unext(evaluateAbsolute( the_insn.exp,0),5); opcode |= ( im5 << 16 ); s = expr_end; continue; case 's': /* 2 bit space identifier at 17 */ s2 = pa_parse_number(&s); if ( s2 < 4 && s2 >= 0 ) { opcode |= s2 << 14; continue; } break; case 'S': /* 3 bit space identifier at 18 */ s3 = pa_parse_number(&s); if ( s3 < 8 && s3 >= 0 ) { s3 = dis_assemble_3(s3); opcode |= s3 << 13; continue; } break; case 'c': /* indexed load completer. */ i = m = u = 0; while ( *s == ',' && i < 2 ) { s++; if ( strncasecmp(s,"sm",2) == 0 ) { m = u = 1; s++; i++; } else if ( strncasecmp(s,"m",1) == 0 ) m = 1; else if ( strncasecmp(s,"s",1) == 0 ) u = 1; else as_bad("Unrecognized Indexed Load" "Completer...assuming 0"); s++; i++; } if ( i > 2 ) as_bad("Illegal Indexed Load Completer Syntax..." "extras ignored"); while ( *s == ' ' || *s == '\t' ) s++; opcode |= m << 5; opcode |= u << 13; continue; case 'C': /* short load and store completer */ m = a = 0; if ( *s == ',' ) { s++; if ( strncasecmp(s,"ma",2) == 0 ) { a = 0; m = 1; } else if ( strncasecmp(s,"mb",2) == 0 ) { m = a = 1; } else as_bad("Unrecognized Indexed Load Completer" "...assuming 0"); s += 2; } while ( *s == ' ' || *s == '\t' ) s++; opcode |= m << 5; opcode |= a << 13; continue; /* bug #41317 .... [email protected] * Fri Jul 22 09:43:46 PDT 1994 * * Modified to parse 'cache control hints' * * These parse ",cc" and encode "cc" in 2 bits at 20, * where "cc" encoding is as given in Tables 5-8, 5-9. * Refer to 'PA-RISC 1.1 Architecture and Instruction Set * Reference Manual, Second Edition' for the tables. */ case 'Y': /* Store Bytes Short completer */ /* with cache control hints */ { unsigned long result = (unsigned long)0UL; i = m = a = 0; while ( *s == ',' && i < 3 ) { s++; if ( strncasecmp(s,"m",1) == 0 ) m = 1; else if ( strncasecmp(s,"b",1) == 0 && (strncasecmp((s+1),"c",1) != 0) ) a = 0; else if ( strncasecmp(s,"e",1) == 0 ) a = 1; else if ( strncmp(s,",",1) == 0 ) /* no completer */ result |= parse_cache_control_hint(&s, 0); else if ( (strncasecmp(s,"c",1) == 0) || (strncasecmp(s,"b",1) == 0) ) {/* just 1 completer */ s--; result |= parse_cache_control_hint(&s, 0); } else as_bad("Unrecognized Store Bytes Short" "Completer with cache control hints" " ...assuming 0"); if (result == (unsigned long)0UL) s++; i++; } /** if ( i >= 2 ) **/ if ( i > 3 ) as_bad("Illegal Store Bytes Short Completer " "with cache control hints ... extras ignored"); while ( *s == ' ' || *s == '\t' ) /* skip to next operand */ s++; opcode |= result; opcode |= m << 5; opcode |= a << 13; continue; } case '<': /* non-negated compare/subtract conditions. */ cmpltr = pa_parse_nonneg_cmpsub_cmpltr(&s); if ( cmpltr < 0 ) { as_bad("Unrecognized Compare/Subtract Condition: %c",*s); cmpltr = 0; } opcode |= cmpltr << 13; continue; case '?': /* negated or non-negated cmp/sub conditions. */ /* used only by ``comb'' and ``comib'' pseudo-ops */ save_s = s; cmpltr = pa_parse_nonneg_cmpsub_cmpltr(&s); if ( cmpltr < 0 ) { s = save_s; cmpltr = pa_parse_neg_cmpsub_cmpltr(&s); if ( cmpltr < 0 ) { as_bad("Unrecognized Compare/Subtract Condition: %c" ,*s); cmpltr = 0; } else { opcode |= 1 << 27; /* required opcode change to make COMIBT into a COMIBF or a COMBT into a COMBF or a ADDBT into a ADDBF or a ADDIBT into a ADDIBF */ } } opcode |= cmpltr << 13; continue; case '!': /* negated or non-negated add conditions. */ /* used only by ``addb'' and ``addib'' pseudo-ops */ save_s = s; cmpltr = pa_parse_nonneg_add_cmpltr(&s); if ( cmpltr < 0 ) { s = save_s; cmpltr = pa_parse_neg_add_cmpltr(&s); if ( cmpltr < 0 ) { as_bad("Unrecognized Compare/Subtract Condition: %c", *s); cmpltr = 0; } else { opcode |= 1 << 27; /* required opcode change to make COMIBT into a COMIBF or a COMBT into a COMBF or a ADDBT into a ADDBF or a ADDIBT into a ADDIBF */ } } opcode |= cmpltr << 13; continue; case '-': /* compare/subtract conditions */ f = cmpltr = 0; save_s = s; if ( *s == ',' ) { cmpltr = pa_parse_nonneg_cmpsub_cmpltr(&s); if ( cmpltr < 0 ) { f = 1; s = save_s; cmpltr = pa_parse_neg_cmpsub_cmpltr(&s); if ( cmpltr < 0 ) { as_bad("Unrecognized Compare/Subtract Condition"); } } } opcode |= cmpltr << 13; opcode |= f << 12; continue; case '+': /* non-negated add conditions */ flag = nullif = cmpltr = 0; if ( *s == ',' ) { s++; name = s; while ( *s != ',' && *s != ' ' && *s != '\t' ) s += 1; c = *s; *s = 0x00; if ( strcmp(name,"=") == 0 ) { cmpltr = 1; } else if ( strcmp(name,"<") == 0 ) { cmpltr = 2; } else if ( strcmp(name,"<=") == 0 ) { cmpltr = 3; } else if ( strcasecmp(name,"nuv") == 0 ) { cmpltr = 4; } else if ( strcasecmp(name,"znv") == 0 ) { cmpltr = 5; } else if ( strcasecmp(name,"sv") == 0 ) { cmpltr = 6; } else if ( strcasecmp(name,"od") == 0 ) { cmpltr = 7; } else if ( strcasecmp(name,"n") == 0 ) { nullif = 1; } else if ( strcasecmp(name,"tr") == 0 ) { cmpltr = 0; flag = 1; } else if ( strcasecmp(name,"<>") == 0 ) { flag = cmpltr = 1; } else if ( strcasecmp(name,">=") == 0 ) { cmpltr = 2; flag = 1; } else if ( strcasecmp(name,">") == 0 ) { cmpltr = 3; flag = 1; } else if ( strcasecmp(name,"uv") == 0 ) { cmpltr = 4; flag = 1; } else if ( strcasecmp(name,"vnz") == 0 ) { cmpltr = 5; flag = 1; } else if ( strcasecmp(name,"nsv") == 0 ) { cmpltr = 6; flag = 1; } else if ( strcasecmp(name,"ev") == 0 ) { cmpltr = 7; flag = 1; } else as_bad("Unrecognized Add Condition: %s",name); *s = c; } nullif = pa_parse_nullif(&s); opcode |= nullif << 1; opcode |= cmpltr << 13; opcode |= flag << 12; continue; case '&': /* logical instruction conditions */ f = cmpltr = 0; if ( *s == ',' ) { s++; name = s; while ( *s != ',' && *s != ' ' && *s != '\t' ) s += 1; c = *s; *s = 0x00; if ( strcmp(name,"=") == 0 ) { cmpltr = 1; } else if ( strcmp(name,"<") == 0 ) { cmpltr = 2; } else if ( strcmp(name,"<=") == 0 ) { cmpltr = 3; } else if ( strcasecmp(name,"od") == 0 ) { cmpltr = 7; } else if ( strcasecmp(name,"tr") == 0 ) { cmpltr = 0; f = 1; } else if ( strcmp(name,"<>") == 0 ) { f = cmpltr = 1; } else if ( strcmp(name,">=") == 0 ) { cmpltr = 2; f = 1; } else if ( strcmp(name,">") == 0 ) { cmpltr = 3; f = 1; } else if ( strcasecmp(name,"ev") == 0 ) { cmpltr = 7; f = 1; } else as_bad("Unrecognized Logical Instruction Condition:" " %s",name); *s = c; } opcode |= cmpltr << 13; opcode |= f << 12; continue; case 'U': /* unit instruction conditions */ cmpltr = 0; f = 0; if ( *s == ',' ) { s++; if ( strncasecmp(s,"sbz",3) == 0 ) { cmpltr = 2; s += 3; } else if ( strncasecmp(s,"shz",3) == 0 ) { cmpltr = 3; s += 3; } else if ( strncasecmp(s,"sdc",3) == 0 ) { cmpltr = 4; s += 3; } else if ( strncasecmp(s,"sbc",3) == 0 ) { cmpltr = 6; s += 3; } else if ( strncasecmp(s,"shc",3) == 0 ) { cmpltr = 7; s += 3; } else if ( strncasecmp(s,"tr",2) == 0 ) { cmpltr = 0; f = 1; s += 2; } else if ( strncasecmp(s,"nbz",3) == 0 ) { cmpltr = 2; f = 1; s += 3; } else if ( strncasecmp(s,"nhz",3) == 0 ) { cmpltr = 3; f = 1; s += 3; } else if ( strncasecmp(s,"ndc",3) == 0 ) { cmpltr = 4; f = 1; s += 3; } else if ( strncasecmp(s,"nbc",3) == 0 ) { cmpltr = 6; f = 1; s += 3; } else if ( strncasecmp(s,"nhc",3) == 0 ) { cmpltr = 7; f = 1; s += 3; } else as_bad("Unrecognized Logical Instruction Condition:" " %c",*s); } opcode |= cmpltr << 13; opcode |= f << 12; continue; case '>': /* shift/extract/deposit conditions. */ cmpltr = 0; if ( *s == ',' ) { s++; name = s; while ( *s != ',' && *s != ' ' && *s != '\t' ) s += 1; c = *s; *s = 0x00; if ( strcmp(name,"=") == 0 ) { cmpltr = 1; } else if ( strcmp(name,"<") == 0 ) { cmpltr = 2; } else if ( strcasecmp(name,"od") == 0 ) { cmpltr = 3; } else if ( strcasecmp(name,"tr") == 0 ) { cmpltr = 4; } else if ( strcmp(name,"<>") == 0 ) { cmpltr = 5; } else if ( strcmp(name,">=") == 0 ) { cmpltr = 6; } else if ( strcasecmp(name,"ev") == 0 ) { cmpltr = 7; } else as_bad("Unrecognized Shift/Extract/Deposit" "Condition: %s",name); *s = c; } opcode |= cmpltr << 13; continue; case '~': /* bvb,bb conditions */ cmpltr = 0; if ( *s == ',' ) { s++; if ( strncmp(s,"<",1) == 0 ) { cmpltr = 2; s++; } else if ( strncmp(s,">=",2) == 0 ) { cmpltr = 6; s += 2; } else as_bad("Unrecognized Bit Branch Condition: %c",*s); } opcode |= cmpltr << 13; continue; case 'V': /* 5 bit immediate at 31 */ getExpression(s); im5 = low_sign_unext(evaluateAbsolute( the_insn.exp,0),5); opcode |= im5; s = expr_end; continue; case 'r': /* 5 bit immediate at 31 */ /* (unsigned value for the break instruction) */ getExpression(s); im5 = evaluateAbsolute(the_insn.exp,0); if ( im5 > 31 ) { as_bad("Operand out of range. Was: %d. Should be" "[0..31]. Assuming %d.\n",im5,im5&0x1f); im5 = im5 & 0x1f; } opcode |= im5; s = expr_end; continue; case 'R': /* 5 bit immediate at 15 */ /* (unsigned value for the ssm and rsm instruction) */ getExpression(s); im5 = evaluateAbsolute(the_insn.exp,0); if ( im5 > 31 ) { as_bad("Operand out of range. Was: %d. Should be" "[0..31]. Assuming %d.\n",im5,im5&0x1f); im5 = im5 & 0x1f; } opcode |= im5 << 16; s = expr_end; continue; case 'i': /* 11 bit immediate at 31 */ getExpression(s); if ( the_insn.exp.X_seg == SEG_ABSOLUTE ) { im11 = low_sign_unext(evaluateAbsolute( the_insn.exp,0),11); opcode |= im11; } else { the_insn.code = 'i'; } s = expr_end; continue; case 'j': /* 14 bit immediate at 31 --- LO14 */ { int field_selector = parse_L_or_R(s); switch (field_selector) { case 2: /* found the field selector R`*/ case 1: /* found the field selector L`*/ s += 2; /* eat up L` or R` */ case 0: /* not found */ getExpression(s); break; default: as_bad("Bad field selector. Was: %.2s. Should be either L` or R`\n",s); break; } if ( the_insn.exp.X_seg == SEG_ABSOLUTE ) { im14 = low_sign_unext( evaluateAbsolute(the_insn.exp,field_selector), 14); /* I donot think the mask is necessary here low_sign_unext() takes */ /* care of putting only 14 bits in im14 ! ... 090993 ... USV */ /* if (field_selector) opcode |= (im14 & 0x7ff); else */ opcode |= im14; } else { the_insn.reloc = HPPA_RELOC_LO14; the_insn.code = 'j'; } s = expr_end; continue; } case 'z': /* 17 bit branch displacement (non-pc-relative) */ /* for be, ble --- BR17*/ /* bl, ble in absence of L` or R` can have */ /* a 17 bit immmidiate number */ { unsigned long w, w1, w2; int field_selector = parse_L_or_R(s); switch (field_selector) { case 2: /* found the field selector R`*/ case 1: /* found the field selector L`*/ s += 2; /* eat up L` or R` */ case 0: /* not found */ getExpression(s); break; default: as_bad("Bad field selector. Was: %.2s." "Should be either L` or R`\n",s); break; } if ( the_insn.exp.X_seg == SEG_ABSOLUTE ) { im14 = sign_unext( evaluateAbsolute(the_insn.exp,field_selector), 17); dis_assemble_17(im14>>2,&w1,&w2,&w); opcode |= ( ( w2 << 2 ) | ( w1 << 16 ) | w ); } else { the_insn.reloc = HPPA_RELOC_BR17; the_insn.code = 'z'; } s = expr_end; continue; } case 'k': /* 21 bit immediate at 31 --- HI21 */ { int field_selector = parse_L_or_R(s); switch (field_selector) { case 2: /* found the field selector R`*/ case 1: /* found the field selector L`*/ s += 2; /* eat up L` or R` */ case 0: /* not found */ getExpression(s); break; default: as_bad("Bad field selector. Was: %.2s." "Should be either L` or R`\n",s); break; } if ( the_insn.exp.X_seg == SEG_ABSOLUTE ) { im21 = dis_assemble_21( (evaluateAbsolute(the_insn.exp,field_selector) >> 11)); opcode |= im21 ; } else { the_insn.reloc = HPPA_RELOC_HI21; the_insn.code = 'k'; } s = expr_end; continue; }