repo_name
string
path
string
copies
string
size
string
content
string
license
string
sdphome/UHF_Reader
u-boot-2015.04/arch/avr32/cpu/portmux-gpio.c
52
2316
/* * Copyright (C) 2008 Atmel Corporation * * SPDX-License-Identifier: GPL-2.0+ */ #include <common.h> #include <asm/io.h> #include <asm/arch/hardware.h> #include <asm/arch/gpio.h> void portmux_select_peripheral(void *port, unsigned long pin_mask, enum portmux_function func, unsigned long flags) { /* Both pull-up and pull-down set means buskeeper */ if (flags & PORTMUX_PULL_DOWN) gpio_writel(port, PDERS, pin_mask); else gpio_writel(port, PDERC, pin_mask); if (flags & PORTMUX_PULL_UP) gpio_writel(port, PUERS, pin_mask); else gpio_writel(port, PUERC, pin_mask); /* Select drive strength */ if (flags & PORTMUX_DRIVE_LOW) gpio_writel(port, ODCR0S, pin_mask); else gpio_writel(port, ODCR0C, pin_mask); if (flags & PORTMUX_DRIVE_HIGH) gpio_writel(port, ODCR1S, pin_mask); else gpio_writel(port, ODCR1C, pin_mask); /* Select function */ if (func & PORTMUX_FUNC_B) gpio_writel(port, PMR0S, pin_mask); else gpio_writel(port, PMR0C, pin_mask); if (func & PORTMUX_FUNC_C) gpio_writel(port, PMR1S, pin_mask); else gpio_writel(port, PMR1C, pin_mask); /* Disable GPIO (i.e. enable peripheral) */ gpio_writel(port, GPERC, pin_mask); } void portmux_select_gpio(void *port, unsigned long pin_mask, unsigned long flags) { /* Both pull-up and pull-down set means buskeeper */ if (flags & PORTMUX_PULL_DOWN) gpio_writel(port, PDERS, pin_mask); else gpio_writel(port, PDERC, pin_mask); if (flags & PORTMUX_PULL_UP) gpio_writel(port, PUERS, pin_mask); else gpio_writel(port, PUERC, pin_mask); /* Enable open-drain mode if requested */ if (flags & PORTMUX_OPEN_DRAIN) gpio_writel(port, ODMERS, pin_mask); else gpio_writel(port, ODMERC, pin_mask); /* Select drive strength */ if (flags & PORTMUX_DRIVE_LOW) gpio_writel(port, ODCR0S, pin_mask); else gpio_writel(port, ODCR0C, pin_mask); if (flags & PORTMUX_DRIVE_HIGH) gpio_writel(port, ODCR1S, pin_mask); else gpio_writel(port, ODCR1C, pin_mask); /* Select direction and initial pin state */ if (flags & PORTMUX_DIR_OUTPUT) { if (flags & PORTMUX_INIT_HIGH) gpio_writel(port, OVRS, pin_mask); else gpio_writel(port, OVRC, pin_mask); gpio_writel(port, ODERS, pin_mask); } else { gpio_writel(port, ODERC, pin_mask); } /* Enable GPIO */ gpio_writel(port, GPERS, pin_mask); }
gpl-3.0
shlevy/grub
grub-core/gnulib/argp-parse.c
52
31705
/* Hierarchical argument parsing, layered over getopt Copyright (C) 1995-2000, 2002-2004, 2009-2013 Free Software Foundation, Inc. This file is part of the GNU C Library. Written by Miles Bader <miles@gnu.ai.mit.edu>. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifdef HAVE_CONFIG_H # include <config.h> #endif #include <alloca.h> #include <stdalign.h> #include <stddef.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <limits.h> #include <getopt.h> #include <getopt_int.h> #ifdef _LIBC # include <libintl.h> # undef dgettext # define dgettext(domain, msgid) \ INTUSE(__dcgettext) (domain, msgid, LC_MESSAGES) #else # include "gettext.h" #endif #define N_(msgid) msgid #include "argp.h" #include "argp-namefrob.h" #define alignto(n, d) ((((n) + (d) - 1) / (d)) * (d)) /* Getopt return values. */ #define KEY_END (-1) /* The end of the options. */ #define KEY_ARG 1 /* A non-option argument. */ #define KEY_ERR '?' /* An error parsing the options. */ /* The meta-argument used to prevent any further arguments being interpreted as options. */ #define QUOTE "--" /* The number of bits we steal in a long-option value for our own use. */ #define GROUP_BITS CHAR_BIT /* The number of bits available for the user value. */ #define USER_BITS ((sizeof ((struct option *)0)->val * CHAR_BIT) - GROUP_BITS) #define USER_MASK ((1 << USER_BITS) - 1) /* EZ alias for ARGP_ERR_UNKNOWN. */ #define EBADKEY ARGP_ERR_UNKNOWN /* Default options. */ /* When argp is given the --HANG switch, _ARGP_HANG is set and argp will sleep for one second intervals, decrementing _ARGP_HANG until it's zero. Thus you can force the program to continue by attaching a debugger and setting it to 0 yourself. */ static volatile int _argp_hang; #define OPT_PROGNAME -2 #define OPT_USAGE -3 #define OPT_HANG -4 static const struct argp_option argp_default_options[] = { {"help", '?', 0, 0, N_("give this help list"), -1}, {"usage", OPT_USAGE, 0, 0, N_("give a short usage message"), 0}, {"program-name",OPT_PROGNAME,N_("NAME"), OPTION_HIDDEN, N_("set the program name"), 0}, {"HANG", OPT_HANG, N_("SECS"), OPTION_ARG_OPTIONAL | OPTION_HIDDEN, N_("hang for SECS seconds (default 3600)"), 0}, {NULL, 0, 0, 0, NULL, 0} }; static error_t argp_default_parser (int key, char *arg, struct argp_state *state) { switch (key) { case '?': __argp_state_help (state, state->out_stream, ARGP_HELP_STD_HELP); break; case OPT_USAGE: __argp_state_help (state, state->out_stream, ARGP_HELP_USAGE | ARGP_HELP_EXIT_OK); break; case OPT_PROGNAME: /* Set the program name. */ #if defined _LIBC || HAVE_DECL_PROGRAM_INVOCATION_NAME program_invocation_name = arg; #endif /* [Note that some systems only have PROGRAM_INVOCATION_SHORT_NAME (aka __PROGNAME), in which case, PROGRAM_INVOCATION_NAME is just defined to be that, so we have to be a bit careful here.] */ /* Update what we use for messages. */ state->name = __argp_base_name (arg); #if defined _LIBC || HAVE_DECL_PROGRAM_INVOCATION_SHORT_NAME program_invocation_short_name = state->name; #endif if ((state->flags & (ARGP_PARSE_ARGV0 | ARGP_NO_ERRS)) == ARGP_PARSE_ARGV0) /* Update what getopt uses too. */ state->argv[0] = arg; break; case OPT_HANG: _argp_hang = atoi (arg ? arg : "3600"); while (_argp_hang-- > 0) __sleep (1); break; default: return EBADKEY; } return 0; } static const struct argp argp_default_argp = {argp_default_options, &argp_default_parser, NULL, NULL, NULL, NULL, "libc"}; static const struct argp_option argp_version_options[] = { {"version", 'V', 0, 0, N_("print program version"), -1}, {NULL, 0, 0, 0, NULL, 0} }; static error_t argp_version_parser (int key, char *arg, struct argp_state *state) { switch (key) { case 'V': if (argp_program_version_hook) (*argp_program_version_hook) (state->out_stream, state); else if (argp_program_version) fprintf (state->out_stream, "%s\n", argp_program_version); else __argp_error (state, "%s", dgettext (state->root_argp->argp_domain, "(PROGRAM ERROR) No version known!?")); if (! (state->flags & ARGP_NO_EXIT)) exit (0); break; default: return EBADKEY; } return 0; } static const struct argp argp_version_argp = {argp_version_options, &argp_version_parser, NULL, NULL, NULL, NULL, "libc"}; /* Returns the offset into the getopt long options array LONG_OPTIONS of a long option with called NAME, or -1 if none is found. Passing NULL as NAME will return the number of options. */ static int find_long_option (struct option *long_options, const char *name) { struct option *l = long_options; while (l->name != NULL) if (name != NULL && strcmp (l->name, name) == 0) return l - long_options; else l++; if (name == NULL) return l - long_options; else return -1; } /* The state of a "group" during parsing. Each group corresponds to a particular argp structure from the tree of such descending from the top level argp passed to argp_parse. */ struct group { /* This group's parsing function. */ argp_parser_t parser; /* Which argp this group is from. */ const struct argp *argp; /* Points to the point in SHORT_OPTS corresponding to the end of the short options for this group. We use it to determine from which group a particular short options is from. */ char *short_end; /* The number of non-option args successfully handled by this parser. */ unsigned args_processed; /* This group's parser's parent's group. */ struct group *parent; unsigned parent_index; /* And the our position in the parent. */ /* These fields are swapped into and out of the state structure when calling this group's parser. */ void *input, **child_inputs; void *hook; }; /* Call GROUP's parser with KEY and ARG, swapping any group-specific info from STATE before calling, and back into state afterwards. If GROUP has no parser, EBADKEY is returned. */ static error_t group_parse (struct group *group, struct argp_state *state, int key, char *arg) { if (group->parser) { error_t err; state->hook = group->hook; state->input = group->input; state->child_inputs = group->child_inputs; state->arg_num = group->args_processed; err = (*group->parser)(key, arg, state); group->hook = state->hook; return err; } else return EBADKEY; } struct parser { const struct argp *argp; /* SHORT_OPTS is the getopt short options string for the union of all the groups of options. */ char *short_opts; /* LONG_OPTS is the array of getop long option structures for the union of all the groups of options. */ struct option *long_opts; /* OPT_DATA is the getopt data used for the re-entrant getopt. */ struct _getopt_data opt_data; /* States of the various parsing groups. */ struct group *groups; /* The end of the GROUPS array. */ struct group *egroup; /* A vector containing storage for the CHILD_INPUTS field in all groups. */ void **child_inputs; /* True if we think using getopt is still useful; if false, then remaining arguments are just passed verbatim with ARGP_KEY_ARG. This is cleared whenever getopt returns KEY_END, but may be set again if the user moves the next argument pointer backwards. */ int try_getopt; /* State block supplied to parsing routines. */ struct argp_state state; /* Memory used by this parser. */ void *storage; }; /* The next usable entries in the various parser tables being filled in by convert_options. */ struct parser_convert_state { struct parser *parser; char *short_end; struct option *long_end; void **child_inputs_end; }; /* Converts all options in ARGP (which is put in GROUP) and ancestors into getopt options stored in SHORT_OPTS and LONG_OPTS; SHORT_END and CVT->LONG_END are the points at which new options are added. Returns the next unused group entry. CVT holds state used during the conversion. */ static struct group * convert_options (const struct argp *argp, struct group *parent, unsigned parent_index, struct group *group, struct parser_convert_state *cvt) { /* REAL is the most recent non-alias value of OPT. */ const struct argp_option *real = argp->options; const struct argp_child *children = argp->children; if (real || argp->parser) { const struct argp_option *opt; if (real) for (opt = real; !__option_is_end (opt); opt++) { if (! (opt->flags & OPTION_ALIAS)) /* OPT isn't an alias, so we can use values from it. */ real = opt; if (! (real->flags & OPTION_DOC)) /* A real option (not just documentation). */ { if (__option_is_short (opt)) /* OPT can be used as a short option. */ { *cvt->short_end++ = opt->key; if (real->arg) { *cvt->short_end++ = ':'; if (real->flags & OPTION_ARG_OPTIONAL) *cvt->short_end++ = ':'; } *cvt->short_end = '\0'; /* keep 0 terminated */ } if (opt->name && find_long_option (cvt->parser->long_opts, opt->name) < 0) /* OPT can be used as a long option. */ { cvt->long_end->name = opt->name; cvt->long_end->has_arg = (real->arg ? (real->flags & OPTION_ARG_OPTIONAL ? optional_argument : required_argument) : no_argument); cvt->long_end->flag = 0; /* we add a disambiguating code to all the user's values (which is removed before we actually call the function to parse the value); this means that the user loses use of the high 8 bits in all his values (the sign of the lower bits is preserved however)... */ cvt->long_end->val = ((opt->key ? opt->key : real->key) & USER_MASK) + (((group - cvt->parser->groups) + 1) << USER_BITS); /* Keep the LONG_OPTS list terminated. */ (++cvt->long_end)->name = NULL; } } } group->parser = argp->parser; group->argp = argp; group->short_end = cvt->short_end; group->args_processed = 0; group->parent = parent; group->parent_index = parent_index; group->input = 0; group->hook = 0; group->child_inputs = 0; if (children) /* Assign GROUP's CHILD_INPUTS field some space from CVT->child_inputs_end.*/ { unsigned num_children = 0; while (children[num_children].argp) num_children++; group->child_inputs = cvt->child_inputs_end; cvt->child_inputs_end += num_children; } parent = group++; } else parent = 0; if (children) { unsigned index = 0; while (children->argp) group = convert_options (children++->argp, parent, index++, group, cvt); } return group; } /* Find the merged set of getopt options, with keys appropriately prefixed. */ static void parser_convert (struct parser *parser, const struct argp *argp, int flags) { struct parser_convert_state cvt; cvt.parser = parser; cvt.short_end = parser->short_opts; cvt.long_end = parser->long_opts; cvt.child_inputs_end = parser->child_inputs; if (flags & ARGP_IN_ORDER) *cvt.short_end++ = '-'; else if (flags & ARGP_NO_ARGS) *cvt.short_end++ = '+'; *cvt.short_end = '\0'; cvt.long_end->name = NULL; parser->argp = argp; if (argp) parser->egroup = convert_options (argp, 0, 0, parser->groups, &cvt); else parser->egroup = parser->groups; /* No parsers at all! */ } /* Lengths of various parser fields which we will allocated. */ struct parser_sizes { size_t short_len; /* Getopt short options string. */ size_t long_len; /* Getopt long options vector. */ size_t num_groups; /* Group structures we allocate. */ size_t num_child_inputs; /* Child input slots. */ }; /* For ARGP, increments the NUM_GROUPS field in SZS by the total number of argp structures descended from it, and the SHORT_LEN & LONG_LEN fields by the maximum lengths of the resulting merged getopt short options string and long-options array, respectively. */ static void calc_sizes (const struct argp *argp, struct parser_sizes *szs) { const struct argp_child *child = argp->children; const struct argp_option *opt = argp->options; if (opt || argp->parser) { szs->num_groups++; if (opt) { int num_opts = 0; while (!__option_is_end (opt++)) num_opts++; szs->short_len += num_opts * 3; /* opt + up to 2 ':'s */ szs->long_len += num_opts; } } if (child) while (child->argp) { calc_sizes ((child++)->argp, szs); szs->num_child_inputs++; } } /* Initializes PARSER to parse ARGP in a manner described by FLAGS. */ static error_t parser_init (struct parser *parser, const struct argp *argp, int argc, char **argv, int flags, void *input) { error_t err = 0; struct group *group; struct parser_sizes szs; struct _getopt_data opt_data = _GETOPT_DATA_INITIALIZER; char *storage; size_t glen, gsum; size_t clen, csum; size_t llen, lsum; size_t slen, ssum; szs.short_len = (flags & ARGP_NO_ARGS) ? 0 : 1; szs.long_len = 0; szs.num_groups = 0; szs.num_child_inputs = 0; if (argp) calc_sizes (argp, &szs); /* Lengths of the various bits of storage used by PARSER. */ glen = (szs.num_groups + 1) * sizeof (struct group); clen = szs.num_child_inputs * sizeof (void *); llen = (szs.long_len + 1) * sizeof (struct option); slen = szs.short_len + 1; /* Sums of previous lengths, properly aligned. There's no need to align gsum, since struct group is aligned at least as strictly as void * (since it contains a void * member). And there's no need to align lsum, since struct option is aligned at least as strictly as char. */ gsum = glen; csum = alignto (gsum + clen, alignof (struct option)); lsum = csum + llen; ssum = lsum + slen; parser->storage = malloc (ssum); if (! parser->storage) return ENOMEM; storage = parser->storage; parser->groups = parser->storage; parser->child_inputs = (void **) (storage + gsum); parser->long_opts = (struct option *) (storage + csum); parser->short_opts = storage + lsum; parser->opt_data = opt_data; memset (parser->child_inputs, 0, clen); parser_convert (parser, argp, flags); memset (&parser->state, 0, sizeof (struct argp_state)); parser->state.root_argp = parser->argp; parser->state.argc = argc; parser->state.argv = argv; parser->state.flags = flags; parser->state.err_stream = stderr; parser->state.out_stream = stdout; parser->state.next = 0; /* Tell getopt to initialize. */ parser->state.pstate = parser; parser->try_getopt = 1; /* Call each parser for the first time, giving it a chance to propagate values to child parsers. */ if (parser->groups < parser->egroup) parser->groups->input = input; for (group = parser->groups; group < parser->egroup && (!err || err == EBADKEY); group++) { if (group->parent) /* If a child parser, get the initial input value from the parent. */ group->input = group->parent->child_inputs[group->parent_index]; if (!group->parser && group->argp->children && group->argp->children->argp) /* For the special case where no parsing function is supplied for an argp, propagate its input to its first child, if any (this just makes very simple wrapper argps more convenient). */ group->child_inputs[0] = group->input; err = group_parse (group, &parser->state, ARGP_KEY_INIT, 0); } if (err == EBADKEY) err = 0; /* Some parser didn't understand. */ if (err) return err; if (parser->state.flags & ARGP_NO_ERRS) { parser->opt_data.opterr = 0; if (parser->state.flags & ARGP_PARSE_ARGV0) /* getopt always skips ARGV[0], so we have to fake it out. As long as OPTERR is 0, then it shouldn't actually try to access it. */ parser->state.argv--, parser->state.argc++; } else parser->opt_data.opterr = 1; /* Print error messages. */ if (parser->state.argv == argv && argv[0]) /* There's an argv[0]; use it for messages. */ parser->state.name = __argp_base_name (argv[0]); else parser->state.name = __argp_short_program_name (); return 0; } /* Free any storage consumed by PARSER (but not PARSER itself). */ static error_t parser_finalize (struct parser *parser, error_t err, int arg_ebadkey, int *end_index) { struct group *group; if (err == EBADKEY && arg_ebadkey) /* Suppress errors generated by unparsed arguments. */ err = 0; if (! err) { if (parser->state.next == parser->state.argc) /* We successfully parsed all arguments! Call all the parsers again, just a few more times... */ { for (group = parser->groups; group < parser->egroup && (!err || err==EBADKEY); group++) if (group->args_processed == 0) err = group_parse (group, &parser->state, ARGP_KEY_NO_ARGS, 0); for (group = parser->egroup - 1; group >= parser->groups && (!err || err==EBADKEY); group--) err = group_parse (group, &parser->state, ARGP_KEY_END, 0); if (err == EBADKEY) err = 0; /* Some parser didn't understand. */ /* Tell the user that all arguments are parsed. */ if (end_index) *end_index = parser->state.next; } else if (end_index) /* Return any remaining arguments to the user. */ *end_index = parser->state.next; else /* No way to return the remaining arguments, they must be bogus. */ { if (!(parser->state.flags & ARGP_NO_ERRS) && parser->state.err_stream) fprintf (parser->state.err_stream, dgettext (parser->argp->argp_domain, "%s: Too many arguments\n"), parser->state.name); err = EBADKEY; } } /* Okay, we're all done, with either an error or success; call the parsers to indicate which one. */ if (err) { /* Maybe print an error message. */ if (err == EBADKEY) /* An appropriate message describing what the error was should have been printed earlier. */ __argp_state_help (&parser->state, parser->state.err_stream, ARGP_HELP_STD_ERR); /* Since we didn't exit, give each parser an error indication. */ for (group = parser->groups; group < parser->egroup; group++) group_parse (group, &parser->state, ARGP_KEY_ERROR, 0); } else /* Notify parsers of success, and propagate back values from parsers. */ { /* We pass over the groups in reverse order so that child groups are given a chance to do there processing before passing back a value to the parent. */ for (group = parser->egroup - 1 ; group >= parser->groups && (!err || err == EBADKEY) ; group--) err = group_parse (group, &parser->state, ARGP_KEY_SUCCESS, 0); if (err == EBADKEY) err = 0; /* Some parser didn't understand. */ } /* Call parsers once more, to do any final cleanup. Errors are ignored. */ for (group = parser->egroup - 1; group >= parser->groups; group--) group_parse (group, &parser->state, ARGP_KEY_FINI, 0); if (err == EBADKEY) err = EINVAL; free (parser->storage); return err; } /* Call the user parsers to parse the non-option argument VAL, at the current position, returning any error. The state NEXT pointer is assumed to have been adjusted (by getopt) to point after this argument; this function will adjust it correctly to reflect however many args actually end up being consumed. */ static error_t parser_parse_arg (struct parser *parser, char *val) { /* Save the starting value of NEXT, first adjusting it so that the arg we're parsing is again the front of the arg vector. */ int index = --parser->state.next; error_t err = EBADKEY; struct group *group; int key = 0; /* Which of ARGP_KEY_ARG[S] we used. */ /* Try to parse the argument in each parser. */ for (group = parser->groups ; group < parser->egroup && err == EBADKEY ; group++) { parser->state.next++; /* For ARGP_KEY_ARG, consume the arg. */ key = ARGP_KEY_ARG; err = group_parse (group, &parser->state, key, val); if (err == EBADKEY) /* This parser doesn't like ARGP_KEY_ARG; try ARGP_KEY_ARGS instead. */ { parser->state.next--; /* For ARGP_KEY_ARGS, put back the arg. */ key = ARGP_KEY_ARGS; err = group_parse (group, &parser->state, key, 0); } } if (! err) { if (key == ARGP_KEY_ARGS) /* The default for ARGP_KEY_ARGS is to assume that if NEXT isn't changed by the user, *all* arguments should be considered consumed. */ parser->state.next = parser->state.argc; if (parser->state.next > index) /* Remember that we successfully processed a non-option argument -- but only if the user hasn't gotten tricky and set the clock back. */ (--group)->args_processed += (parser->state.next - index); else /* The user wants to reparse some args, give getopt another try. */ parser->try_getopt = 1; } return err; } /* Call the user parsers to parse the option OPT, with argument VAL, at the current position, returning any error. */ static error_t parser_parse_opt (struct parser *parser, int opt, char *val) { /* The group key encoded in the high bits; 0 for short opts or group_number + 1 for long opts. */ int group_key = opt >> USER_BITS; error_t err = EBADKEY; if (group_key == 0) /* A short option. By comparing OPT's position in SHORT_OPTS to the various starting positions in each group's SHORT_END field, we can determine which group OPT came from. */ { struct group *group; char *short_index = strchr (parser->short_opts, opt); if (short_index) for (group = parser->groups; group < parser->egroup; group++) if (group->short_end > short_index) { err = group_parse (group, &parser->state, opt, parser->opt_data.optarg); break; } } else /* A long option. We use shifts instead of masking for extracting the user value in order to preserve the sign. */ err = group_parse (&parser->groups[group_key - 1], &parser->state, (opt << GROUP_BITS) >> GROUP_BITS, parser->opt_data.optarg); if (err == EBADKEY) /* At least currently, an option not recognized is an error in the parser, because we pre-compute which parser is supposed to deal with each option. */ { static const char bad_key_err[] = N_("(PROGRAM ERROR) Option should have been recognized!?"); if (group_key == 0) __argp_error (&parser->state, "-%c: %s", opt, dgettext (parser->argp->argp_domain, bad_key_err)); else { struct option *long_opt = parser->long_opts; while (long_opt->val != opt && long_opt->name) long_opt++; __argp_error (&parser->state, "--%s: %s", long_opt->name ? long_opt->name : "???", dgettext (parser->argp->argp_domain, bad_key_err)); } } return err; } /* Parse the next argument in PARSER (as indicated by PARSER->state.next). Any error from the parsers is returned, and *ARGP_EBADKEY indicates whether a value of EBADKEY is due to an unrecognized argument (which is generally not fatal). */ static error_t parser_parse_next (struct parser *parser, int *arg_ebadkey) { int opt; error_t err = 0; if (parser->state.quoted && parser->state.next < parser->state.quoted) /* The next argument pointer has been moved to before the quoted region, so pretend we never saw the quoting "--", and give getopt another chance. If the user hasn't removed it, getopt will just process it again. */ parser->state.quoted = 0; if (parser->try_getopt && !parser->state.quoted) /* Give getopt a chance to parse this. */ { /* Put it back in OPTIND for getopt. */ parser->opt_data.optind = parser->state.next; /* Distinguish KEY_ERR from a real option. */ parser->opt_data.optopt = KEY_END; if (parser->state.flags & ARGP_LONG_ONLY) opt = _getopt_long_only_r (parser->state.argc, parser->state.argv, parser->short_opts, parser->long_opts, 0, &parser->opt_data); else opt = _getopt_long_r (parser->state.argc, parser->state.argv, parser->short_opts, parser->long_opts, 0, &parser->opt_data); /* And see what getopt did. */ parser->state.next = parser->opt_data.optind; if (opt == KEY_END) /* Getopt says there are no more options, so stop using getopt; we'll continue if necessary on our own. */ { parser->try_getopt = 0; if (parser->state.next > 1 && strcmp (parser->state.argv[parser->state.next - 1], QUOTE) == 0) /* Not only is this the end of the options, but it's a "quoted" region, which may have args that *look* like options, so we definitely shouldn't try to use getopt past here, whatever happens. */ parser->state.quoted = parser->state.next; } else if (opt == KEY_ERR && parser->opt_data.optopt != KEY_END) /* KEY_ERR can have the same value as a valid user short option, but in the case of a real error, getopt sets OPTOPT to the offending character, which can never be KEY_END. */ { *arg_ebadkey = 0; return EBADKEY; } } else opt = KEY_END; if (opt == KEY_END) { /* We're past what getopt considers the options. */ if (parser->state.next >= parser->state.argc || (parser->state.flags & ARGP_NO_ARGS)) /* Indicate that we're done. */ { *arg_ebadkey = 1; return EBADKEY; } else /* A non-option arg; simulate what getopt might have done. */ { opt = KEY_ARG; parser->opt_data.optarg = parser->state.argv[parser->state.next++]; } } if (opt == KEY_ARG) /* A non-option argument; try each parser in turn. */ err = parser_parse_arg (parser, parser->opt_data.optarg); else err = parser_parse_opt (parser, opt, parser->opt_data.optarg); if (err == EBADKEY) *arg_ebadkey = (opt == KEY_END || opt == KEY_ARG); return err; } /* Parse the options strings in ARGC & ARGV according to the argp in ARGP. FLAGS is one of the ARGP_ flags above. If END_INDEX is non-NULL, the index in ARGV of the first unparsed option is returned in it. If an unknown option is present, EINVAL is returned; if some parser routine returned a non-zero value, it is returned; otherwise 0 is returned. */ error_t __argp_parse (const struct argp *argp, int argc, char **argv, unsigned flags, int *end_index, void *input) { error_t err; struct parser parser; /* If true, then err == EBADKEY is a result of a non-option argument failing to be parsed (which in some cases isn't actually an error). */ int arg_ebadkey = 0; #ifndef _LIBC if (!(flags & ARGP_PARSE_ARGV0)) { #if HAVE_DECL_PROGRAM_INVOCATION_NAME if (!program_invocation_name) program_invocation_name = argv[0]; #endif #if HAVE_DECL_PROGRAM_INVOCATION_SHORT_NAME if (!program_invocation_short_name) program_invocation_short_name = __argp_base_name (argv[0]); #endif } #endif if (! (flags & ARGP_NO_HELP)) /* Add our own options. */ { struct argp_child *child = alloca (4 * sizeof (struct argp_child)); struct argp *top_argp = alloca (sizeof (struct argp)); /* TOP_ARGP has no options, it just serves to group the user & default argps. */ memset (top_argp, 0, sizeof (*top_argp)); top_argp->children = child; memset (child, 0, 4 * sizeof (struct argp_child)); if (argp) (child++)->argp = argp; (child++)->argp = &argp_default_argp; if (argp_program_version || argp_program_version_hook) (child++)->argp = &argp_version_argp; child->argp = 0; argp = top_argp; } /* Construct a parser for these arguments. */ err = parser_init (&parser, argp, argc, argv, flags, input); if (! err) /* Parse! */ { while (! err) err = parser_parse_next (&parser, &arg_ebadkey); err = parser_finalize (&parser, err, arg_ebadkey, end_index); } return err; } #ifdef weak_alias weak_alias (__argp_parse, argp_parse) #endif /* Return the input field for ARGP in the parser corresponding to STATE; used by the help routines. */ void * __argp_input (const struct argp *argp, const struct argp_state *state) { if (state && state->pstate) { struct group *group; struct parser *parser = state->pstate; for (group = parser->groups; group < parser->egroup; group++) if (group->argp == argp) return group->input; } return 0; } #ifdef weak_alias weak_alias (__argp_input, _argp_input) #endif
gpl-3.0
wafgo/linux-kernel-custom-hw-uio
drivers/platform/x86/toshiba-wmi.c
312
3388
/* * toshiba_wmi.c - Toshiba WMI Hotkey Driver * * Copyright (C) 2015 Azael Avalos <coproscefalo@gmail.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/kernel.h> #include <linux/module.h> #include <linux/init.h> #include <linux/types.h> #include <linux/acpi.h> #include <linux/input.h> #include <linux/input/sparse-keymap.h> MODULE_AUTHOR("Azael Avalos"); MODULE_DESCRIPTION("Toshiba WMI Hotkey Driver"); MODULE_LICENSE("GPL"); #define TOSHIBA_WMI_EVENT_GUID "59142400-C6A3-40FA-BADB-8A2652834100" MODULE_ALIAS("wmi:"TOSHIBA_WMI_EVENT_GUID); static struct input_dev *toshiba_wmi_input_dev; static const struct key_entry toshiba_wmi_keymap[] __initconst = { /* TODO: Add keymap values once found... */ /*{ KE_KEY, 0x00, { KEY_ } },*/ { KE_END, 0 } }; static void toshiba_wmi_notify(u32 value, void *context) { struct acpi_buffer response = { ACPI_ALLOCATE_BUFFER, NULL }; union acpi_object *obj; acpi_status status; status = wmi_get_event_data(value, &response); if (ACPI_FAILURE(status)) { pr_err("Bad event status 0x%x\n", status); return; } obj = (union acpi_object *)response.pointer; if (!obj) return; /* TODO: Add proper checks once we have data */ pr_debug("Unknown event received, obj type %x\n", obj->type); kfree(response.pointer); } static int __init toshiba_wmi_input_setup(void) { acpi_status status; int err; toshiba_wmi_input_dev = input_allocate_device(); if (!toshiba_wmi_input_dev) return -ENOMEM; toshiba_wmi_input_dev->name = "Toshiba WMI hotkeys"; toshiba_wmi_input_dev->phys = "wmi/input0"; toshiba_wmi_input_dev->id.bustype = BUS_HOST; err = sparse_keymap_setup(toshiba_wmi_input_dev, toshiba_wmi_keymap, NULL); if (err) goto err_free_dev; status = wmi_install_notify_handler(TOSHIBA_WMI_EVENT_GUID, toshiba_wmi_notify, NULL); if (ACPI_FAILURE(status)) { err = -EIO; goto err_free_keymap; } err = input_register_device(toshiba_wmi_input_dev); if (err) goto err_remove_notifier; return 0; err_remove_notifier: wmi_remove_notify_handler(TOSHIBA_WMI_EVENT_GUID); err_free_keymap: sparse_keymap_free(toshiba_wmi_input_dev); err_free_dev: input_free_device(toshiba_wmi_input_dev); return err; } static void toshiba_wmi_input_destroy(void) { wmi_remove_notify_handler(TOSHIBA_WMI_EVENT_GUID); sparse_keymap_free(toshiba_wmi_input_dev); input_unregister_device(toshiba_wmi_input_dev); } static int __init toshiba_wmi_init(void) { int ret; if (!wmi_has_guid(TOSHIBA_WMI_EVENT_GUID)) return -ENODEV; ret = toshiba_wmi_input_setup(); if (ret) { pr_err("Failed to setup input device\n"); return ret; } pr_info("Toshiba WMI Hotkey Driver\n"); return 0; } static void __exit toshiba_wmi_exit(void) { if (wmi_has_guid(TOSHIBA_WMI_EVENT_GUID)) toshiba_wmi_input_destroy(); } module_init(toshiba_wmi_init); module_exit(toshiba_wmi_exit);
gpl-3.0
Anubisss/tao_time_example
libs/ACE_wrappers/ace/Intrusive_List.cpp
571
2184
// $Id: Intrusive_List.cpp 92069 2010-09-28 11:38:59Z johnnyw $ #ifndef ACE_INTRUSIVE_LIST_CPP #define ACE_INTRUSIVE_LIST_CPP #include "ace/Intrusive_List.h" #if !defined (ACE_LACKS_PRAGMA_ONCE) # pragma once #endif /* ACE_LACKS_PRAGMA_ONCE */ #if !defined (__ACE_INLINE__) #include "ace/Intrusive_List.inl" #endif /* __ACE_INLINE__ */ ACE_BEGIN_VERSIONED_NAMESPACE_DECL template <class T> ACE_Intrusive_List<T>::ACE_Intrusive_List (void) : head_ (0) , tail_ (0) { } template<class T> ACE_Intrusive_List<T>::~ACE_Intrusive_List (void) { } template<class T> void ACE_Intrusive_List<T>::push_back (T *node) { if (this->tail_ == 0) { this->tail_ = node; this->head_ = node; node->next (0); node->prev (0); } else { this->tail_->next (node); node->prev (this->tail_); node->next (0); this->tail_ = node; } } template<class T> void ACE_Intrusive_List<T>::push_front (T *node) { if (this->head_ == 0) { this->tail_ = node; this->head_ = node; node->next (0); node->prev (0); } else { this->head_->prev (node); node->next (this->head_); node->prev (0); this->head_ = node; } } template<class T> T * ACE_Intrusive_List<T>::pop_front (void) { T *node = this->head_; if (node != 0) { this->unsafe_remove (node); } return node; } template<class T> T * ACE_Intrusive_List<T>::pop_back (void) { T *node = this->tail_; if (node != 0) { this->unsafe_remove (node); } return node; } template<class T> void ACE_Intrusive_List<T>::remove (T *node) { for (T *i = this->head_; i != 0; i = i->next ()) { if (node == i) { this->unsafe_remove (node); return; } } } template<class T> void ACE_Intrusive_List<T>::unsafe_remove (T *node) { if (node->prev () != 0) node->prev ()->next (node->next ()); else this->head_ = node->next (); if (node->next () != 0) node->next ()->prev (node->prev ()); else this->tail_ = node->prev (); node->next (0); node->prev (0); } ACE_END_VERSIONED_NAMESPACE_DECL #endif /* ACE_INTRUSIVE_LIST_CPP */
gpl-3.0
autc04/Retro68
gcc/gcc/testsuite/gcc.dg/enum-incomplete-2.c
69
1353
/* PR c/52085 */ /* { dg-do compile } */ /* { dg-options "" } */ #define SA(X) _Static_assert((X),#X) enum e1; enum e1 { A } __attribute__ ((__packed__)); enum e2 { B } __attribute__ ((__packed__)); SA (sizeof (enum e1) == sizeof (enum e2)); SA (_Alignof (enum e1) == _Alignof (enum e2)); enum e3; enum e3 { C = 256 } __attribute__ ((__packed__)); enum e4 { D = 256 } __attribute__ ((__packed__)); SA (sizeof (enum e3) == sizeof (enum e4)); SA (_Alignof (enum e3) == _Alignof (enum e4)); enum e5; enum e5 { E = __INT_MAX__ } __attribute__ ((__packed__)); enum e6 { F = __INT_MAX__ } __attribute__ ((__packed__)); SA (sizeof (enum e5) == sizeof (enum e6)); SA (_Alignof (enum e5) == _Alignof (enum e6)); enum e7; enum e7 { G } __attribute__ ((__mode__(__byte__))); enum e8 { H } __attribute__ ((__mode__(__byte__))); SA (sizeof (enum e7) == sizeof (enum e8)); SA (_Alignof (enum e7) == _Alignof (enum e8)); enum e9; enum e9 { I } __attribute__ ((__packed__, __mode__(__byte__))); enum e10 { J } __attribute__ ((__packed__, __mode__(__byte__))); SA (sizeof (enum e9) == sizeof (enum e10)); SA (_Alignof (enum e9) == _Alignof (enum e10)); enum e11; enum e11 { K } __attribute__ ((__mode__(__word__))); enum e12 { L } __attribute__ ((__mode__(__word__))); SA (sizeof (enum e11) == sizeof (enum e12)); SA (_Alignof (enum e11) == _Alignof (enum e12));
gpl-3.0
jabez1314/shadowsocks-libev
libsodium/test/default/scalarmult.c
342
1088
#define TEST_NAME "scalarmult" #include "cmptest.h" unsigned char alicesk[32] = { 0x77, 0x07, 0x6d, 0x0a, 0x73, 0x18, 0xa5, 0x7d, 0x3c, 0x16, 0xc1, 0x72, 0x51, 0xb2, 0x66, 0x45, 0xdf, 0x4c, 0x2f, 0x87, 0xeb, 0xc0, 0x99, 0x2a, 0xb1, 0x77, 0xfb, 0xa5, 0x1d, 0xb9, 0x2c, 0x2a }; unsigned char alicepk[32]; int main(void) { int i; crypto_scalarmult_base(alicepk, alicesk); for (i = 0; i < 32; ++i) { if (i > 0) { printf(","); } else { printf(" "); } printf("0x%02x", (unsigned int)alicepk[i]); if (i % 8 == 7) { printf("\n"); } } assert(crypto_scalarmult_bytes() > 0U); assert(crypto_scalarmult_scalarbytes() > 0U); assert(strcmp(crypto_scalarmult_primitive(), "curve25519") == 0); assert(crypto_scalarmult_bytes() == crypto_scalarmult_curve25519_bytes()); assert(crypto_scalarmult_scalarbytes() == crypto_scalarmult_curve25519_scalarbytes()); assert(crypto_scalarmult_bytes() == crypto_scalarmult_scalarbytes()); return 0; }
gpl-3.0
CertifiedBlyndGuy/ewok-onyx
drivers/media/rc/rc-loopback.c
5462
6448
/* * Loopback driver for rc-core, * * Copyright (c) 2010 David Härdeman <david@hardeman.nu> * * This driver receives TX data and passes it back as RX data, * which is useful for (scripted) debugging of rc-core without * having to use actual hardware. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ #include <linux/device.h> #include <linux/module.h> #include <linux/sched.h> #include <media/rc-core.h> #define DRIVER_NAME "rc-loopback" #define dprintk(x...) if (debug) printk(KERN_INFO DRIVER_NAME ": " x) #define RXMASK_REGULAR 0x1 #define RXMASK_LEARNING 0x2 static bool debug; struct loopback_dev { struct rc_dev *dev; u32 txmask; u32 txcarrier; u32 txduty; bool idle; bool learning; bool carrierreport; u32 rxcarriermin; u32 rxcarriermax; }; static struct loopback_dev loopdev; static int loop_set_tx_mask(struct rc_dev *dev, u32 mask) { struct loopback_dev *lodev = dev->priv; if ((mask & (RXMASK_REGULAR | RXMASK_LEARNING)) != mask) { dprintk("invalid tx mask: %u\n", mask); return -EINVAL; } dprintk("setting tx mask: %u\n", mask); lodev->txmask = mask; return 0; } static int loop_set_tx_carrier(struct rc_dev *dev, u32 carrier) { struct loopback_dev *lodev = dev->priv; dprintk("setting tx carrier: %u\n", carrier); lodev->txcarrier = carrier; return 0; } static int loop_set_tx_duty_cycle(struct rc_dev *dev, u32 duty_cycle) { struct loopback_dev *lodev = dev->priv; if (duty_cycle < 1 || duty_cycle > 99) { dprintk("invalid duty cycle: %u\n", duty_cycle); return -EINVAL; } dprintk("setting duty cycle: %u\n", duty_cycle); lodev->txduty = duty_cycle; return 0; } static int loop_set_rx_carrier_range(struct rc_dev *dev, u32 min, u32 max) { struct loopback_dev *lodev = dev->priv; if (min < 1 || min > max) { dprintk("invalid rx carrier range %u to %u\n", min, max); return -EINVAL; } dprintk("setting rx carrier range %u to %u\n", min, max); lodev->rxcarriermin = min; lodev->rxcarriermax = max; return 0; } static int loop_tx_ir(struct rc_dev *dev, unsigned *txbuf, unsigned count) { struct loopback_dev *lodev = dev->priv; u32 rxmask; unsigned total_duration = 0; unsigned i; DEFINE_IR_RAW_EVENT(rawir); for (i = 0; i < count; i++) total_duration += abs(txbuf[i]); if (total_duration == 0) { dprintk("invalid tx data, total duration zero\n"); return -EINVAL; } if (lodev->txcarrier < lodev->rxcarriermin || lodev->txcarrier > lodev->rxcarriermax) { dprintk("ignoring tx, carrier out of range\n"); goto out; } if (lodev->learning) rxmask = RXMASK_LEARNING; else rxmask = RXMASK_REGULAR; if (!(rxmask & lodev->txmask)) { dprintk("ignoring tx, rx mask mismatch\n"); goto out; } for (i = 0; i < count; i++) { rawir.pulse = i % 2 ? false : true; rawir.duration = txbuf[i] * 1000; if (rawir.duration) ir_raw_event_store_with_filter(dev, &rawir); } /* Fake a silence long enough to cause us to go idle */ rawir.pulse = false; rawir.duration = dev->timeout; ir_raw_event_store_with_filter(dev, &rawir); ir_raw_event_handle(dev); out: /* Lirc expects this function to take as long as the total duration */ set_current_state(TASK_INTERRUPTIBLE); schedule_timeout(usecs_to_jiffies(total_duration)); return count; } static void loop_set_idle(struct rc_dev *dev, bool enable) { struct loopback_dev *lodev = dev->priv; if (lodev->idle != enable) { dprintk("%sing idle mode\n", enable ? "enter" : "exit"); lodev->idle = enable; } } static int loop_set_learning_mode(struct rc_dev *dev, int enable) { struct loopback_dev *lodev = dev->priv; if (lodev->learning != enable) { dprintk("%sing learning mode\n", enable ? "enter" : "exit"); lodev->learning = !!enable; } return 0; } static int loop_set_carrier_report(struct rc_dev *dev, int enable) { struct loopback_dev *lodev = dev->priv; if (lodev->carrierreport != enable) { dprintk("%sabling carrier reports\n", enable ? "en" : "dis"); lodev->carrierreport = !!enable; } return 0; } static int __init loop_init(void) { struct rc_dev *rc; int ret; rc = rc_allocate_device(); if (!rc) { printk(KERN_ERR DRIVER_NAME ": rc_dev allocation failed\n"); return -ENOMEM; } rc->input_name = "rc-core loopback device"; rc->input_phys = "rc-core/virtual"; rc->input_id.bustype = BUS_VIRTUAL; rc->input_id.version = 1; rc->driver_name = DRIVER_NAME; rc->map_name = RC_MAP_EMPTY; rc->priv = &loopdev; rc->driver_type = RC_DRIVER_IR_RAW; rc->allowed_protos = RC_TYPE_ALL; rc->timeout = 100 * 1000 * 1000; /* 100 ms */ rc->min_timeout = 1; rc->max_timeout = UINT_MAX; rc->rx_resolution = 1000; rc->tx_resolution = 1000; rc->s_tx_mask = loop_set_tx_mask; rc->s_tx_carrier = loop_set_tx_carrier; rc->s_tx_duty_cycle = loop_set_tx_duty_cycle; rc->s_rx_carrier_range = loop_set_rx_carrier_range; rc->tx_ir = loop_tx_ir; rc->s_idle = loop_set_idle; rc->s_learning_mode = loop_set_learning_mode; rc->s_carrier_report = loop_set_carrier_report; rc->priv = &loopdev; loopdev.txmask = RXMASK_REGULAR; loopdev.txcarrier = 36000; loopdev.txduty = 50; loopdev.rxcarriermin = 1; loopdev.rxcarriermax = ~0; loopdev.idle = true; loopdev.learning = false; loopdev.carrierreport = false; ret = rc_register_device(rc); if (ret < 0) { printk(KERN_ERR DRIVER_NAME ": rc_dev registration failed\n"); rc_free_device(rc); return ret; } loopdev.dev = rc; return 0; } static void __exit loop_exit(void) { rc_unregister_device(loopdev.dev); } module_init(loop_init); module_exit(loop_exit); module_param(debug, bool, S_IRUGO | S_IWUSR); MODULE_PARM_DESC(debug, "Enable debug messages"); MODULE_DESCRIPTION("Loopback device for rc-core debugging"); MODULE_AUTHOR("David Härdeman <david@hardeman.nu>"); MODULE_LICENSE("GPL");
gpl-3.0
adomasalcore3/android_kernel_Vodafone_VDF600
fs/btrfs/extent_map.c
1634
10917
#include <linux/err.h> #include <linux/slab.h> #include <linux/spinlock.h> #include <linux/hardirq.h> #include "ctree.h" #include "extent_map.h" static struct kmem_cache *extent_map_cache; int __init extent_map_init(void) { extent_map_cache = kmem_cache_create("btrfs_extent_map", sizeof(struct extent_map), 0, SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL); if (!extent_map_cache) return -ENOMEM; return 0; } void extent_map_exit(void) { if (extent_map_cache) kmem_cache_destroy(extent_map_cache); } /** * extent_map_tree_init - initialize extent map tree * @tree: tree to initialize * * Initialize the extent tree @tree. Should be called for each new inode * or other user of the extent_map interface. */ void extent_map_tree_init(struct extent_map_tree *tree) { tree->map = RB_ROOT; INIT_LIST_HEAD(&tree->modified_extents); rwlock_init(&tree->lock); } /** * alloc_extent_map - allocate new extent map structure * * Allocate a new extent_map structure. The new structure is * returned with a reference count of one and needs to be * freed using free_extent_map() */ struct extent_map *alloc_extent_map(void) { struct extent_map *em; em = kmem_cache_zalloc(extent_map_cache, GFP_NOFS); if (!em) return NULL; em->in_tree = 0; em->flags = 0; em->compress_type = BTRFS_COMPRESS_NONE; em->generation = 0; atomic_set(&em->refs, 1); INIT_LIST_HEAD(&em->list); return em; } /** * free_extent_map - drop reference count of an extent_map * @em: extent map beeing releasead * * Drops the reference out on @em by one and free the structure * if the reference count hits zero. */ void free_extent_map(struct extent_map *em) { if (!em) return; WARN_ON(atomic_read(&em->refs) == 0); if (atomic_dec_and_test(&em->refs)) { WARN_ON(em->in_tree); WARN_ON(!list_empty(&em->list)); kmem_cache_free(extent_map_cache, em); } } static struct rb_node *tree_insert(struct rb_root *root, u64 offset, struct rb_node *node) { struct rb_node **p = &root->rb_node; struct rb_node *parent = NULL; struct extent_map *entry; while (*p) { parent = *p; entry = rb_entry(parent, struct extent_map, rb_node); WARN_ON(!entry->in_tree); if (offset < entry->start) p = &(*p)->rb_left; else if (offset >= extent_map_end(entry)) p = &(*p)->rb_right; else return parent; } entry = rb_entry(node, struct extent_map, rb_node); entry->in_tree = 1; rb_link_node(node, parent, p); rb_insert_color(node, root); return NULL; } /* * search through the tree for an extent_map with a given offset. If * it can't be found, try to find some neighboring extents */ static struct rb_node *__tree_search(struct rb_root *root, u64 offset, struct rb_node **prev_ret, struct rb_node **next_ret) { struct rb_node *n = root->rb_node; struct rb_node *prev = NULL; struct rb_node *orig_prev = NULL; struct extent_map *entry; struct extent_map *prev_entry = NULL; while (n) { entry = rb_entry(n, struct extent_map, rb_node); prev = n; prev_entry = entry; WARN_ON(!entry->in_tree); if (offset < entry->start) n = n->rb_left; else if (offset >= extent_map_end(entry)) n = n->rb_right; else return n; } if (prev_ret) { orig_prev = prev; while (prev && offset >= extent_map_end(prev_entry)) { prev = rb_next(prev); prev_entry = rb_entry(prev, struct extent_map, rb_node); } *prev_ret = prev; prev = orig_prev; } if (next_ret) { prev_entry = rb_entry(prev, struct extent_map, rb_node); while (prev && offset < prev_entry->start) { prev = rb_prev(prev); prev_entry = rb_entry(prev, struct extent_map, rb_node); } *next_ret = prev; } return NULL; } /* check to see if two extent_map structs are adjacent and safe to merge */ static int mergable_maps(struct extent_map *prev, struct extent_map *next) { if (test_bit(EXTENT_FLAG_PINNED, &prev->flags)) return 0; /* * don't merge compressed extents, we need to know their * actual size */ if (test_bit(EXTENT_FLAG_COMPRESSED, &prev->flags)) return 0; if (test_bit(EXTENT_FLAG_LOGGING, &prev->flags) || test_bit(EXTENT_FLAG_LOGGING, &next->flags)) return 0; /* * We don't want to merge stuff that hasn't been written to the log yet * since it may not reflect exactly what is on disk, and that would be * bad. */ if (!list_empty(&prev->list) || !list_empty(&next->list)) return 0; if (extent_map_end(prev) == next->start && prev->flags == next->flags && prev->bdev == next->bdev && ((next->block_start == EXTENT_MAP_HOLE && prev->block_start == EXTENT_MAP_HOLE) || (next->block_start == EXTENT_MAP_INLINE && prev->block_start == EXTENT_MAP_INLINE) || (next->block_start == EXTENT_MAP_DELALLOC && prev->block_start == EXTENT_MAP_DELALLOC) || (next->block_start < EXTENT_MAP_LAST_BYTE - 1 && next->block_start == extent_map_block_end(prev)))) { return 1; } return 0; } static void try_merge_map(struct extent_map_tree *tree, struct extent_map *em) { struct extent_map *merge = NULL; struct rb_node *rb; if (em->start != 0) { rb = rb_prev(&em->rb_node); if (rb) merge = rb_entry(rb, struct extent_map, rb_node); if (rb && mergable_maps(merge, em)) { em->start = merge->start; em->orig_start = merge->orig_start; em->len += merge->len; em->block_len += merge->block_len; em->block_start = merge->block_start; merge->in_tree = 0; em->mod_len = (em->mod_len + em->mod_start) - merge->mod_start; em->mod_start = merge->mod_start; em->generation = max(em->generation, merge->generation); rb_erase(&merge->rb_node, &tree->map); free_extent_map(merge); } } rb = rb_next(&em->rb_node); if (rb) merge = rb_entry(rb, struct extent_map, rb_node); if (rb && mergable_maps(em, merge)) { em->len += merge->len; em->block_len += merge->len; rb_erase(&merge->rb_node, &tree->map); merge->in_tree = 0; em->mod_len = (merge->mod_start + merge->mod_len) - em->mod_start; em->generation = max(em->generation, merge->generation); free_extent_map(merge); } } /** * unpin_extent_cache - unpin an extent from the cache * @tree: tree to unpin the extent in * @start: logical offset in the file * @len: length of the extent * @gen: generation that this extent has been modified in * * Called after an extent has been written to disk properly. Set the generation * to the generation that actually added the file item to the inode so we know * we need to sync this extent when we call fsync(). */ int unpin_extent_cache(struct extent_map_tree *tree, u64 start, u64 len, u64 gen) { int ret = 0; struct extent_map *em; bool prealloc = false; write_lock(&tree->lock); em = lookup_extent_mapping(tree, start, len); WARN_ON(!em || em->start != start); if (!em) goto out; if (!test_bit(EXTENT_FLAG_LOGGING, &em->flags)) list_move(&em->list, &tree->modified_extents); em->generation = gen; clear_bit(EXTENT_FLAG_PINNED, &em->flags); em->mod_start = em->start; em->mod_len = em->len; if (test_bit(EXTENT_FLAG_FILLING, &em->flags)) { prealloc = true; clear_bit(EXTENT_FLAG_FILLING, &em->flags); } try_merge_map(tree, em); if (prealloc) { em->mod_start = em->start; em->mod_len = em->len; } free_extent_map(em); out: write_unlock(&tree->lock); return ret; } void clear_em_logging(struct extent_map_tree *tree, struct extent_map *em) { clear_bit(EXTENT_FLAG_LOGGING, &em->flags); if (em->in_tree) try_merge_map(tree, em); } /** * add_extent_mapping - add new extent map to the extent tree * @tree: tree to insert new map in * @em: map to insert * * Insert @em into @tree or perform a simple forward/backward merge with * existing mappings. The extent_map struct passed in will be inserted * into the tree directly, with an additional reference taken, or a * reference dropped if the merge attempt was successful. */ int add_extent_mapping(struct extent_map_tree *tree, struct extent_map *em, int modified) { int ret = 0; struct rb_node *rb; struct extent_map *exist; exist = lookup_extent_mapping(tree, em->start, em->len); if (exist) { free_extent_map(exist); ret = -EEXIST; goto out; } rb = tree_insert(&tree->map, em->start, &em->rb_node); if (rb) { ret = -EEXIST; goto out; } atomic_inc(&em->refs); em->mod_start = em->start; em->mod_len = em->len; if (modified) list_move(&em->list, &tree->modified_extents); else try_merge_map(tree, em); out: return ret; } /* simple helper to do math around the end of an extent, handling wrap */ static u64 range_end(u64 start, u64 len) { if (start + len < start) return (u64)-1; return start + len; } static struct extent_map * __lookup_extent_mapping(struct extent_map_tree *tree, u64 start, u64 len, int strict) { struct extent_map *em; struct rb_node *rb_node; struct rb_node *prev = NULL; struct rb_node *next = NULL; u64 end = range_end(start, len); rb_node = __tree_search(&tree->map, start, &prev, &next); if (!rb_node) { if (prev) rb_node = prev; else if (next) rb_node = next; else return NULL; } em = rb_entry(rb_node, struct extent_map, rb_node); if (strict && !(end > em->start && start < extent_map_end(em))) return NULL; atomic_inc(&em->refs); return em; } /** * lookup_extent_mapping - lookup extent_map * @tree: tree to lookup in * @start: byte offset to start the search * @len: length of the lookup range * * Find and return the first extent_map struct in @tree that intersects the * [start, len] range. There may be additional objects in the tree that * intersect, so check the object returned carefully to make sure that no * additional lookups are needed. */ struct extent_map *lookup_extent_mapping(struct extent_map_tree *tree, u64 start, u64 len) { return __lookup_extent_mapping(tree, start, len, 1); } /** * search_extent_mapping - find a nearby extent map * @tree: tree to lookup in * @start: byte offset to start the search * @len: length of the lookup range * * Find and return the first extent_map struct in @tree that intersects the * [start, len] range. * * If one can't be found, any nearby extent may be returned */ struct extent_map *search_extent_mapping(struct extent_map_tree *tree, u64 start, u64 len) { return __lookup_extent_mapping(tree, start, len, 0); } /** * remove_extent_mapping - removes an extent_map from the extent tree * @tree: extent tree to remove from * @em: extent map beeing removed * * Removes @em from @tree. No reference counts are dropped, and no checks * are done to see if the range is in use */ int remove_extent_mapping(struct extent_map_tree *tree, struct extent_map *em) { int ret = 0; WARN_ON(test_bit(EXTENT_FLAG_PINNED, &em->flags)); rb_erase(&em->rb_node, &tree->map); if (!test_bit(EXTENT_FLAG_LOGGING, &em->flags)) list_del_init(&em->list); em->in_tree = 0; return ret; }
gpl-3.0
jeichenhofer/chuck-light
SoC/software/spl_bsp/uboot-socfpga/board/freescale/common/pixis.c
102
12089
/* * Copyright 2006,2010 Freescale Semiconductor * Jeff Brown * Srikanth Srinivasan (srikanth.srinivasan@freescale.com) * * See file CREDITS for list of people who contributed to this * project. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ #include <common.h> #include <command.h> #include <asm/io.h> #define pixis_base (u8 *)PIXIS_BASE /* * Simple board reset. */ void pixis_reset(void) { out_8(pixis_base + PIXIS_RST, 0); while (1); } /* * Per table 27, page 58 of MPC8641HPCN spec. */ static int set_px_sysclk(unsigned long sysclk) { u8 sysclk_s, sysclk_r, sysclk_v, vclkh, vclkl, sysclk_aux; switch (sysclk) { case 33: sysclk_s = 0x04; sysclk_r = 0x04; sysclk_v = 0x07; sysclk_aux = 0x00; break; case 40: sysclk_s = 0x01; sysclk_r = 0x1F; sysclk_v = 0x20; sysclk_aux = 0x01; break; case 50: sysclk_s = 0x01; sysclk_r = 0x1F; sysclk_v = 0x2A; sysclk_aux = 0x02; break; case 66: sysclk_s = 0x01; sysclk_r = 0x04; sysclk_v = 0x04; sysclk_aux = 0x03; break; case 83: sysclk_s = 0x01; sysclk_r = 0x1F; sysclk_v = 0x4B; sysclk_aux = 0x04; break; case 100: sysclk_s = 0x01; sysclk_r = 0x1F; sysclk_v = 0x5C; sysclk_aux = 0x05; break; case 134: sysclk_s = 0x06; sysclk_r = 0x1F; sysclk_v = 0x3B; sysclk_aux = 0x06; break; case 166: sysclk_s = 0x06; sysclk_r = 0x1F; sysclk_v = 0x4B; sysclk_aux = 0x07; break; default: printf("Unsupported SYSCLK frequency.\n"); return 0; } vclkh = (sysclk_s << 5) | sysclk_r; vclkl = sysclk_v; out_8(pixis_base + PIXIS_VCLKH, vclkh); out_8(pixis_base + PIXIS_VCLKL, vclkl); out_8(pixis_base + PIXIS_AUX, sysclk_aux); return 1; } /* Set the CFG_SYSPLL bits * * This only has effect if PX_VCFGEN0[SYSPLL]=1, which is true if * read_from_px_regs() is called. */ static int set_px_mpxpll(unsigned long mpxpll) { switch (mpxpll) { case 2: case 4: case 6: case 8: case 10: case 12: case 14: case 16: clrsetbits_8(pixis_base + PIXIS_VSPEED1, 0x1F, mpxpll); return 1; } printf("Unsupported MPXPLL ratio.\n"); return 0; } static int set_px_corepll(unsigned long corepll) { u8 val; switch (corepll) { case 20: val = 0x08; break; case 25: val = 0x0C; break; case 30: val = 0x10; break; case 35: val = 0x1C; break; case 40: val = 0x14; break; case 45: val = 0x0E; break; default: printf("Unsupported COREPLL ratio.\n"); return 0; } clrsetbits_8(pixis_base + PIXIS_VSPEED0, 0x1F, val); return 1; } #ifndef CONFIG_SYS_PIXIS_VCFGEN0_ENABLE #define CONFIG_SYS_PIXIS_VCFGEN0_ENABLE 0x1C #endif /* Tell the PIXIS where to find the COREPLL, MPXPLL, SYSCLK values * * The PIXIS can be programmed to look at either the on-board dip switches * or various other PIXIS registers to determine the values for COREPLL, * MPXPLL, and SYSCLK. * * CONFIG_SYS_PIXIS_VCFGEN0_ENABLE is the value to write to the PIXIS_VCFGEN0 * register that tells the pixis to use the various PIXIS register. */ static void read_from_px_regs(int set) { u8 tmp = in_8(pixis_base + PIXIS_VCFGEN0); if (set) tmp = tmp | CONFIG_SYS_PIXIS_VCFGEN0_ENABLE; else tmp = tmp & ~CONFIG_SYS_PIXIS_VCFGEN0_ENABLE; out_8(pixis_base + PIXIS_VCFGEN0, tmp); } /* CONFIG_SYS_PIXIS_VBOOT_ENABLE is the value to write to the PX_VCFGEN1 * register that tells the pixis to use the PX_VBOOT[LBMAP] register. */ #ifndef CONFIG_SYS_PIXIS_VBOOT_ENABLE #define CONFIG_SYS_PIXIS_VBOOT_ENABLE 0x04 #endif /* Configure the source of the boot location * * The PIXIS can be programmed to look at either the on-board dip switches * or the PX_VBOOT[LBMAP] register to determine where we should boot. * * If we want to boot from the alternate boot bank, we need to tell the PIXIS * to ignore the on-board dip switches and use the PX_VBOOT[LBMAP] instead. */ static void read_from_px_regs_altbank(int set) { u8 tmp = in_8(pixis_base + PIXIS_VCFGEN1); if (set) tmp = tmp | CONFIG_SYS_PIXIS_VBOOT_ENABLE; else tmp = tmp & ~CONFIG_SYS_PIXIS_VBOOT_ENABLE; out_8(pixis_base + PIXIS_VCFGEN1, tmp); } /* CONFIG_SYS_PIXIS_VBOOT_MASK contains the bits to set in VBOOT register that * tells the PIXIS what the alternate flash bank is. * * Note that it's not really a mask. It contains the actual LBMAP bits that * must be set to select the alternate bank. This code assumes that the * primary bank has these bits set to 0, and the alternate bank has these * bits set to 1. */ #ifndef CONFIG_SYS_PIXIS_VBOOT_MASK #define CONFIG_SYS_PIXIS_VBOOT_MASK (0x40) #endif /* Tell the PIXIS to boot from the default flash bank * * Program the default flash bank into the VBOOT register. This register is * used only if PX_VCFGEN1[FLASH]=1. */ static void clear_altbank(void) { clrbits_8(pixis_base + PIXIS_VBOOT, CONFIG_SYS_PIXIS_VBOOT_MASK); } /* Tell the PIXIS to boot from the alternate flash bank * * Program the alternate flash bank into the VBOOT register. This register is * used only if PX_VCFGEN1[FLASH]=1. */ static void set_altbank(void) { setbits_8(pixis_base + PIXIS_VBOOT, CONFIG_SYS_PIXIS_VBOOT_MASK); } /* Reset the board with watchdog disabled. * * This respects the altbank setting. */ static void set_px_go(void) { /* Disable the VELA sequencer and watchdog */ clrbits_8(pixis_base + PIXIS_VCTL, 9); /* Reboot by starting the VELA sequencer */ setbits_8(pixis_base + PIXIS_VCTL, 0x1); while (1); } /* Reset the board with watchdog enabled. * * This respects the altbank setting. */ static void set_px_go_with_watchdog(void) { /* Disable the VELA sequencer */ clrbits_8(pixis_base + PIXIS_VCTL, 1); /* Enable the watchdog and reboot by starting the VELA sequencer */ setbits_8(pixis_base + PIXIS_VCTL, 0x9); while (1); } /* Disable the watchdog * */ static int pixis_disable_watchdog_cmd(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[]) { /* Disable the VELA sequencer and the watchdog */ clrbits_8(pixis_base + PIXIS_VCTL, 9); return 0; } U_BOOT_CMD( diswd, 1, 0, pixis_disable_watchdog_cmd, "Disable watchdog timer", "" ); #ifdef CONFIG_PIXIS_SGMII_CMD /* Enable or disable SGMII mode for a TSEC */ static int pixis_set_sgmii(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[]) { int which_tsec = -1; unsigned char mask; unsigned char switch_mask; if ((argc > 2) && (strcmp(argv[1], "all") != 0)) which_tsec = simple_strtoul(argv[1], NULL, 0); switch (which_tsec) { #ifdef CONFIG_TSEC1 case 1: mask = PIXIS_VSPEED2_TSEC1SER; switch_mask = PIXIS_VCFGEN1_TSEC1SER; break; #endif #ifdef CONFIG_TSEC2 case 2: mask = PIXIS_VSPEED2_TSEC2SER; switch_mask = PIXIS_VCFGEN1_TSEC2SER; break; #endif #ifdef CONFIG_TSEC3 case 3: mask = PIXIS_VSPEED2_TSEC3SER; switch_mask = PIXIS_VCFGEN1_TSEC3SER; break; #endif #ifdef CONFIG_TSEC4 case 4: mask = PIXIS_VSPEED2_TSEC4SER; switch_mask = PIXIS_VCFGEN1_TSEC4SER; break; #endif default: mask = PIXIS_VSPEED2_MASK; switch_mask = PIXIS_VCFGEN1_MASK; break; } /* Toggle whether the switches or FPGA control the settings */ if (!strcmp(argv[argc - 1], "switch")) clrbits_8(pixis_base + PIXIS_VCFGEN1, switch_mask); else setbits_8(pixis_base + PIXIS_VCFGEN1, switch_mask); /* If it's not the switches, enable or disable SGMII, as specified */ if (!strcmp(argv[argc - 1], "on")) clrbits_8(pixis_base + PIXIS_VSPEED2, mask); else if (!strcmp(argv[argc - 1], "off")) setbits_8(pixis_base + PIXIS_VSPEED2, mask); return 0; } U_BOOT_CMD( pixis_set_sgmii, CONFIG_SYS_MAXARGS, 1, pixis_set_sgmii, "pixis_set_sgmii" " - Enable or disable SGMII mode for a given TSEC \n", "\npixis_set_sgmii [TSEC num] <on|off|switch>\n" " TSEC num: 1,2,3,4 or 'all'. 'all' is default.\n" " on - enables SGMII\n" " off - disables SGMII\n" " switch - use switch settings" ); #endif /* * This function takes the non-integral cpu:mpx pll ratio * and converts it to an integer that can be used to assign * FPGA register values. * input: strptr i.e. argv[2] */ static unsigned long strfractoint(char *strptr) { int i, j; int mulconst; int no_dec = 0; unsigned long intval = 0, decval = 0; char intarr[3], decarr[3]; /* Assign the integer part to intarr[] * If there is no decimal point i.e. * if the ratio is an integral value * simply create the intarr. */ i = 0; while (strptr[i] != '.') { if (strptr[i] == 0) { no_dec = 1; break; } intarr[i] = strptr[i]; i++; } intarr[i] = '\0'; if (no_dec) { /* Currently needed only for single digit corepll ratios */ mulconst = 10; decval = 0; } else { j = 0; i++; /* Skipping the decimal point */ while ((strptr[i] >= '0') && (strptr[i] <= '9')) { decarr[j] = strptr[i]; i++; j++; } decarr[j] = '\0'; mulconst = 1; for (i = 0; i < j; i++) mulconst *= 10; decval = simple_strtoul(decarr, NULL, 10); } intval = simple_strtoul(intarr, NULL, 10); intval = intval * mulconst; return intval + decval; } static int pixis_reset_cmd(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[]) { unsigned int i; char *p_cf = NULL; char *p_cf_sysclk = NULL; char *p_cf_corepll = NULL; char *p_cf_mpxpll = NULL; char *p_altbank = NULL; char *p_wd = NULL; int unknown_param = 0; /* * No args is a simple reset request. */ if (argc <= 1) { pixis_reset(); /* not reached */ } for (i = 1; i < argc; i++) { if (strcmp(argv[i], "cf") == 0) { p_cf = argv[i]; if (i + 3 >= argc) { break; } p_cf_sysclk = argv[i+1]; p_cf_corepll = argv[i+2]; p_cf_mpxpll = argv[i+3]; i += 3; continue; } if (strcmp(argv[i], "altbank") == 0) { p_altbank = argv[i]; continue; } if (strcmp(argv[i], "wd") == 0) { p_wd = argv[i]; continue; } unknown_param = 1; } /* * Check that cf has all required parms */ if ((p_cf && !(p_cf_sysclk && p_cf_corepll && p_cf_mpxpll)) || unknown_param) { #ifdef CONFIG_SYS_LONGHELP puts(cmdtp->help); #endif return 1; } /* * PIXIS seems to be sensitive to the ordering of * the registers that are touched. */ read_from_px_regs(0); if (p_altbank) read_from_px_regs_altbank(0); clear_altbank(); /* * Clock configuration specified. */ if (p_cf) { unsigned long sysclk; unsigned long corepll; unsigned long mpxpll; sysclk = simple_strtoul(p_cf_sysclk, NULL, 10); corepll = strfractoint(p_cf_corepll); mpxpll = simple_strtoul(p_cf_mpxpll, NULL, 10); if (!(set_px_sysclk(sysclk) && set_px_corepll(corepll) && set_px_mpxpll(mpxpll))) { #ifdef CONFIG_SYS_LONGHELP puts(cmdtp->help); #endif return 1; } read_from_px_regs(1); } /* * Altbank specified * * NOTE CHANGE IN BEHAVIOR: previous code would default * to enabling watchdog if altbank is specified. * Now the watchdog must be enabled explicitly using 'wd'. */ if (p_altbank) { set_altbank(); read_from_px_regs_altbank(1); } /* * Reset with watchdog specified. */ if (p_wd) set_px_go_with_watchdog(); else set_px_go(); /* * Shouldn't be reached. */ return 0; } U_BOOT_CMD( pixis_reset, CONFIG_SYS_MAXARGS, 1, pixis_reset_cmd, "Reset the board using the FPGA sequencer", " pixis_reset\n" " pixis_reset [altbank]\n" " pixis_reset altbank wd\n" " pixis_reset altbank cf <SYSCLK freq> <COREPLL ratio> <MPXPLL ratio>\n" " pixis_reset cf <SYSCLK freq> <COREPLL ratio> <MPXPLL ratio>" );
gpl-3.0
d1b/TextSecure
jni/openssl/crypto/x509/x509_d2.c
876
4337
/* crypto/x509/x509_d2.c */ /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * * This package is an SSL implementation written * by Eric Young (eay@cryptsoft.com). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson (tjh@cryptsoft.com). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes cryptographic software written by * Eric Young (eay@cryptsoft.com)" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ #include <stdio.h> #include "cryptlib.h" #include <openssl/crypto.h> #include <openssl/x509.h> #ifndef OPENSSL_NO_STDIO int X509_STORE_set_default_paths(X509_STORE *ctx) { X509_LOOKUP *lookup; lookup=X509_STORE_add_lookup(ctx,X509_LOOKUP_file()); if (lookup == NULL) return(0); X509_LOOKUP_load_file(lookup,NULL,X509_FILETYPE_DEFAULT); lookup=X509_STORE_add_lookup(ctx,X509_LOOKUP_hash_dir()); if (lookup == NULL) return(0); X509_LOOKUP_add_dir(lookup,NULL,X509_FILETYPE_DEFAULT); /* clear any errors */ ERR_clear_error(); return(1); } int X509_STORE_load_locations(X509_STORE *ctx, const char *file, const char *path) { X509_LOOKUP *lookup; if (file != NULL) { lookup=X509_STORE_add_lookup(ctx,X509_LOOKUP_file()); if (lookup == NULL) return(0); if (X509_LOOKUP_load_file(lookup,file,X509_FILETYPE_PEM) != 1) return(0); } if (path != NULL) { lookup=X509_STORE_add_lookup(ctx,X509_LOOKUP_hash_dir()); if (lookup == NULL) return(0); if (X509_LOOKUP_add_dir(lookup,path,X509_FILETYPE_PEM) != 1) return(0); } if ((path == NULL) && (file == NULL)) return(0); return(1); } #endif
gpl-3.0
chkamil/ardupilot
ArduCopter/control_flip.cpp
114
8881
/// -*- tab-width: 4; Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- #include "Copter.h" /* * control_flip.pde - init and run calls for flip flight mode * original implementation in 2010 by Jose Julio * Adapted and updated for AC2 in 2011 by Jason Short * * Controls: * CH7_OPT - CH12_OPT parameter must be set to "Flip" (AUXSW_FLIP) which is "2" * Pilot switches to Stabilize, Acro or AltHold flight mode and puts ch7/ch8 switch to ON position * Vehicle will Roll right by default but if roll or pitch stick is held slightly left, forward or back it will flip in that direction * Vehicle should complete the roll within 2.5sec and will then return to the original flight mode it was in before flip was triggered * Pilot may manually exit flip by switching off ch7/ch8 or by moving roll stick to >40deg left or right * * State machine approach: * Flip_Start (while copter is leaning <45deg) : roll right at 400deg/sec, increase throttle * Flip_Roll (while copter is between +45deg ~ -90) : roll right at 400deg/sec, reduce throttle * Flip_Recover (while copter is between -90deg and original target angle) : use earth frame angle controller to return vehicle to original attitude */ #define FLIP_THR_INC 200 // throttle increase during Flip_Start stage (under 45deg lean angle) #define FLIP_THR_DEC 240 // throttle decrease during Flip_Roll stage (between 45deg ~ -90deg roll) #define FLIP_ROTATION_RATE 40000 // rotation rate request in centi-degrees / sec (i.e. 400 deg/sec) #define FLIP_TIMEOUT_MS 2500 // timeout after 2.5sec. Vehicle will switch back to original flight mode #define FLIP_RECOVERY_ANGLE 500 // consider successful recovery when roll is back within 5 degrees of original #define FLIP_ROLL_RIGHT 1 // used to set flip_dir #define FLIP_ROLL_LEFT -1 // used to set flip_dir #define FLIP_PITCH_BACK 1 // used to set flip_dir #define FLIP_PITCH_FORWARD -1 // used to set flip_dir FlipState flip_state; // current state of flip uint8_t flip_orig_control_mode; // flight mode when flip was initated uint32_t flip_start_time; // time since flip began int8_t flip_roll_dir; // roll direction (-1 = roll left, 1 = roll right) int8_t flip_pitch_dir; // pitch direction (-1 = pitch forward, 1 = pitch back) // flip_init - initialise flip controller bool Copter::flip_init(bool ignore_checks) { // only allow flip from ACRO, Stabilize, AltHold or Drift flight modes if (control_mode != ACRO && control_mode != STABILIZE && control_mode != ALT_HOLD) { return false; } // if in acro or stabilize ensure throttle is above zero if (ap.throttle_zero && (control_mode == ACRO || control_mode == STABILIZE)) { return false; } // ensure roll input is less than 40deg if (abs(channel_roll->control_in) >= 4000) { return false; } // only allow flip when flying if (!motors.armed() || ap.land_complete) { return false; } // capture original flight mode so that we can return to it after completion flip_orig_control_mode = control_mode; // initialise state flip_state = Flip_Start; flip_start_time = millis(); flip_roll_dir = flip_pitch_dir = 0; // choose direction based on pilot's roll and pitch sticks if (channel_pitch->control_in > 300) { flip_pitch_dir = FLIP_PITCH_BACK; }else if(channel_pitch->control_in < -300) { flip_pitch_dir = FLIP_PITCH_FORWARD; }else if (channel_roll->control_in >= 0) { flip_roll_dir = FLIP_ROLL_RIGHT; }else{ flip_roll_dir = FLIP_ROLL_LEFT; } // log start of flip Log_Write_Event(DATA_FLIP_START); // capture current attitude which will be used during the Flip_Recovery stage flip_orig_attitude.x = constrain_float(ahrs.roll_sensor, -aparm.angle_max, aparm.angle_max); flip_orig_attitude.y = constrain_float(ahrs.pitch_sensor, -aparm.angle_max, aparm.angle_max); flip_orig_attitude.z = ahrs.yaw_sensor; return true; } // flip_run - runs the flip controller // should be called at 100hz or more void Copter::flip_run() { int16_t throttle_out; float recovery_angle; // if pilot inputs roll > 40deg or timeout occurs abandon flip if (!motors.armed() || (abs(channel_roll->control_in) >= 4000) || (abs(channel_pitch->control_in) >= 4000) || ((millis() - flip_start_time) > FLIP_TIMEOUT_MS)) { flip_state = Flip_Abandon; } // get pilot's desired throttle throttle_out = get_pilot_desired_throttle(channel_throttle->control_in); // get corrected angle based on direction and axis of rotation // we flip the sign of flip_angle to minimize the code repetition int32_t flip_angle; if (flip_roll_dir != 0) { flip_angle = ahrs.roll_sensor * flip_roll_dir; } else { flip_angle = ahrs.pitch_sensor * flip_pitch_dir; } // state machine switch (flip_state) { case Flip_Start: // under 45 degrees request 400deg/sec roll or pitch attitude_control.rate_bf_roll_pitch_yaw(FLIP_ROTATION_RATE * flip_roll_dir, FLIP_ROTATION_RATE * flip_pitch_dir, 0.0); // increase throttle throttle_out += FLIP_THR_INC; // beyond 45deg lean angle move to next stage if (flip_angle >= 4500) { if (flip_roll_dir != 0) { // we are rolling flip_state = Flip_Roll; } else { // we are pitching flip_state = Flip_Pitch_A; } } break; case Flip_Roll: // between 45deg ~ -90deg request 400deg/sec roll attitude_control.rate_bf_roll_pitch_yaw(FLIP_ROTATION_RATE * flip_roll_dir, 0.0, 0.0); // decrease throttle if (throttle_out >= g.throttle_min) { throttle_out = max(throttle_out - FLIP_THR_DEC, g.throttle_min); } // beyond -90deg move on to recovery if ((flip_angle < 4500) && (flip_angle > -9000)) { flip_state = Flip_Recover; } break; case Flip_Pitch_A: // between 45deg ~ -90deg request 400deg/sec pitch attitude_control.rate_bf_roll_pitch_yaw(0.0, FLIP_ROTATION_RATE * flip_pitch_dir, 0.0); // decrease throttle if (throttle_out >= g.throttle_min) { throttle_out = max(throttle_out - FLIP_THR_DEC, g.throttle_min); } // check roll for inversion if ((labs(ahrs.roll_sensor) > 9000) && (flip_angle > 4500)) { flip_state = Flip_Pitch_B; } break; case Flip_Pitch_B: // between 45deg ~ -90deg request 400deg/sec pitch attitude_control.rate_bf_roll_pitch_yaw(0.0, FLIP_ROTATION_RATE * flip_pitch_dir, 0.0); // decrease throttle if (throttle_out >= g.throttle_min) { throttle_out = max(throttle_out - FLIP_THR_DEC, g.throttle_min); } // check roll for inversion if ((labs(ahrs.roll_sensor) < 9000) && (flip_angle > -4500)) { flip_state = Flip_Recover; } break; case Flip_Recover: // use originally captured earth-frame angle targets to recover attitude_control.angle_ef_roll_pitch_yaw(flip_orig_attitude.x, flip_orig_attitude.y, flip_orig_attitude.z, false); // increase throttle to gain any lost altitude throttle_out += FLIP_THR_INC; if (flip_roll_dir != 0) { // we are rolling recovery_angle = fabsf(flip_orig_attitude.x - (float)ahrs.roll_sensor); } else { // we are pitching recovery_angle = fabsf(flip_orig_attitude.y - (float)ahrs.pitch_sensor); } // check for successful recovery if (fabsf(recovery_angle) <= FLIP_RECOVERY_ANGLE) { // restore original flight mode if (!set_mode(flip_orig_control_mode)) { // this should never happen but just in case set_mode(STABILIZE); } // log successful completion Log_Write_Event(DATA_FLIP_END); } break; case Flip_Abandon: // restore original flight mode if (!set_mode(flip_orig_control_mode)) { // this should never happen but just in case set_mode(STABILIZE); } // log abandoning flip Log_Write_Error(ERROR_SUBSYSTEM_FLIP,ERROR_CODE_FLIP_ABANDONED); break; } // output pilot's throttle without angle boost if (throttle_out == 0) { attitude_control.set_throttle_out_unstabilized(0,false,g.throttle_filt); } else { attitude_control.set_throttle_out(throttle_out, false, g.throttle_filt); } }
gpl-3.0
justhyx/DOOM-3
neo/game/physics/Physics_Parametric.cpp
116
35860
/* =========================================================================== Doom 3 GPL Source Code Copyright (C) 1999-2011 id Software LLC, a ZeniMax Media company. This file is part of the Doom 3 GPL Source Code (?Doom 3 Source Code?). Doom 3 Source Code is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Doom 3 Source Code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Doom 3 Source Code. If not, see <http://www.gnu.org/licenses/>. In addition, the Doom 3 Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 Source Code. If not, please request a copy in writing from id Software at the address below. If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA. =========================================================================== */ #include "../../idlib/precompiled.h" #pragma hdrstop #include "../Game_local.h" CLASS_DECLARATION( idPhysics_Base, idPhysics_Parametric ) END_CLASS /* ================ idPhysics_Parametric::Activate ================ */ void idPhysics_Parametric::Activate( void ) { current.atRest = -1; self->BecomeActive( TH_PHYSICS ); } /* ================ idPhysics_Parametric::TestIfAtRest ================ */ bool idPhysics_Parametric::TestIfAtRest( void ) const { if ( ( current.linearExtrapolation.GetExtrapolationType() & ~EXTRAPOLATION_NOSTOP ) == EXTRAPOLATION_NONE && ( current.angularExtrapolation.GetExtrapolationType() & ~EXTRAPOLATION_NOSTOP ) == EXTRAPOLATION_NONE && current.linearInterpolation.GetDuration() == 0 && current.angularInterpolation.GetDuration() == 0 && current.spline == NULL ) { return true; } if ( !current.linearExtrapolation.IsDone( current.time ) ) { return false; } if ( !current.angularExtrapolation.IsDone( current.time ) ) { return false; } if ( !current.linearInterpolation.IsDone( current.time ) ) { return false; } if ( !current.angularInterpolation.IsDone( current.time ) ) { return false; } if ( current.spline != NULL && !current.spline->IsDone( current.time ) ) { return false; } return true; } /* ================ idPhysics_Parametric::Rest ================ */ void idPhysics_Parametric::Rest( void ) { current.atRest = gameLocal.time; self->BecomeInactive( TH_PHYSICS ); } /* ================ idPhysics_Parametric::idPhysics_Parametric ================ */ idPhysics_Parametric::idPhysics_Parametric( void ) { current.time = gameLocal.time; current.atRest = -1; current.useSplineAngles = false; current.origin.Zero(); current.angles.Zero(); current.axis.Identity(); current.localOrigin.Zero(); current.localAngles.Zero(); current.linearExtrapolation.Init( 0, 0, vec3_zero, vec3_zero, vec3_zero, EXTRAPOLATION_NONE ); current.angularExtrapolation.Init( 0, 0, ang_zero, ang_zero, ang_zero, EXTRAPOLATION_NONE ); current.linearInterpolation.Init( 0, 0, 0, 0, vec3_zero, vec3_zero ); current.angularInterpolation.Init( 0, 0, 0, 0, ang_zero, ang_zero ); current.spline = NULL; current.splineInterpolate.Init( 0, 1, 1, 2, 0, 0 ); saved = current; isPusher = false; pushFlags = 0; clipModel = NULL; isBlocked = false; memset( &pushResults, 0, sizeof( pushResults ) ); hasMaster = false; isOrientated = false; } /* ================ idPhysics_Parametric::~idPhysics_Parametric ================ */ idPhysics_Parametric::~idPhysics_Parametric( void ) { if ( clipModel != NULL ) { delete clipModel; clipModel = NULL; } if ( current.spline != NULL ) { delete current.spline; current.spline = NULL; } } /* ================ idPhysics_Parametric_SavePState ================ */ void idPhysics_Parametric_SavePState( idSaveGame *savefile, const parametricPState_t &state ) { savefile->WriteInt( state.time ); savefile->WriteInt( state.atRest ); savefile->WriteBool( state.useSplineAngles ); savefile->WriteVec3( state.origin ); savefile->WriteAngles( state.angles ); savefile->WriteMat3( state.axis ); savefile->WriteVec3( state.localOrigin ); savefile->WriteAngles( state.localAngles ); savefile->WriteInt( (int)state.linearExtrapolation.GetExtrapolationType() ); savefile->WriteFloat( state.linearExtrapolation.GetStartTime() ); savefile->WriteFloat( state.linearExtrapolation.GetDuration() ); savefile->WriteVec3( state.linearExtrapolation.GetStartValue() ); savefile->WriteVec3( state.linearExtrapolation.GetBaseSpeed() ); savefile->WriteVec3( state.linearExtrapolation.GetSpeed() ); savefile->WriteInt( (int)state.angularExtrapolation.GetExtrapolationType() ); savefile->WriteFloat( state.angularExtrapolation.GetStartTime() ); savefile->WriteFloat( state.angularExtrapolation.GetDuration() ); savefile->WriteAngles( state.angularExtrapolation.GetStartValue() ); savefile->WriteAngles( state.angularExtrapolation.GetBaseSpeed() ); savefile->WriteAngles( state.angularExtrapolation.GetSpeed() ); savefile->WriteFloat( state.linearInterpolation.GetStartTime() ); savefile->WriteFloat( state.linearInterpolation.GetAcceleration() ); savefile->WriteFloat( state.linearInterpolation.GetDeceleration() ); savefile->WriteFloat( state.linearInterpolation.GetDuration() ); savefile->WriteVec3( state.linearInterpolation.GetStartValue() ); savefile->WriteVec3( state.linearInterpolation.GetEndValue() ); savefile->WriteFloat( state.angularInterpolation.GetStartTime() ); savefile->WriteFloat( state.angularInterpolation.GetAcceleration() ); savefile->WriteFloat( state.angularInterpolation.GetDeceleration() ); savefile->WriteFloat( state.angularInterpolation.GetDuration() ); savefile->WriteAngles( state.angularInterpolation.GetStartValue() ); savefile->WriteAngles( state.angularInterpolation.GetEndValue() ); // spline is handled by owner savefile->WriteFloat( state.splineInterpolate.GetStartTime() ); savefile->WriteFloat( state.splineInterpolate.GetAcceleration() ); savefile->WriteFloat( state.splineInterpolate.GetDuration() ); savefile->WriteFloat( state.splineInterpolate.GetDeceleration() ); savefile->WriteFloat( state.splineInterpolate.GetStartValue() ); savefile->WriteFloat( state.splineInterpolate.GetEndValue() ); } /* ================ idPhysics_Parametric_RestorePState ================ */ void idPhysics_Parametric_RestorePState( idRestoreGame *savefile, parametricPState_t &state ) { extrapolation_t etype; float startTime, duration, accelTime, decelTime, startValue, endValue; idVec3 linearStartValue, linearBaseSpeed, linearSpeed, startPos, endPos; idAngles angularStartValue, angularBaseSpeed, angularSpeed, startAng, endAng; savefile->ReadInt( state.time ); savefile->ReadInt( state.atRest ); savefile->ReadBool( state.useSplineAngles ); savefile->ReadVec3( state.origin ); savefile->ReadAngles( state.angles ); savefile->ReadMat3( state.axis ); savefile->ReadVec3( state.localOrigin ); savefile->ReadAngles( state.localAngles ); savefile->ReadInt( (int &)etype ); savefile->ReadFloat( startTime ); savefile->ReadFloat( duration ); savefile->ReadVec3( linearStartValue ); savefile->ReadVec3( linearBaseSpeed ); savefile->ReadVec3( linearSpeed ); state.linearExtrapolation.Init( startTime, duration, linearStartValue, linearBaseSpeed, linearSpeed, etype ); savefile->ReadInt( (int &)etype ); savefile->ReadFloat( startTime ); savefile->ReadFloat( duration ); savefile->ReadAngles( angularStartValue ); savefile->ReadAngles( angularBaseSpeed ); savefile->ReadAngles( angularSpeed ); state.angularExtrapolation.Init( startTime, duration, angularStartValue, angularBaseSpeed, angularSpeed, etype ); savefile->ReadFloat( startTime ); savefile->ReadFloat( accelTime ); savefile->ReadFloat( decelTime ); savefile->ReadFloat( duration ); savefile->ReadVec3( startPos ); savefile->ReadVec3( endPos ); state.linearInterpolation.Init( startTime, accelTime, decelTime, duration, startPos, endPos ); savefile->ReadFloat( startTime ); savefile->ReadFloat( accelTime ); savefile->ReadFloat( decelTime ); savefile->ReadFloat( duration ); savefile->ReadAngles( startAng ); savefile->ReadAngles( endAng ); state.angularInterpolation.Init( startTime, accelTime, decelTime, duration, startAng, endAng ); // spline is handled by owner savefile->ReadFloat( startTime ); savefile->ReadFloat( accelTime ); savefile->ReadFloat( duration ); savefile->ReadFloat( decelTime ); savefile->ReadFloat( startValue ); savefile->ReadFloat( endValue ); state.splineInterpolate.Init( startTime, accelTime, decelTime, duration, startValue, endValue ); } /* ================ idPhysics_Parametric::Save ================ */ void idPhysics_Parametric::Save( idSaveGame *savefile ) const { idPhysics_Parametric_SavePState( savefile, current ); idPhysics_Parametric_SavePState( savefile, saved ); savefile->WriteBool( isPusher ); savefile->WriteClipModel( clipModel ); savefile->WriteInt( pushFlags ); savefile->WriteTrace( pushResults ); savefile->WriteBool( isBlocked ); savefile->WriteBool( hasMaster ); savefile->WriteBool( isOrientated ); } /* ================ idPhysics_Parametric::Restore ================ */ void idPhysics_Parametric::Restore( idRestoreGame *savefile ) { idPhysics_Parametric_RestorePState( savefile, current ); idPhysics_Parametric_RestorePState( savefile, saved ); savefile->ReadBool( isPusher ); savefile->ReadClipModel( clipModel ); savefile->ReadInt( pushFlags ); savefile->ReadTrace( pushResults ); savefile->ReadBool( isBlocked ); savefile->ReadBool( hasMaster ); savefile->ReadBool( isOrientated ); } /* ================ idPhysics_Parametric::SetPusher ================ */ void idPhysics_Parametric::SetPusher( int flags ) { assert( clipModel ); isPusher = true; pushFlags = flags; } /* ================ idPhysics_Parametric::IsPusher ================ */ bool idPhysics_Parametric::IsPusher( void ) const { return isPusher; } /* ================ idPhysics_Parametric::SetLinearExtrapolation ================ */ void idPhysics_Parametric::SetLinearExtrapolation( extrapolation_t type, int time, int duration, const idVec3 &base, const idVec3 &speed, const idVec3 &baseSpeed ) { current.time = gameLocal.time; current.linearExtrapolation.Init( time, duration, base, baseSpeed, speed, type ); current.localOrigin = base; Activate(); } /* ================ idPhysics_Parametric::SetAngularExtrapolation ================ */ void idPhysics_Parametric::SetAngularExtrapolation( extrapolation_t type, int time, int duration, const idAngles &base, const idAngles &speed, const idAngles &baseSpeed ) { current.time = gameLocal.time; current.angularExtrapolation.Init( time, duration, base, baseSpeed, speed, type ); current.localAngles = base; Activate(); } /* ================ idPhysics_Parametric::GetLinearExtrapolationType ================ */ extrapolation_t idPhysics_Parametric::GetLinearExtrapolationType( void ) const { return current.linearExtrapolation.GetExtrapolationType(); } /* ================ idPhysics_Parametric::GetAngularExtrapolationType ================ */ extrapolation_t idPhysics_Parametric::GetAngularExtrapolationType( void ) const { return current.angularExtrapolation.GetExtrapolationType(); } /* ================ idPhysics_Parametric::SetLinearInterpolation ================ */ void idPhysics_Parametric::SetLinearInterpolation( int time, int accelTime, int decelTime, int duration, const idVec3 &startPos, const idVec3 &endPos ) { current.time = gameLocal.time; current.linearInterpolation.Init( time, accelTime, decelTime, duration, startPos, endPos ); current.localOrigin = startPos; Activate(); } /* ================ idPhysics_Parametric::SetAngularInterpolation ================ */ void idPhysics_Parametric::SetAngularInterpolation( int time, int accelTime, int decelTime, int duration, const idAngles &startAng, const idAngles &endAng ) { current.time = gameLocal.time; current.angularInterpolation.Init( time, accelTime, decelTime, duration, startAng, endAng ); current.localAngles = startAng; Activate(); } /* ================ idPhysics_Parametric::SetSpline ================ */ void idPhysics_Parametric::SetSpline( idCurve_Spline<idVec3> *spline, int accelTime, int decelTime, bool useSplineAngles ) { if ( current.spline != NULL ) { delete current.spline; current.spline = NULL; } current.spline = spline; if ( current.spline != NULL ) { float startTime = current.spline->GetTime( 0 ); float endTime = current.spline->GetTime( current.spline->GetNumValues() - 1 ); float length = current.spline->GetLengthForTime( endTime ); current.splineInterpolate.Init( startTime, accelTime, decelTime, endTime - startTime, 0.0f, length ); } current.useSplineAngles = useSplineAngles; Activate(); } /* ================ idPhysics_Parametric::GetSpline ================ */ idCurve_Spline<idVec3> *idPhysics_Parametric::GetSpline( void ) const { return current.spline; } /* ================ idPhysics_Parametric::GetSplineAcceleration ================ */ int idPhysics_Parametric::GetSplineAcceleration( void ) const { return current.splineInterpolate.GetAcceleration(); } /* ================ idPhysics_Parametric::GetSplineDeceleration ================ */ int idPhysics_Parametric::GetSplineDeceleration( void ) const { return current.splineInterpolate.GetDeceleration(); } /* ================ idPhysics_Parametric::UsingSplineAngles ================ */ bool idPhysics_Parametric::UsingSplineAngles( void ) const { return current.useSplineAngles; } /* ================ idPhysics_Parametric::GetLocalOrigin ================ */ void idPhysics_Parametric::GetLocalOrigin( idVec3 &curOrigin ) const { curOrigin = current.localOrigin; } /* ================ idPhysics_Parametric::GetLocalAngles ================ */ void idPhysics_Parametric::GetLocalAngles( idAngles &curAngles ) const { curAngles = current.localAngles; } /* ================ idPhysics_Parametric::SetClipModel ================ */ void idPhysics_Parametric::SetClipModel( idClipModel *model, float density, int id, bool freeOld ) { assert( self ); assert( model ); if ( clipModel && clipModel != model && freeOld ) { delete clipModel; } clipModel = model; clipModel->Link( gameLocal.clip, self, 0, current.origin, current.axis ); } /* ================ idPhysics_Parametric::GetClipModel ================ */ idClipModel *idPhysics_Parametric::GetClipModel( int id ) const { return clipModel; } /* ================ idPhysics_Parametric::GetNumClipModels ================ */ int idPhysics_Parametric::GetNumClipModels( void ) const { return ( clipModel != NULL ); } /* ================ idPhysics_Parametric::SetMass ================ */ void idPhysics_Parametric::SetMass( float mass, int id ) { } /* ================ idPhysics_Parametric::GetMass ================ */ float idPhysics_Parametric::GetMass( int id ) const { return 0.0f; } /* ================ idPhysics_Parametric::SetClipMask ================ */ void idPhysics_Parametric::SetContents( int contents, int id ) { if ( clipModel ) { clipModel->SetContents( contents ); } } /* ================ idPhysics_Parametric::SetClipMask ================ */ int idPhysics_Parametric::GetContents( int id ) const { if ( clipModel ) { return clipModel->GetContents(); } return 0; } /* ================ idPhysics_Parametric::GetBounds ================ */ const idBounds &idPhysics_Parametric::GetBounds( int id ) const { if ( clipModel ) { return clipModel->GetBounds(); } return idPhysics_Base::GetBounds(); } /* ================ idPhysics_Parametric::GetAbsBounds ================ */ const idBounds &idPhysics_Parametric::GetAbsBounds( int id ) const { if ( clipModel ) { return clipModel->GetAbsBounds(); } return idPhysics_Base::GetAbsBounds(); } /* ================ idPhysics_Parametric::Evaluate ================ */ bool idPhysics_Parametric::Evaluate( int timeStepMSec, int endTimeMSec ) { idVec3 oldLocalOrigin, oldOrigin, masterOrigin; idAngles oldLocalAngles, oldAngles; idMat3 oldAxis, masterAxis; isBlocked = false; oldLocalOrigin = current.localOrigin; oldOrigin = current.origin; oldLocalAngles = current.localAngles; oldAngles = current.angles; oldAxis = current.axis; current.localOrigin.Zero(); current.localAngles.Zero(); if ( current.spline != NULL ) { float length = current.splineInterpolate.GetCurrentValue( endTimeMSec ); float t = current.spline->GetTimeForLength( length, 0.01f ); current.localOrigin = current.spline->GetCurrentValue( t ); if ( current.useSplineAngles ) { current.localAngles = current.spline->GetCurrentFirstDerivative( t ).ToAngles(); } } else if ( current.linearInterpolation.GetDuration() != 0 ) { current.localOrigin += current.linearInterpolation.GetCurrentValue( endTimeMSec ); } else { current.localOrigin += current.linearExtrapolation.GetCurrentValue( endTimeMSec ); } if ( current.angularInterpolation.GetDuration() != 0 ) { current.localAngles += current.angularInterpolation.GetCurrentValue( endTimeMSec ); } else { current.localAngles += current.angularExtrapolation.GetCurrentValue( endTimeMSec ); } current.localAngles.Normalize360(); current.origin = current.localOrigin; current.angles = current.localAngles; current.axis = current.localAngles.ToMat3(); if ( hasMaster ) { self->GetMasterPosition( masterOrigin, masterAxis ); if ( masterAxis.IsRotated() ) { current.origin = current.origin * masterAxis + masterOrigin; if ( isOrientated ) { current.axis *= masterAxis; current.angles = current.axis.ToAngles(); } } else { current.origin += masterOrigin; } } if ( isPusher ) { gameLocal.push.ClipPush( pushResults, self, pushFlags, oldOrigin, oldAxis, current.origin, current.axis ); if ( pushResults.fraction < 1.0f ) { clipModel->Link( gameLocal.clip, self, 0, oldOrigin, oldAxis ); current.localOrigin = oldLocalOrigin; current.origin = oldOrigin; current.localAngles = oldLocalAngles; current.angles = oldAngles; current.axis = oldAxis; isBlocked = true; return false; } current.angles = current.axis.ToAngles(); } if ( clipModel ) { clipModel->Link( gameLocal.clip, self, 0, current.origin, current.axis ); } current.time = endTimeMSec; if ( TestIfAtRest() ) { Rest(); } return ( current.origin != oldOrigin || current.axis != oldAxis ); } /* ================ idPhysics_Parametric::UpdateTime ================ */ void idPhysics_Parametric::UpdateTime( int endTimeMSec ) { int timeLeap = endTimeMSec - current.time; current.time = endTimeMSec; // move the trajectory start times to sync the trajectory with the current endTime current.linearExtrapolation.SetStartTime( current.linearExtrapolation.GetStartTime() + timeLeap ); current.angularExtrapolation.SetStartTime( current.angularExtrapolation.GetStartTime() + timeLeap ); current.linearInterpolation.SetStartTime( current.linearInterpolation.GetStartTime() + timeLeap ); current.angularInterpolation.SetStartTime( current.angularInterpolation.GetStartTime() + timeLeap ); if ( current.spline != NULL ) { current.spline->ShiftTime( timeLeap ); current.splineInterpolate.SetStartTime( current.splineInterpolate.GetStartTime() + timeLeap ); } } /* ================ idPhysics_Parametric::GetTime ================ */ int idPhysics_Parametric::GetTime( void ) const { return current.time; } /* ================ idPhysics_Parametric::IsAtRest ================ */ bool idPhysics_Parametric::IsAtRest( void ) const { return current.atRest >= 0; } /* ================ idPhysics_Parametric::GetRestStartTime ================ */ int idPhysics_Parametric::GetRestStartTime( void ) const { return current.atRest; } /* ================ idPhysics_Parametric::IsPushable ================ */ bool idPhysics_Parametric::IsPushable( void ) const { return false; } /* ================ idPhysics_Parametric::SaveState ================ */ void idPhysics_Parametric::SaveState( void ) { saved = current; } /* ================ idPhysics_Parametric::RestoreState ================ */ void idPhysics_Parametric::RestoreState( void ) { current = saved; if ( clipModel ) { clipModel->Link( gameLocal.clip, self, 0, current.origin, current.axis ); } } /* ================ idPhysics_Parametric::SetOrigin ================ */ void idPhysics_Parametric::SetOrigin( const idVec3 &newOrigin, int id ) { idVec3 masterOrigin; idMat3 masterAxis; current.linearExtrapolation.SetStartValue( newOrigin ); current.linearInterpolation.SetStartValue( newOrigin ); current.localOrigin = current.linearExtrapolation.GetCurrentValue( current.time ); if ( hasMaster ) { self->GetMasterPosition( masterOrigin, masterAxis ); current.origin = masterOrigin + current.localOrigin * masterAxis; } else { current.origin = current.localOrigin; } if ( clipModel ) { clipModel->Link( gameLocal.clip, self, 0, current.origin, current.axis ); } Activate(); } /* ================ idPhysics_Parametric::SetAxis ================ */ void idPhysics_Parametric::SetAxis( const idMat3 &newAxis, int id ) { idVec3 masterOrigin; idMat3 masterAxis; current.localAngles = newAxis.ToAngles(); current.angularExtrapolation.SetStartValue( current.localAngles ); current.angularInterpolation.SetStartValue( current.localAngles ); current.localAngles = current.angularExtrapolation.GetCurrentValue( current.time ); if ( hasMaster && isOrientated ) { self->GetMasterPosition( masterOrigin, masterAxis ); current.axis = current.localAngles.ToMat3() * masterAxis; current.angles = current.axis.ToAngles(); } else { current.axis = current.localAngles.ToMat3(); current.angles = current.localAngles; } if ( clipModel ) { clipModel->Link( gameLocal.clip, self, 0, current.origin, current.axis ); } Activate(); } /* ================ idPhysics_Parametric::Move ================ */ void idPhysics_Parametric::Translate( const idVec3 &translation, int id ) { } /* ================ idPhysics_Parametric::Rotate ================ */ void idPhysics_Parametric::Rotate( const idRotation &rotation, int id ) { } /* ================ idPhysics_Parametric::GetOrigin ================ */ const idVec3 &idPhysics_Parametric::GetOrigin( int id ) const { return current.origin; } /* ================ idPhysics_Parametric::GetAxis ================ */ const idMat3 &idPhysics_Parametric::GetAxis( int id ) const { return current.axis; } /* ================ idPhysics_Parametric::GetAngles ================ */ void idPhysics_Parametric::GetAngles( idAngles &curAngles ) const { curAngles = current.angles; } /* ================ idPhysics_Parametric::SetLinearVelocity ================ */ void idPhysics_Parametric::SetLinearVelocity( const idVec3 &newLinearVelocity, int id ) { SetLinearExtrapolation( extrapolation_t(EXTRAPOLATION_LINEAR|EXTRAPOLATION_NOSTOP), gameLocal.time, 0, current.origin, newLinearVelocity, vec3_origin ); current.linearInterpolation.Init( 0, 0, 0, 0, vec3_zero, vec3_zero ); Activate(); } /* ================ idPhysics_Parametric::SetAngularVelocity ================ */ void idPhysics_Parametric::SetAngularVelocity( const idVec3 &newAngularVelocity, int id ) { idRotation rotation; idVec3 vec; float angle; vec = newAngularVelocity; angle = vec.Normalize(); rotation.Set( vec3_origin, vec, (float) RAD2DEG( angle ) ); SetAngularExtrapolation( extrapolation_t(EXTRAPOLATION_LINEAR|EXTRAPOLATION_NOSTOP), gameLocal.time, 0, current.angles, rotation.ToAngles(), ang_zero ); current.angularInterpolation.Init( 0, 0, 0, 0, ang_zero, ang_zero ); Activate(); } /* ================ idPhysics_Parametric::GetLinearVelocity ================ */ const idVec3 &idPhysics_Parametric::GetLinearVelocity( int id ) const { static idVec3 curLinearVelocity; curLinearVelocity = current.linearExtrapolation.GetCurrentSpeed( gameLocal.time ); return curLinearVelocity; } /* ================ idPhysics_Parametric::GetAngularVelocity ================ */ const idVec3 &idPhysics_Parametric::GetAngularVelocity( int id ) const { static idVec3 curAngularVelocity; idAngles angles; angles = current.angularExtrapolation.GetCurrentSpeed( gameLocal.time ); curAngularVelocity = angles.ToAngularVelocity(); return curAngularVelocity; } /* ================ idPhysics_Parametric::DisableClip ================ */ void idPhysics_Parametric::DisableClip( void ) { if ( clipModel ) { clipModel->Disable(); } } /* ================ idPhysics_Parametric::EnableClip ================ */ void idPhysics_Parametric::EnableClip( void ) { if ( clipModel ) { clipModel->Enable(); } } /* ================ idPhysics_Parametric::UnlinkClip ================ */ void idPhysics_Parametric::UnlinkClip( void ) { if ( clipModel ) { clipModel->Unlink(); } } /* ================ idPhysics_Parametric::LinkClip ================ */ void idPhysics_Parametric::LinkClip( void ) { if ( clipModel ) { clipModel->Link( gameLocal.clip, self, 0, current.origin, current.axis ); } } /* ================ idPhysics_Parametric::GetBlockingInfo ================ */ const trace_t *idPhysics_Parametric::GetBlockingInfo( void ) const { return ( isBlocked ? &pushResults : NULL ); } /* ================ idPhysics_Parametric::GetBlockingEntity ================ */ idEntity *idPhysics_Parametric::GetBlockingEntity( void ) const { if ( isBlocked ) { return gameLocal.entities[ pushResults.c.entityNum ]; } return NULL; } /* ================ idPhysics_Parametric::SetMaster ================ */ void idPhysics_Parametric::SetMaster( idEntity *master, const bool orientated ) { idVec3 masterOrigin; idMat3 masterAxis; if ( master ) { if ( !hasMaster ) { // transform from world space to master space self->GetMasterPosition( masterOrigin, masterAxis ); current.localOrigin = ( current.origin - masterOrigin ) * masterAxis.Transpose(); if ( orientated ) { current.localAngles = ( current.axis * masterAxis.Transpose() ).ToAngles(); } else { current.localAngles = current.axis.ToAngles(); } current.linearExtrapolation.SetStartValue( current.localOrigin ); current.angularExtrapolation.SetStartValue( current.localAngles ); hasMaster = true; isOrientated = orientated; } } else { if ( hasMaster ) { // transform from master space to world space current.localOrigin = current.origin; current.localAngles = current.angles; SetLinearExtrapolation( EXTRAPOLATION_NONE, 0, 0, current.origin, vec3_origin, vec3_origin ); SetAngularExtrapolation( EXTRAPOLATION_NONE, 0, 0, current.angles, ang_zero, ang_zero ); hasMaster = false; } } } /* ================ idPhysics_Parametric::GetLinearEndTime ================ */ int idPhysics_Parametric::GetLinearEndTime( void ) const { if ( current.spline != NULL ) { if ( current.spline->GetBoundaryType() != idCurve_Spline<idVec3>::BT_CLOSED ) { return current.spline->GetTime( current.spline->GetNumValues() - 1 ); } else { return 0; } } else if ( current.linearInterpolation.GetDuration() != 0 ) { return current.linearInterpolation.GetEndTime(); } else { return current.linearExtrapolation.GetEndTime(); } } /* ================ idPhysics_Parametric::GetAngularEndTime ================ */ int idPhysics_Parametric::GetAngularEndTime( void ) const { if ( current.angularInterpolation.GetDuration() != 0 ) { return current.angularInterpolation.GetEndTime(); } else { return current.angularExtrapolation.GetEndTime(); } } /* ================ idPhysics_Parametric::WriteToSnapshot ================ */ void idPhysics_Parametric::WriteToSnapshot( idBitMsgDelta &msg ) const { msg.WriteLong( current.time ); msg.WriteLong( current.atRest ); msg.WriteFloat( current.origin[0] ); msg.WriteFloat( current.origin[1] ); msg.WriteFloat( current.origin[2] ); msg.WriteFloat( current.angles[0] ); msg.WriteFloat( current.angles[1] ); msg.WriteFloat( current.angles[2] ); msg.WriteDeltaFloat( current.origin[0], current.localOrigin[0] ); msg.WriteDeltaFloat( current.origin[1], current.localOrigin[1] ); msg.WriteDeltaFloat( current.origin[2], current.localOrigin[2] ); msg.WriteDeltaFloat( current.angles[0], current.localAngles[0] ); msg.WriteDeltaFloat( current.angles[1], current.localAngles[1] ); msg.WriteDeltaFloat( current.angles[2], current.localAngles[2] ); msg.WriteBits( current.linearExtrapolation.GetExtrapolationType(), 8 ); msg.WriteDeltaFloat( 0.0f, current.linearExtrapolation.GetStartTime() ); msg.WriteDeltaFloat( 0.0f, current.linearExtrapolation.GetDuration() ); msg.WriteDeltaFloat( 0.0f, current.linearExtrapolation.GetStartValue()[0] ); msg.WriteDeltaFloat( 0.0f, current.linearExtrapolation.GetStartValue()[1] ); msg.WriteDeltaFloat( 0.0f, current.linearExtrapolation.GetStartValue()[2] ); msg.WriteDeltaFloat( 0.0f, current.linearExtrapolation.GetSpeed()[0] ); msg.WriteDeltaFloat( 0.0f, current.linearExtrapolation.GetSpeed()[1] ); msg.WriteDeltaFloat( 0.0f, current.linearExtrapolation.GetSpeed()[2] ); msg.WriteDeltaFloat( 0.0f, current.linearExtrapolation.GetBaseSpeed()[0] ); msg.WriteDeltaFloat( 0.0f, current.linearExtrapolation.GetBaseSpeed()[1] ); msg.WriteDeltaFloat( 0.0f, current.linearExtrapolation.GetBaseSpeed()[2] ); msg.WriteBits( current.angularExtrapolation.GetExtrapolationType(), 8 ); msg.WriteDeltaFloat( 0.0f, current.angularExtrapolation.GetStartTime() ); msg.WriteDeltaFloat( 0.0f, current.angularExtrapolation.GetDuration() ); msg.WriteDeltaFloat( 0.0f, current.angularExtrapolation.GetStartValue()[0] ); msg.WriteDeltaFloat( 0.0f, current.angularExtrapolation.GetStartValue()[1] ); msg.WriteDeltaFloat( 0.0f, current.angularExtrapolation.GetStartValue()[2] ); msg.WriteDeltaFloat( 0.0f, current.angularExtrapolation.GetSpeed()[0] ); msg.WriteDeltaFloat( 0.0f, current.angularExtrapolation.GetSpeed()[1] ); msg.WriteDeltaFloat( 0.0f, current.angularExtrapolation.GetSpeed()[2] ); msg.WriteDeltaFloat( 0.0f, current.angularExtrapolation.GetBaseSpeed()[0] ); msg.WriteDeltaFloat( 0.0f, current.angularExtrapolation.GetBaseSpeed()[1] ); msg.WriteDeltaFloat( 0.0f, current.angularExtrapolation.GetBaseSpeed()[2] ); msg.WriteDeltaFloat( 0.0f, current.linearInterpolation.GetStartTime() ); msg.WriteDeltaFloat( 0.0f, current.linearInterpolation.GetAcceleration() ); msg.WriteDeltaFloat( 0.0f, current.linearInterpolation.GetDeceleration() ); msg.WriteDeltaFloat( 0.0f, current.linearInterpolation.GetDuration() ); msg.WriteDeltaFloat( 0.0f, current.linearInterpolation.GetStartValue()[0] ); msg.WriteDeltaFloat( 0.0f, current.linearInterpolation.GetStartValue()[1] ); msg.WriteDeltaFloat( 0.0f, current.linearInterpolation.GetStartValue()[2] ); msg.WriteDeltaFloat( 0.0f, current.linearInterpolation.GetEndValue()[0] ); msg.WriteDeltaFloat( 0.0f, current.linearInterpolation.GetEndValue()[1] ); msg.WriteDeltaFloat( 0.0f, current.linearInterpolation.GetEndValue()[2] ); msg.WriteDeltaFloat( 0.0f, current.angularInterpolation.GetStartTime() ); msg.WriteDeltaFloat( 0.0f, current.angularInterpolation.GetAcceleration() ); msg.WriteDeltaFloat( 0.0f, current.angularInterpolation.GetDeceleration() ); msg.WriteDeltaFloat( 0.0f, current.angularInterpolation.GetDuration() ); msg.WriteDeltaFloat( 0.0f, current.angularInterpolation.GetStartValue()[0] ); msg.WriteDeltaFloat( 0.0f, current.angularInterpolation.GetStartValue()[1] ); msg.WriteDeltaFloat( 0.0f, current.angularInterpolation.GetStartValue()[2] ); msg.WriteDeltaFloat( 0.0f, current.angularInterpolation.GetEndValue()[0] ); msg.WriteDeltaFloat( 0.0f, current.angularInterpolation.GetEndValue()[1] ); msg.WriteDeltaFloat( 0.0f, current.angularInterpolation.GetEndValue()[2] ); } /* ================ idPhysics_Parametric::ReadFromSnapshot ================ */ void idPhysics_Parametric::ReadFromSnapshot( const idBitMsgDelta &msg ) { extrapolation_t linearType, angularType; float startTime, duration, accelTime, decelTime; idVec3 linearStartValue, linearSpeed, linearBaseSpeed, startPos, endPos; idAngles angularStartValue, angularSpeed, angularBaseSpeed, startAng, endAng; current.time = msg.ReadLong(); current.atRest = msg.ReadLong(); current.origin[0] = msg.ReadFloat(); current.origin[1] = msg.ReadFloat(); current.origin[2] = msg.ReadFloat(); current.angles[0] = msg.ReadFloat(); current.angles[1] = msg.ReadFloat(); current.angles[2] = msg.ReadFloat(); current.localOrigin[0] = msg.ReadDeltaFloat( current.origin[0] ); current.localOrigin[1] = msg.ReadDeltaFloat( current.origin[1] ); current.localOrigin[2] = msg.ReadDeltaFloat( current.origin[2] ); current.localAngles[0] = msg.ReadDeltaFloat( current.angles[0] ); current.localAngles[1] = msg.ReadDeltaFloat( current.angles[1] ); current.localAngles[2] = msg.ReadDeltaFloat( current.angles[2] ); linearType = (extrapolation_t) msg.ReadBits( 8 ); startTime = msg.ReadDeltaFloat( 0.0f ); duration = msg.ReadDeltaFloat( 0.0f ); linearStartValue[0] = msg.ReadDeltaFloat( 0.0f ); linearStartValue[1] = msg.ReadDeltaFloat( 0.0f ); linearStartValue[2] = msg.ReadDeltaFloat( 0.0f ); linearSpeed[0] = msg.ReadDeltaFloat( 0.0f ); linearSpeed[1] = msg.ReadDeltaFloat( 0.0f ); linearSpeed[2] = msg.ReadDeltaFloat( 0.0f ); linearBaseSpeed[0] = msg.ReadDeltaFloat( 0.0f ); linearBaseSpeed[1] = msg.ReadDeltaFloat( 0.0f ); linearBaseSpeed[2] = msg.ReadDeltaFloat( 0.0f ); current.linearExtrapolation.Init( startTime, duration, linearStartValue, linearBaseSpeed, linearSpeed, linearType ); angularType = (extrapolation_t) msg.ReadBits( 8 ); startTime = msg.ReadDeltaFloat( 0.0f ); duration = msg.ReadDeltaFloat( 0.0f ); angularStartValue[0] = msg.ReadDeltaFloat( 0.0f ); angularStartValue[1] = msg.ReadDeltaFloat( 0.0f ); angularStartValue[2] = msg.ReadDeltaFloat( 0.0f ); angularSpeed[0] = msg.ReadDeltaFloat( 0.0f ); angularSpeed[1] = msg.ReadDeltaFloat( 0.0f ); angularSpeed[2] = msg.ReadDeltaFloat( 0.0f ); angularBaseSpeed[0] = msg.ReadDeltaFloat( 0.0f ); angularBaseSpeed[1] = msg.ReadDeltaFloat( 0.0f ); angularBaseSpeed[2] = msg.ReadDeltaFloat( 0.0f ); current.angularExtrapolation.Init( startTime, duration, angularStartValue, angularBaseSpeed, angularSpeed, angularType ); startTime = msg.ReadDeltaFloat( 0.0f ); accelTime = msg.ReadDeltaFloat( 0.0f ); decelTime = msg.ReadDeltaFloat( 0.0f ); duration = msg.ReadDeltaFloat( 0.0f ); startPos[0] = msg.ReadDeltaFloat( 0.0f ); startPos[1] = msg.ReadDeltaFloat( 0.0f ); startPos[2] = msg.ReadDeltaFloat( 0.0f ); endPos[0] = msg.ReadDeltaFloat( 0.0f ); endPos[1] = msg.ReadDeltaFloat( 0.0f ); endPos[2] = msg.ReadDeltaFloat( 0.0f ); current.linearInterpolation.Init( startTime, accelTime, decelTime, duration, startPos, endPos ); startTime = msg.ReadDeltaFloat( 0.0f ); accelTime = msg.ReadDeltaFloat( 0.0f ); decelTime = msg.ReadDeltaFloat( 0.0f ); duration = msg.ReadDeltaFloat( 0.0f ); startAng[0] = msg.ReadDeltaFloat( 0.0f ); startAng[1] = msg.ReadDeltaFloat( 0.0f ); startAng[2] = msg.ReadDeltaFloat( 0.0f ); endAng[0] = msg.ReadDeltaFloat( 0.0f ); endAng[1] = msg.ReadDeltaFloat( 0.0f ); endAng[2] = msg.ReadDeltaFloat( 0.0f ); current.angularInterpolation.Init( startTime, accelTime, decelTime, duration, startAng, endAng ); current.axis = current.angles.ToMat3(); if ( clipModel ) { clipModel->Link( gameLocal.clip, self, 0, current.origin, current.axis ); } }
gpl-3.0
n5047c/android_kernel_chagall
drivers/power/bq27x00_battery.c
150
26897
/* * BQ27x00 battery driver * * Copyright (C) 2008 Rodolfo Giometti <giometti@linux.it> * Copyright (C) 2008 Eurotech S.p.A. <info@eurotech.it> * Copyright (C) 2010-2011 Lars-Peter Clausen <lars@metafoo.de> * Copyright (C) 2011 Pali Rohár <pali.rohar@gmail.com> * Copyright (C) 2011 NVIDIA Corporation. * * Based on a previous work by Copyright (C) 2008 Texas Instruments, Inc. * * This package is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. * */ /* * Datasheets: * http://focus.ti.com/docs/prod/folders/print/bq27000.html * http://focus.ti.com/docs/prod/folders/print/bq27500.html */ #include <linux/module.h> #include <linux/param.h> #include <linux/jiffies.h> #include <linux/workqueue.h> #include <linux/delay.h> #include <linux/platform_device.h> #include <linux/power_supply.h> #include <linux/idr.h> #include <linux/i2c.h> #include <linux/slab.h> #include <asm/unaligned.h> #include <linux/power/bq27x00_battery.h> #define DRIVER_VERSION "1.2.0" #define BQ27x00_REG_TEMP 0x06 #define BQ27x00_REG_VOLT 0x08 #define BQ27x00_REG_AI 0x14 #define BQ27x00_REG_FLAGS 0x0A #define BQ27x00_REG_TTE 0x16 #define BQ27x00_REG_TTF 0x18 #define BQ27x00_REG_TTECP 0x26 #define BQ27x00_REG_NAC 0x0C /* Nominal available capaciy */ #define BQ27x00_REG_LMD 0x12 /* Last measured discharge */ #define BQ27x00_REG_CYCT 0x2A /* Cycle count total */ #define BQ27x00_REG_AE 0x22 /* Available enery */ #define BQ27000_REG_RSOC 0x0B /* Relative State-of-Charge */ #define BQ27000_REG_ILMD 0x76 /* Initial last measured discharge */ #define BQ27000_FLAG_CHGS BIT(7) #define BQ27000_FLAG_FC BIT(5) #define BQ27500_REG_SOC 0x2C #define BQ27500_REG_DCAP 0x3C /* Design capacity */ #define BQ27500_FLAG_DSC BIT(0) #define BQ27500_FLAG_SOCF BIT(1) #define BQ27500_FLAG_BAT_DET BIT(3) #define BQ27500_FLAG_FC BIT(9) #define BQ27500_FLAG_OTC BIT(15) #define BQ27000_RS 20 /* Resistor sense */ #define BQ27510_CNTL 0x00 #define BQ27510_ATRATE 0x02 #define BQ27510_ENERGY_AVAIL 0x22 #define BQ27510_POWER_AVG 0x24 /* bq27510-g2 control register sub-commands*/ #define BQ27510_CNTL_DEVICE_TYPE 0x0001 #define BQ27510_CNTL_SET_SLEEP 0x0013 #define BQ27510_CNTL_CLEAR_SLEEP 0x0014 /* bq27x00 requires 3 to 4 second to update charging status */ #define CHARGING_STATUS_UPDATE_DELAY_SECS 4 struct bq27x00_device_info; struct bq27x00_access_methods { int (*read)(struct bq27x00_device_info *di, u8 reg, bool single); int (*ctrl_read)(struct bq27x00_device_info *di, u8 ctrl_reg, u16 ctrl_func_reg); int (*write)(struct bq27x00_device_info *di, u8 reg, u16 val, bool single); }; enum bq27x00_chip { BQ27000, BQ27500, BQ27510 }; struct bq27x00_reg_cache { int temperature; int time_to_empty; int time_to_empty_avg; int time_to_full; int charge_full; int cycle_count; int capacity; int flags; int current_now; }; struct bq27x00_device_info { struct device *dev; int id; enum bq27x00_chip chip; struct bq27x00_reg_cache cache; int charge_design_full; unsigned long last_update; struct delayed_work work; struct delayed_work external_power_changed_work; struct power_supply bat; struct bq27x00_access_methods bus; struct mutex lock; struct mutex update_lock; }; static enum power_supply_property bq27x00_battery_props[] = { POWER_SUPPLY_PROP_STATUS, POWER_SUPPLY_PROP_PRESENT, POWER_SUPPLY_PROP_VOLTAGE_NOW, POWER_SUPPLY_PROP_CURRENT_NOW, POWER_SUPPLY_PROP_CAPACITY, POWER_SUPPLY_PROP_TEMP, POWER_SUPPLY_PROP_TIME_TO_EMPTY_NOW, POWER_SUPPLY_PROP_TIME_TO_EMPTY_AVG, POWER_SUPPLY_PROP_TIME_TO_FULL_NOW, POWER_SUPPLY_PROP_TECHNOLOGY, POWER_SUPPLY_PROP_CHARGE_FULL, POWER_SUPPLY_PROP_CHARGE_NOW, POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN, POWER_SUPPLY_PROP_CYCLE_COUNT, POWER_SUPPLY_PROP_ENERGY_NOW, POWER_SUPPLY_PROP_POWER_AVG, POWER_SUPPLY_PROP_SERIAL_NUMBER, POWER_SUPPLY_PROP_HEALTH, }; static unsigned int poll_interval = 360; module_param(poll_interval, uint, 0644); MODULE_PARM_DESC(poll_interval, "battery poll interval in seconds - " \ "0 disables polling"); /* * Common code for BQ27x00 devices */ static inline int bq27x00_read(struct bq27x00_device_info *di, u8 reg, bool single) { return di->bus.read(di, reg, single); } static inline int bq27x00_ctrl_read(struct bq27x00_device_info *di, u8 ctrl_reg, u16 ctrl_func_reg) { return di->bus.ctrl_read(di, ctrl_reg, ctrl_func_reg); } static inline int bq27x00_write(struct bq27x00_device_info *di, u8 reg, u16 val, bool single) { return di->bus.write(di, reg, val, single); } static int bq27510_battery_health(struct bq27x00_device_info *di, union power_supply_propval *val) { int ret; if ((di->chip == BQ27500) || (di->chip == BQ27510)) { ret = bq27x00_read(di, BQ27x00_REG_FLAGS, false); if (ret < 0) { dev_err(di->dev, "read failure\n"); return ret; } if (ret & BQ27500_FLAG_SOCF) val->intval = POWER_SUPPLY_HEALTH_DEAD; else if (ret & BQ27500_FLAG_OTC) val->intval = POWER_SUPPLY_HEALTH_OVERHEAT; else val->intval = POWER_SUPPLY_HEALTH_GOOD; return 0; } return -1; } /* * Return the battery Relative State-of-Charge * Or < 0 if something fails. */ static int bq27x00_battery_read_rsoc(struct bq27x00_device_info *di) { int rsoc; if ((di->chip == BQ27500) || (di->chip == BQ27510)) rsoc = bq27x00_read(di, BQ27500_REG_SOC, false); else rsoc = bq27x00_read(di, BQ27000_REG_RSOC, true); if (rsoc < 0) dev_err(di->dev, "error reading relative State-of-Charge\n"); return rsoc; } /* * Return a battery charge value in µAh * Or < 0 if something fails. */ static int bq27x00_battery_read_charge(struct bq27x00_device_info *di, u8 reg) { int charge; charge = bq27x00_read(di, reg, false); if (charge < 0) { dev_err(di->dev, "error reading nominal available capacity\n"); return charge; } if ((di->chip == BQ27500) || (di->chip == BQ27510)) charge *= 1000; else charge = charge * 3570 / BQ27000_RS; return charge; } /* * Return the battery Nominal available capaciy in µAh * Or < 0 if something fails. */ static inline int bq27x00_battery_read_nac(struct bq27x00_device_info *di) { return bq27x00_battery_read_charge(di, BQ27x00_REG_NAC); } /* * Return the battery Last measured discharge in µAh * Or < 0 if something fails. */ static inline int bq27x00_battery_read_lmd(struct bq27x00_device_info *di) { return bq27x00_battery_read_charge(di, BQ27x00_REG_LMD); } /* * Return the battery Initial last measured discharge in µAh * Or < 0 if something fails. */ static int bq27x00_battery_read_ilmd(struct bq27x00_device_info *di) { int ilmd; if ((di->chip == BQ27500) || (di->chip == BQ27510)) ilmd = bq27x00_read(di, BQ27500_REG_DCAP, false); else ilmd = bq27x00_read(di, BQ27000_REG_ILMD, true); if (ilmd < 0) { dev_err(di->dev, "error reading initial last measured discharge\n"); return ilmd; } if ((di->chip == BQ27500) || (di->chip == BQ27510)) ilmd *= 1000; else ilmd = ilmd * 256 * 3570 / BQ27000_RS; return ilmd; } /* * Return the battery Cycle count total * Or < 0 if something fails. */ static int bq27x00_battery_read_cyct(struct bq27x00_device_info *di) { int cyct; cyct = bq27x00_read(di, BQ27x00_REG_CYCT, false); if (cyct < 0) dev_err(di->dev, "error reading cycle count total\n"); return cyct; } /* * Read a time register. * Return < 0 if something fails. */ static int bq27x00_battery_read_time(struct bq27x00_device_info *di, u8 reg) { int tval; tval = bq27x00_read(di, reg, false); if (tval < 0) { dev_err(di->dev, "error reading register %02x: %d\n", reg, tval); return tval; } if (tval == 65535) return -ENODATA; return tval * 60; } static void bq27x00_update(struct bq27x00_device_info *di) { struct bq27x00_reg_cache cache = {0, }; bool is_bq27500 = (di->chip == BQ27500 || di->chip == BQ27510); mutex_lock(&di->update_lock); cache.flags = bq27x00_read(di, BQ27x00_REG_FLAGS, is_bq27500); if (cache.flags >= 0) { cache.capacity = bq27x00_battery_read_rsoc(di); cache.temperature = bq27x00_read(di, BQ27x00_REG_TEMP, false); cache.time_to_empty = bq27x00_battery_read_time(di, BQ27x00_REG_TTE); cache.time_to_empty_avg = bq27x00_battery_read_time(di, BQ27x00_REG_TTECP); cache.time_to_full = bq27x00_battery_read_time(di, BQ27x00_REG_TTF); cache.charge_full = bq27x00_battery_read_lmd(di); cache.cycle_count = bq27x00_battery_read_cyct(di); if (!is_bq27500) cache.current_now = bq27x00_read(di, BQ27x00_REG_AI, false); /* We only have to read charge design full once */ if (di->charge_design_full <= 0) di->charge_design_full = bq27x00_battery_read_ilmd(di); } /* Ignore current_now which is a snapshot of the current battery state * and is likely to be different even between two consecutive reads */ if (memcmp(&di->cache, &cache, sizeof(cache) - sizeof(int)) != 0) { di->cache = cache; power_supply_changed(&di->bat); } di->last_update = jiffies; mutex_unlock(&di->update_lock); } static void bq27x00_battery_poll(struct work_struct *work) { struct bq27x00_device_info *di = container_of(work, struct bq27x00_device_info, work.work); bq27x00_update(di); if (poll_interval > 0) { /* The timer does not have to be accurate. */ set_timer_slack(&di->work.timer, poll_interval * HZ / 4); schedule_delayed_work(&di->work, poll_interval * HZ); } } static void bq27x00_external_power_changed_work(struct work_struct *work) { struct bq27x00_device_info *di = container_of(work, struct bq27x00_device_info, external_power_changed_work.work); bq27x00_update(di); } /* * Return the battery temperature in tenths of degree Celsius * Or < 0 if something fails. */ static int bq27x00_battery_temperature(struct bq27x00_device_info *di, union power_supply_propval *val) { if (di->cache.temperature < 0) return di->cache.temperature; if ((di->chip == BQ27500) || (di->chip == BQ27510)) val->intval = di->cache.temperature - 2731; else val->intval = ((di->cache.temperature * 5) - 5463) / 2; return 0; } /* * Return the battery average current in µA * Note that current can be negative signed as well * Or 0 if something fails. */ static int bq27x00_battery_current(struct bq27x00_device_info *di, union power_supply_propval *val) { int curr; if ((di->chip == BQ27500) || (di->chip == BQ27510)) curr = bq27x00_read(di, BQ27x00_REG_AI, false); else curr = di->cache.current_now; if (curr < 0) return curr; if ((di->chip == BQ27500) || (di->chip == BQ27510)) { /* bq27500 returns signed value */ val->intval = (int)((s16)curr) * 1000; } else { if (di->cache.flags & BQ27000_FLAG_CHGS) { dev_dbg(di->dev, "negative current!\n"); curr = -curr; } val->intval = curr * 3570 / BQ27000_RS; } return 0; } static int bq27x00_battery_status(struct bq27x00_device_info *di, union power_supply_propval *val) { int status; if ((di->chip == BQ27500) || (di->chip == BQ27510)) { if (di->cache.flags & BQ27500_FLAG_FC) status = POWER_SUPPLY_STATUS_FULL; else if (di->cache.flags & BQ27500_FLAG_DSC) status = POWER_SUPPLY_STATUS_DISCHARGING; else status = POWER_SUPPLY_STATUS_CHARGING; } else { if (di->cache.flags & BQ27000_FLAG_FC) status = POWER_SUPPLY_STATUS_FULL; else if (di->cache.flags & BQ27000_FLAG_CHGS) status = POWER_SUPPLY_STATUS_CHARGING; else if (power_supply_am_i_supplied(&di->bat)) status = POWER_SUPPLY_STATUS_NOT_CHARGING; else status = POWER_SUPPLY_STATUS_DISCHARGING; } val->intval = status; return 0; } /* * Return the battery Voltage in milivolts * Or < 0 if something fails. */ static int bq27x00_battery_voltage(struct bq27x00_device_info *di, union power_supply_propval *val) { int volt; volt = bq27x00_read(di, BQ27x00_REG_VOLT, false); if (volt < 0) return volt; val->intval = volt * 1000; return 0; } /* * Return the battery Available energy in µWh * Or < 0 if something fails. */ static int bq27x00_battery_energy(struct bq27x00_device_info *di, union power_supply_propval *val) { int ae; ae = bq27x00_read(di, BQ27x00_REG_AE, false); if (ae < 0) { dev_err(di->dev, "error reading available energy\n"); return ae; } if ((di->chip == BQ27500) || (di->chip == BQ27510)) ae *= 1000; else ae = ae * 29200 / BQ27000_RS; val->intval = ae; return 0; } static int bq27x00_simple_value(int value, union power_supply_propval *val) { if (value < 0) return value; val->intval = value; return 0; } static int bq27510_battery_present(struct bq27x00_device_info *di, union power_supply_propval *val) { int ret; ret = bq27x00_read(di, BQ27x00_REG_FLAGS, false); if (ret < 0) { dev_err(di->dev, "error reading flags\n"); return ret; } if (ret & BQ27500_FLAG_BAT_DET) val->intval = 1; else val->intval = 0; return 0; } static char bq27510_serial[5]; static int bq27510_get_battery_serial_number(struct bq27x00_device_info *di, union power_supply_propval *val) { int ret; if (di->chip == BQ27510) { ret = bq27x00_ctrl_read(di, BQ27510_CNTL, BQ27510_CNTL_DEVICE_TYPE); ret = sprintf(bq27510_serial, "%04x", ret); val->strval = bq27510_serial; return 0; } else { return 1; } } static int bq27510_battery_power_avg(struct bq27x00_device_info *di, union power_supply_propval *val) { int ret; if (di->chip == BQ27510) { ret = bq27x00_read(di, BQ27510_POWER_AVG, false); if (ret < 0) { dev_err(di->dev, "read failure\n"); return ret; } val->intval = ret; return 0; } return -1; } #define to_bq27x00_device_info(x) container_of((x), \ struct bq27x00_device_info, bat); static int bq27x00_battery_get_property(struct power_supply *psy, enum power_supply_property psp, union power_supply_propval *val) { int ret = 0; struct bq27x00_device_info *di = to_bq27x00_device_info(psy); mutex_lock(&di->lock); if (time_is_before_jiffies(di->last_update + 5 * HZ)) { cancel_delayed_work_sync(&di->work); bq27x00_battery_poll(&di->work.work); } mutex_unlock(&di->lock); if (psp != POWER_SUPPLY_PROP_PRESENT && di->cache.flags < 0) return -ENODEV; switch (psp) { case POWER_SUPPLY_PROP_STATUS: ret = bq27x00_battery_status(di, val); break; case POWER_SUPPLY_PROP_VOLTAGE_NOW: ret = bq27x00_battery_voltage(di, val); break; case POWER_SUPPLY_PROP_PRESENT: ret = bq27510_battery_present(di, val); break; case POWER_SUPPLY_PROP_CURRENT_NOW: ret = bq27x00_battery_current(di, val); break; case POWER_SUPPLY_PROP_CAPACITY: ret = bq27x00_simple_value(di->cache.capacity, val); break; case POWER_SUPPLY_PROP_TEMP: ret = bq27x00_battery_temperature(di, val); break; case POWER_SUPPLY_PROP_TIME_TO_EMPTY_NOW: ret = bq27x00_simple_value(di->cache.time_to_empty, val); break; case POWER_SUPPLY_PROP_TIME_TO_EMPTY_AVG: ret = bq27x00_simple_value(di->cache.time_to_empty_avg, val); break; case POWER_SUPPLY_PROP_TIME_TO_FULL_NOW: ret = bq27x00_simple_value(di->cache.time_to_full, val); break; case POWER_SUPPLY_PROP_TECHNOLOGY: val->intval = POWER_SUPPLY_TECHNOLOGY_LION; break; case POWER_SUPPLY_PROP_CHARGE_NOW: ret = bq27x00_simple_value(bq27x00_battery_read_nac(di), val); break; case POWER_SUPPLY_PROP_CHARGE_FULL: ret = bq27x00_simple_value(di->cache.charge_full, val); break; case POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN: ret = bq27x00_simple_value(di->charge_design_full, val); break; case POWER_SUPPLY_PROP_CYCLE_COUNT: ret = bq27x00_simple_value(di->cache.cycle_count, val); break; case POWER_SUPPLY_PROP_ENERGY_NOW: ret = bq27x00_battery_energy(di, val); break; case POWER_SUPPLY_PROP_POWER_AVG: ret = bq27510_battery_power_avg(di, val); break; case POWER_SUPPLY_PROP_SERIAL_NUMBER: if (bq27510_get_battery_serial_number(di, val)) return -EINVAL; break; case POWER_SUPPLY_PROP_HEALTH: ret = bq27510_battery_health(di, val); break; default: return -EINVAL; } return ret; } static unsigned int charging_update_delay_secs = CHARGING_STATUS_UPDATE_DELAY_SECS; module_param(charging_update_delay_secs, uint, 0644); MODULE_PARM_DESC(charging_update_delay_secs, "battery charging " \ "status update delay in seconds"); static void bq27x00_external_power_changed(struct power_supply *psy) { struct bq27x00_device_info *di = to_bq27x00_device_info(psy); cancel_delayed_work_sync(&di->external_power_changed_work); schedule_delayed_work(&di->external_power_changed_work, charging_update_delay_secs * HZ); } static int bq27x00_powersupply_init(struct bq27x00_device_info *di) { int ret; di->bat.type = POWER_SUPPLY_TYPE_BATTERY; di->bat.properties = bq27x00_battery_props; di->bat.num_properties = ARRAY_SIZE(bq27x00_battery_props); di->bat.get_property = bq27x00_battery_get_property; di->bat.external_power_changed = bq27x00_external_power_changed; INIT_DELAYED_WORK(&di->work, bq27x00_battery_poll); INIT_DELAYED_WORK(&di->external_power_changed_work, bq27x00_external_power_changed_work); mutex_init(&di->lock); mutex_init(&di->update_lock); ret = power_supply_register(di->dev, &di->bat); if (ret) { dev_err(di->dev, "failed to register battery: %d\n", ret); return ret; } dev_info(di->dev, "support ver. %s enabled\n", DRIVER_VERSION); bq27x00_update(di); return 0; } static void bq27x00_powersupply_unregister(struct bq27x00_device_info *di) { cancel_delayed_work_sync(&di->work); cancel_delayed_work_sync(&di->external_power_changed_work); power_supply_unregister(&di->bat); mutex_destroy(&di->lock); mutex_destroy(&di->update_lock); } /* i2c specific code */ #ifdef CONFIG_BATTERY_BQ27X00_I2C /* If the system has several batteries we need a different name for each * of them... */ static DEFINE_IDR(battery_id); static DEFINE_MUTEX(battery_mutex); static int bq27x00_read_i2c(struct bq27x00_device_info *di, u8 reg, bool single) { struct i2c_client *client = to_i2c_client(di->dev); struct i2c_msg msg[2]; unsigned char data[2]; int ret; if (!client->adapter) return -ENODEV; msg[0].addr = client->addr; msg[0].flags = 0; msg[0].buf = &reg; msg[0].len = sizeof(reg); msg[1].addr = client->addr; msg[1].flags = I2C_M_RD; msg[1].buf = data; if (single) msg[1].len = 1; else msg[1].len = 2; ret = i2c_transfer(client->adapter, msg, ARRAY_SIZE(msg)); if (ret < 0) return ret; if (!single) ret = get_unaligned_le16(data); else ret = data[0]; return ret; } static int bq27x00_write_i2c(struct bq27x00_device_info *di, u8 reg, u16 val, bool single) { struct i2c_client *client = to_i2c_client(di->dev); unsigned char i2c_data[3]; int ret, len; i2c_data[0] = reg; i2c_data[1] = val & 0xff; if (single) { len = 2; } else { i2c_data[2] = (val >> 8) & 0xff; len = 3; } ret = i2c_master_send(client, i2c_data, len); if (ret == len) return 0; return (ret < 0) ? ret : -EIO; } static int bq27x00_ctrl_read_i2c(struct bq27x00_device_info *di, u8 ctrl_reg, u16 ctrl_func_reg) { int ret = bq27x00_write(di, ctrl_reg, ctrl_func_reg, false); if (ret < 0) { dev_err(di->dev, "write failure\n"); return ret; } ret = bq27x00_read(di, ctrl_reg, false); if (ret < 0) { dev_err(di->dev, "read failure\n"); return ret; } return ret; } static int bq27x00_battery_probe(struct i2c_client *client, const struct i2c_device_id *id) { char *name; struct bq27x00_device_info *di; int num; u16 read_data; int retval = 0; /* Get new ID for the new battery device */ retval = idr_pre_get(&battery_id, GFP_KERNEL); if (retval == 0) return -ENOMEM; mutex_lock(&battery_mutex); retval = idr_get_new(&battery_id, client, &num); mutex_unlock(&battery_mutex); if (retval < 0) return retval; name = kasprintf(GFP_KERNEL, "%s-%d", id->name, num); if (!name) { dev_err(&client->dev, "failed to allocate device name\n"); retval = -ENOMEM; goto batt_failed_1; } di = kzalloc(sizeof(*di), GFP_KERNEL); if (!di) { dev_err(&client->dev, "failed to allocate device info data\n"); retval = -ENOMEM; goto batt_failed_2; } di->id = num; di->dev = &client->dev; di->chip = id->driver_data; di->bat.name = name; di->bus.read = &bq27x00_read_i2c; di->bus.ctrl_read = &bq27x00_ctrl_read_i2c; di->bus.write = &bq27x00_write_i2c; i2c_set_clientdata(client, di); /* Let's see whether this adapter can support what we need. */ if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) { dev_err(&client->dev, "insufficient functionality!\n"); retval = -ENODEV; goto batt_failed_3; } read_data = bq27x00_read(di, BQ27x00_REG_FLAGS, false); if (!(read_data & BQ27500_FLAG_BAT_DET)) { dev_err(&client->dev, "no battery present\n"); retval = -ENODEV; goto batt_failed_3; } retval = bq27x00_powersupply_init(di); if (retval < 0) goto batt_failed_3; return 0; batt_failed_3: kfree(di); batt_failed_2: kfree(name); batt_failed_1: mutex_lock(&battery_mutex); idr_remove(&battery_id, num); mutex_unlock(&battery_mutex); return retval; } static int bq27x00_battery_remove(struct i2c_client *client) { struct bq27x00_device_info *di = i2c_get_clientdata(client); bq27x00_powersupply_unregister(di); kfree(di->bat.name); mutex_lock(&battery_mutex); idr_remove(&battery_id, di->id); mutex_unlock(&battery_mutex); kfree(di); return 0; } #ifdef CONFIG_PM static int bq27x00_battery_suspend(struct device *dev) { int ret; struct platform_device *pdev = to_platform_device(dev); struct bq27x00_device_info *di = platform_get_drvdata(pdev); cancel_delayed_work_sync(&di->work); cancel_delayed_work_sync(&di->external_power_changed_work); if (di->chip == BQ27510) { ret = bq27x00_write(di, BQ27510_CNTL, BQ27510_CNTL_SET_SLEEP, false); if (ret < 0) { dev_err(di->dev, "write failure\n"); return ret; } ret = bq27x00_write(di, BQ27510_CNTL, 0x01, false); if (ret < 0) { dev_err(di->dev, "write failure\n"); return ret; } } return 0; } static int bq27x00_battery_resume(struct device *dev) { int ret; struct platform_device *pdev = to_platform_device(dev); struct bq27x00_device_info *di = platform_get_drvdata(pdev); if (di->chip == BQ27510) { ret = bq27x00_write(di, BQ27510_CNTL, BQ27510_CNTL_CLEAR_SLEEP, false); if (ret < 0) { dev_err(di->dev, "write failure\n"); return ret; } ret = bq27x00_write(di, BQ27510_CNTL, 0x01, false); if (ret < 0) { dev_err(di->dev, "write failure\n"); return ret; } } schedule_delayed_work(&di->work, HZ); return 0; } static const struct dev_pm_ops bq27x00_battery_pm_ops = { .suspend = bq27x00_battery_suspend, .resume = bq27x00_battery_resume, }; #endif static const struct i2c_device_id bq27x00_id[] = { { "bq27200", BQ27000 }, /* bq27200 is same as bq27000, but with i2c */ { "bq27500", BQ27500 }, { "bq27510", BQ27510 }, {}, }; MODULE_DEVICE_TABLE(i2c, bq27x00_id); static struct i2c_driver bq27x00_battery_driver = { .probe = bq27x00_battery_probe, .remove = bq27x00_battery_remove, .id_table = bq27x00_id, .driver = { .name = "bq27x00-battery", #if defined(CONFIG_PM) .pm = &bq27x00_battery_pm_ops, #endif }, }; static inline int bq27x00_battery_i2c_init(void) { int ret = i2c_add_driver(&bq27x00_battery_driver); if (ret) printk(KERN_ERR "Unable to register BQ27x00 i2c driver\n"); return ret; } static inline void bq27x00_battery_i2c_exit(void) { i2c_del_driver(&bq27x00_battery_driver); } #else static inline int bq27x00_battery_i2c_init(void) { return 0; } static inline void bq27x00_battery_i2c_exit(void) {}; #endif /* platform specific code */ #ifdef CONFIG_BATTERY_BQ27X00_PLATFORM static int bq27000_read_platform(struct bq27x00_device_info *di, u8 reg, bool single) { struct device *dev = di->dev; struct bq27000_platform_data *pdata = dev->platform_data; unsigned int timeout = 3; int upper, lower; int temp; if (!single) { /* Make sure the value has not changed in between reading the * lower and the upper part */ upper = pdata->read(dev, reg + 1); do { temp = upper; if (upper < 0) return upper; lower = pdata->read(dev, reg); if (lower < 0) return lower; upper = pdata->read(dev, reg + 1); } while (temp != upper && --timeout); if (timeout == 0) return -EIO; return (upper << 8) | lower; } return pdata->read(dev, reg); } static int __devinit bq27000_battery_probe(struct platform_device *pdev) { struct bq27x00_device_info *di; struct bq27000_platform_data *pdata = pdev->dev.platform_data; int ret; if (!pdata) { dev_err(&pdev->dev, "no platform_data supplied\n"); return -EINVAL; } if (!pdata->read) { dev_err(&pdev->dev, "no hdq read callback supplied\n"); return -EINVAL; } di = kzalloc(sizeof(*di), GFP_KERNEL); if (!di) { dev_err(&pdev->dev, "failed to allocate device info data\n"); return -ENOMEM; } platform_set_drvdata(pdev, di); di->dev = &pdev->dev; di->chip = BQ27000; di->bat.name = pdata->name ?: dev_name(&pdev->dev); di->bus.read = &bq27000_read_platform; ret = bq27x00_powersupply_init(di); if (ret) goto err_free; return 0; err_free: platform_set_drvdata(pdev, NULL); kfree(di); return ret; } static int __devexit bq27000_battery_remove(struct platform_device *pdev) { struct bq27x00_device_info *di = platform_get_drvdata(pdev); bq27x00_powersupply_unregister(di); platform_set_drvdata(pdev, NULL); kfree(di); return 0; } static struct platform_driver bq27000_battery_driver = { .probe = bq27000_battery_probe, .remove = __devexit_p(bq27000_battery_remove), .driver = { .name = "bq27000-battery", .owner = THIS_MODULE, }, }; static inline int bq27x00_battery_platform_init(void) { int ret = platform_driver_register(&bq27000_battery_driver); if (ret) printk(KERN_ERR "Unable to register BQ27000 platform driver\n"); return ret; } static inline void bq27x00_battery_platform_exit(void) { platform_driver_unregister(&bq27000_battery_driver); } #else static inline int bq27x00_battery_platform_init(void) { return 0; } static inline void bq27x00_battery_platform_exit(void) {}; #endif /* * Module stuff */ static int __init bq27x00_battery_init(void) { int ret; ret = bq27x00_battery_i2c_init(); if (ret) return ret; ret = bq27x00_battery_platform_init(); if (ret) bq27x00_battery_i2c_exit(); return ret; } module_init(bq27x00_battery_init); static void __exit bq27x00_battery_exit(void) { bq27x00_battery_platform_exit(); bq27x00_battery_i2c_exit(); } module_exit(bq27x00_battery_exit); MODULE_AUTHOR("Rodolfo Giometti <giometti@linux.it>"); MODULE_DESCRIPTION("BQ27x00 battery monitor driver"); MODULE_LICENSE("GPL");
gpl-3.0
guysoft/Marlin
ArduinoAddons/Arduino_1.5.x/hardware/marlin/avr/libraries/U8glib/utility/u8g_com_arduino_parallel.c
411
5309
/* u8g_arduino_parallel.c Universal 8bit Graphics Library Copyright (c) 2011, olikraus@gmail.com All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. PIN_D0 8 PIN_D1 9 PIN_D2 10 PIN_D3 11 PIN_D4 4 PIN_D5 5 PIN_D6 6 PIN_D7 7 PIN_CS1 14 PIN_CS2 15 PIN_RW 16 PIN_DI 17 PIN_EN 18 u8g_Init8Bit(u8g, dev, d0, d1, d2, d3, d4, d5, d6, d7, en, cs1, cs2, di, rw, reset) u8g_Init8Bit(u8g, dev, 8, 9, 10, 11, 4, 5, 6, 7, 18, 14, 15, 17, 16, U8G_PIN_NONE) */ #include "u8g.h" #if defined(ARDUINO) #if ARDUINO < 100 #include <WProgram.h> #else #include <Arduino.h> #endif void u8g_com_arduino_parallel_write(u8g_t *u8g, uint8_t val) { u8g_com_arduino_digital_write(u8g, U8G_PI_D0, val&1); val >>= 1; u8g_com_arduino_digital_write(u8g, U8G_PI_D1, val&1); val >>= 1; u8g_com_arduino_digital_write(u8g, U8G_PI_D2, val&1); val >>= 1; u8g_com_arduino_digital_write(u8g, U8G_PI_D3, val&1); val >>= 1; u8g_com_arduino_digital_write(u8g, U8G_PI_D4, val&1); val >>= 1; u8g_com_arduino_digital_write(u8g, U8G_PI_D5, val&1); val >>= 1; u8g_com_arduino_digital_write(u8g, U8G_PI_D6, val&1); val >>= 1; u8g_com_arduino_digital_write(u8g, U8G_PI_D7, val&1); /* EN cycle time must be 1 micro second, digitalWrite is slow enough to do this */ //u8g_Delay(1); u8g_com_arduino_digital_write(u8g, U8G_PI_EN, HIGH); //u8g_Delay(1); u8g_MicroDelay(); /* delay by 1000ns, reference: ST7920: 140ns, SBN1661: 100ns */ u8g_com_arduino_digital_write(u8g, U8G_PI_EN, LOW); u8g_10MicroDelay(); /* ST7920 commands: 72us */ //u8g_Delay(2); } uint8_t u8g_com_arduino_parallel_fn(u8g_t *u8g, uint8_t msg, uint8_t arg_val, void *arg_ptr) { switch(msg) { case U8G_COM_MSG_INIT: /* setup the RW pin as output and force it to low */ if ( u8g->pin_list[U8G_PI_RW] != U8G_PIN_NONE ) { pinMode(u8g->pin_list[U8G_PI_RW], OUTPUT); u8g_com_arduino_digital_write(u8g, U8G_PI_RW, LOW); } /* set all pins (except RW pin) */ u8g_com_arduino_assign_pin_output_high(u8g); break; case U8G_COM_MSG_STOP: break; case U8G_COM_MSG_CHIP_SELECT: if ( arg_val == 0 ) { /* disable */ u8g_com_arduino_digital_write(u8g, U8G_PI_CS1, HIGH); u8g_com_arduino_digital_write(u8g, U8G_PI_CS2, HIGH); } else if ( arg_val == 1 ) { /* enable */ u8g_com_arduino_digital_write(u8g, U8G_PI_CS1, LOW); u8g_com_arduino_digital_write(u8g, U8G_PI_CS2, HIGH); } else if ( arg_val == 2 ) { /* enable */ u8g_com_arduino_digital_write(u8g, U8G_PI_CS1, HIGH); u8g_com_arduino_digital_write(u8g, U8G_PI_CS2, LOW); } else { /* enable */ u8g_com_arduino_digital_write(u8g, U8G_PI_CS1, LOW); u8g_com_arduino_digital_write(u8g, U8G_PI_CS2, LOW); } break; case U8G_COM_MSG_WRITE_BYTE: u8g_com_arduino_parallel_write(u8g, arg_val); break; case U8G_COM_MSG_WRITE_SEQ: { register uint8_t *ptr = arg_ptr; while( arg_val > 0 ) { u8g_com_arduino_parallel_write(u8g, *ptr++); arg_val--; } } break; case U8G_COM_MSG_WRITE_SEQ_P: { register uint8_t *ptr = arg_ptr; while( arg_val > 0 ) { u8g_com_arduino_parallel_write(u8g, u8g_pgm_read(ptr)); ptr++; arg_val--; } } break; case U8G_COM_MSG_ADDRESS: /* define cmd (arg_val = 0) or data mode (arg_val = 1) */ u8g_com_arduino_digital_write(u8g, U8G_PI_DI, arg_val); break; case U8G_COM_MSG_RESET: if ( u8g->pin_list[U8G_PI_RESET] != U8G_PIN_NONE ) u8g_com_arduino_digital_write(u8g, U8G_PI_RESET, arg_val); break; } return 1; } #else uint8_t u8g_com_arduino_parallel_fn(u8g_t *u8g, uint8_t msg, uint8_t arg_val, void *arg_ptr) { return 1; } #endif /* ARDUINO */
gpl-3.0
cosmomill/Signal-Android
jni/openssl/crypto/asn1/a_time.c
673
5904
/* crypto/asn1/a_time.c */ /* ==================================================================== * Copyright (c) 1999 The OpenSSL Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * licensing@OpenSSL.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * ==================================================================== * * This product includes cryptographic software written by Eric Young * (eay@cryptsoft.com). This product includes software written by Tim * Hudson (tjh@cryptsoft.com). * */ /* This is an implementation of the ASN1 Time structure which is: * Time ::= CHOICE { * utcTime UTCTime, * generalTime GeneralizedTime } * written by Steve Henson. */ #include <stdio.h> #include <time.h> #include "cryptlib.h" #include "o_time.h" #include <openssl/asn1t.h> IMPLEMENT_ASN1_MSTRING(ASN1_TIME, B_ASN1_TIME) IMPLEMENT_ASN1_FUNCTIONS(ASN1_TIME) #if 0 int i2d_ASN1_TIME(ASN1_TIME *a, unsigned char **pp) { #ifdef CHARSET_EBCDIC /* KLUDGE! We convert to ascii before writing DER */ char tmp[24]; ASN1_STRING tmpstr; if(a->type == V_ASN1_UTCTIME || a->type == V_ASN1_GENERALIZEDTIME) { int len; tmpstr = *(ASN1_STRING *)a; len = tmpstr.length; ebcdic2ascii(tmp, tmpstr.data, (len >= sizeof tmp) ? sizeof tmp : len); tmpstr.data = tmp; a = (ASN1_GENERALIZEDTIME *) &tmpstr; } #endif if(a->type == V_ASN1_UTCTIME || a->type == V_ASN1_GENERALIZEDTIME) return(i2d_ASN1_bytes((ASN1_STRING *)a,pp, a->type ,V_ASN1_UNIVERSAL)); ASN1err(ASN1_F_I2D_ASN1_TIME,ASN1_R_EXPECTING_A_TIME); return -1; } #endif ASN1_TIME *ASN1_TIME_set(ASN1_TIME *s, time_t t) { return ASN1_TIME_adj(s, t, 0, 0); } ASN1_TIME *ASN1_TIME_adj(ASN1_TIME *s, time_t t, int offset_day, long offset_sec) { struct tm *ts; struct tm data; ts=OPENSSL_gmtime(&t,&data); if (ts == NULL) { ASN1err(ASN1_F_ASN1_TIME_ADJ, ASN1_R_ERROR_GETTING_TIME); return NULL; } if (offset_day || offset_sec) { if (!OPENSSL_gmtime_adj(ts, offset_day, offset_sec)) return NULL; } if((ts->tm_year >= 50) && (ts->tm_year < 150)) return ASN1_UTCTIME_adj(s, t, offset_day, offset_sec); return ASN1_GENERALIZEDTIME_adj(s, t, offset_day, offset_sec); } int ASN1_TIME_check(ASN1_TIME *t) { if (t->type == V_ASN1_GENERALIZEDTIME) return ASN1_GENERALIZEDTIME_check(t); else if (t->type == V_ASN1_UTCTIME) return ASN1_UTCTIME_check(t); return 0; } /* Convert an ASN1_TIME structure to GeneralizedTime */ ASN1_GENERALIZEDTIME *ASN1_TIME_to_generalizedtime(ASN1_TIME *t, ASN1_GENERALIZEDTIME **out) { ASN1_GENERALIZEDTIME *ret; char *str; int newlen; if (!ASN1_TIME_check(t)) return NULL; if (!out || !*out) { if (!(ret = ASN1_GENERALIZEDTIME_new ())) return NULL; if (out) *out = ret; } else ret = *out; /* If already GeneralizedTime just copy across */ if (t->type == V_ASN1_GENERALIZEDTIME) { if(!ASN1_STRING_set(ret, t->data, t->length)) return NULL; return ret; } /* grow the string */ if (!ASN1_STRING_set(ret, NULL, t->length + 2)) return NULL; /* ASN1_STRING_set() allocated 'len + 1' bytes. */ newlen = t->length + 2 + 1; str = (char *)ret->data; /* Work out the century and prepend */ if (t->data[0] >= '5') BUF_strlcpy(str, "19", newlen); else BUF_strlcpy(str, "20", newlen); BUF_strlcat(str, (char *)t->data, newlen); return ret; } int ASN1_TIME_set_string(ASN1_TIME *s, const char *str) { ASN1_TIME t; t.length = strlen(str); t.data = (unsigned char *)str; t.flags = 0; t.type = V_ASN1_UTCTIME; if (!ASN1_TIME_check(&t)) { t.type = V_ASN1_GENERALIZEDTIME; if (!ASN1_TIME_check(&t)) return 0; } if (s && !ASN1_STRING_copy((ASN1_STRING *)s, (ASN1_STRING *)&t)) return 0; return 1; }
gpl-3.0
IXgnas/dixcovery_kernel
arch/sh/mm/uncached.c
12194
1176
#include <linux/init.h> #include <linux/module.h> #include <asm/sizes.h> #include <asm/page.h> #include <asm/addrspace.h> /* * This is the offset of the uncached section from its cached alias. * * Legacy platforms handle trivial transitions between cached and * uncached segments by making use of the 1:1 mapping relationship in * 512MB lowmem, others via a special uncached mapping. * * Default value only valid in 29 bit mode, in 32bit mode this will be * updated by the early PMB initialization code. */ unsigned long cached_to_uncached = SZ_512M; unsigned long uncached_size = SZ_512M; unsigned long uncached_start, uncached_end; EXPORT_SYMBOL(uncached_start); EXPORT_SYMBOL(uncached_end); int virt_addr_uncached(unsigned long kaddr) { return (kaddr >= uncached_start) && (kaddr < uncached_end); } EXPORT_SYMBOL(virt_addr_uncached); void __init uncached_init(void) { #if defined(CONFIG_29BIT) || !defined(CONFIG_MMU) uncached_start = P2SEG; #else uncached_start = memory_end; #endif uncached_end = uncached_start + uncached_size; } void __init uncached_resize(unsigned long size) { uncached_size = size; uncached_end = uncached_start + uncached_size; }
gpl-3.0
danialbehzadi/Nokia-RM-1013-2.0.0.11
kernel/arch/arm/mach-imx/mx51_efika.c
5036
15697
/* * based on code from the following * Copyright 2009-2010 Freescale Semiconductor, Inc. All Rights Reserved. * Copyright 2009-2010 Pegatron Corporation. All Rights Reserved. * Copyright 2009-2010 Genesi USA, Inc. All Rights Reserved. * * The code contained herein is licensed under the GNU General Public * License. You may obtain a copy of the GNU General Public License * Version 2 or later at the following locations: * * http://www.opensource.org/licenses/gpl-license.html * http://www.gnu.org/copyleft/gpl.html */ #include <linux/init.h> #include <linux/platform_device.h> #include <linux/i2c.h> #include <linux/gpio.h> #include <linux/leds.h> #include <linux/input.h> #include <linux/delay.h> #include <linux/io.h> #include <linux/spi/flash.h> #include <linux/spi/spi.h> #include <linux/mfd/mc13892.h> #include <linux/regulator/machine.h> #include <linux/regulator/consumer.h> #include <mach/common.h> #include <mach/hardware.h> #include <mach/iomux-mx51.h> #include <linux/usb/otg.h> #include <linux/usb/ulpi.h> #include <mach/ulpi.h> #include <asm/setup.h> #include <asm/mach-types.h> #include <asm/mach/arch.h> #include <asm/mach/time.h> #include "devices-imx51.h" #include "efika.h" #include "cpu_op-mx51.h" #define MX51_USB_CTRL_1_OFFSET 0x10 #define MX51_USB_CTRL_UH1_EXT_CLK_EN (1 << 25) #define MX51_USB_PLL_DIV_19_2_MHZ 0x01 #define EFIKAMX_USB_HUB_RESET IMX_GPIO_NR(1, 5) #define EFIKAMX_USBH1_STP IMX_GPIO_NR(1, 27) #define EFIKAMX_SPI_CS0 IMX_GPIO_NR(4, 24) #define EFIKAMX_SPI_CS1 IMX_GPIO_NR(4, 25) #define EFIKAMX_PMIC IMX_GPIO_NR(1, 6) static iomux_v3_cfg_t mx51efika_pads[] = { /* UART1 */ MX51_PAD_UART1_RXD__UART1_RXD, MX51_PAD_UART1_TXD__UART1_TXD, MX51_PAD_UART1_RTS__UART1_RTS, MX51_PAD_UART1_CTS__UART1_CTS, /* SD 1 */ MX51_PAD_SD1_CMD__SD1_CMD, MX51_PAD_SD1_CLK__SD1_CLK, MX51_PAD_SD1_DATA0__SD1_DATA0, MX51_PAD_SD1_DATA1__SD1_DATA1, MX51_PAD_SD1_DATA2__SD1_DATA2, MX51_PAD_SD1_DATA3__SD1_DATA3, /* SD 2 */ MX51_PAD_SD2_CMD__SD2_CMD, MX51_PAD_SD2_CLK__SD2_CLK, MX51_PAD_SD2_DATA0__SD2_DATA0, MX51_PAD_SD2_DATA1__SD2_DATA1, MX51_PAD_SD2_DATA2__SD2_DATA2, MX51_PAD_SD2_DATA3__SD2_DATA3, /* SD/MMC WP/CD */ MX51_PAD_GPIO1_0__SD1_CD, MX51_PAD_GPIO1_1__SD1_WP, MX51_PAD_GPIO1_7__SD2_WP, MX51_PAD_GPIO1_8__SD2_CD, /* spi */ MX51_PAD_CSPI1_MOSI__ECSPI1_MOSI, MX51_PAD_CSPI1_MISO__ECSPI1_MISO, MX51_PAD_CSPI1_SS0__GPIO4_24, MX51_PAD_CSPI1_SS1__GPIO4_25, MX51_PAD_CSPI1_RDY__ECSPI1_RDY, MX51_PAD_CSPI1_SCLK__ECSPI1_SCLK, MX51_PAD_GPIO1_6__GPIO1_6, /* USB HOST1 */ MX51_PAD_USBH1_CLK__USBH1_CLK, MX51_PAD_USBH1_DIR__USBH1_DIR, MX51_PAD_USBH1_NXT__USBH1_NXT, MX51_PAD_USBH1_DATA0__USBH1_DATA0, MX51_PAD_USBH1_DATA1__USBH1_DATA1, MX51_PAD_USBH1_DATA2__USBH1_DATA2, MX51_PAD_USBH1_DATA3__USBH1_DATA3, MX51_PAD_USBH1_DATA4__USBH1_DATA4, MX51_PAD_USBH1_DATA5__USBH1_DATA5, MX51_PAD_USBH1_DATA6__USBH1_DATA6, MX51_PAD_USBH1_DATA7__USBH1_DATA7, /* USB HUB RESET */ MX51_PAD_GPIO1_5__GPIO1_5, /* WLAN */ MX51_PAD_EIM_A22__GPIO2_16, MX51_PAD_EIM_A16__GPIO2_10, /* USB PHY RESET */ MX51_PAD_EIM_D27__GPIO2_9, }; /* Serial ports */ static const struct imxuart_platform_data uart_pdata = { .flags = IMXUART_HAVE_RTSCTS, }; /* This function is board specific as the bit mask for the plldiv will also * be different for other Freescale SoCs, thus a common bitmask is not * possible and cannot get place in /plat-mxc/ehci.c. */ static int initialize_otg_port(struct platform_device *pdev) { u32 v; void __iomem *usb_base; void __iomem *usbother_base; usb_base = ioremap(MX51_USB_OTG_BASE_ADDR, SZ_4K); if (!usb_base) return -ENOMEM; usbother_base = (void __iomem *)(usb_base + MX5_USBOTHER_REGS_OFFSET); /* Set the PHY clock to 19.2MHz */ v = __raw_readl(usbother_base + MXC_USB_PHY_CTR_FUNC2_OFFSET); v &= ~MX5_USB_UTMI_PHYCTRL1_PLLDIV_MASK; v |= MX51_USB_PLL_DIV_19_2_MHZ; __raw_writel(v, usbother_base + MXC_USB_PHY_CTR_FUNC2_OFFSET); iounmap(usb_base); mdelay(10); return mx51_initialize_usb_hw(pdev->id, MXC_EHCI_INTERNAL_PHY); } static const struct mxc_usbh_platform_data dr_utmi_config __initconst = { .init = initialize_otg_port, .portsc = MXC_EHCI_UTMI_16BIT, }; static int initialize_usbh1_port(struct platform_device *pdev) { iomux_v3_cfg_t usbh1stp = MX51_PAD_USBH1_STP__USBH1_STP; iomux_v3_cfg_t usbh1gpio = MX51_PAD_USBH1_STP__GPIO1_27; u32 v; void __iomem *usb_base; void __iomem *socregs_base; mxc_iomux_v3_setup_pad(usbh1gpio); gpio_request(EFIKAMX_USBH1_STP, "usbh1_stp"); gpio_direction_output(EFIKAMX_USBH1_STP, 0); msleep(1); gpio_set_value(EFIKAMX_USBH1_STP, 1); msleep(1); usb_base = ioremap(MX51_USB_OTG_BASE_ADDR, SZ_4K); socregs_base = (void __iomem *)(usb_base + MX5_USBOTHER_REGS_OFFSET); /* The clock for the USBH1 ULPI port will come externally */ /* from the PHY. */ v = __raw_readl(socregs_base + MX51_USB_CTRL_1_OFFSET); __raw_writel(v | MX51_USB_CTRL_UH1_EXT_CLK_EN, socregs_base + MX51_USB_CTRL_1_OFFSET); iounmap(usb_base); gpio_free(EFIKAMX_USBH1_STP); mxc_iomux_v3_setup_pad(usbh1stp); mdelay(10); return mx51_initialize_usb_hw(pdev->id, MXC_EHCI_ITC_NO_THRESHOLD); } static struct mxc_usbh_platform_data usbh1_config __initdata = { .init = initialize_usbh1_port, .portsc = MXC_EHCI_MODE_ULPI, }; static void mx51_efika_hubreset(void) { gpio_request(EFIKAMX_USB_HUB_RESET, "usb_hub_rst"); gpio_direction_output(EFIKAMX_USB_HUB_RESET, 1); msleep(1); gpio_set_value(EFIKAMX_USB_HUB_RESET, 0); msleep(1); gpio_set_value(EFIKAMX_USB_HUB_RESET, 1); } static void __init mx51_efika_usb(void) { mx51_efika_hubreset(); /* pulling it low, means no USB at all... */ gpio_request(EFIKA_USB_PHY_RESET, "usb_phy_reset"); gpio_direction_output(EFIKA_USB_PHY_RESET, 0); msleep(1); gpio_set_value(EFIKA_USB_PHY_RESET, 1); usbh1_config.otg = imx_otg_ulpi_create(ULPI_OTG_DRVVBUS | ULPI_OTG_DRVVBUS_EXT | ULPI_OTG_EXTVBUSIND); imx51_add_mxc_ehci_otg(&dr_utmi_config); if (usbh1_config.otg) imx51_add_mxc_ehci_hs(1, &usbh1_config); } static struct mtd_partition mx51_efika_spi_nor_partitions[] = { { .name = "u-boot", .offset = 0, .size = SZ_256K, }, { .name = "config", .offset = MTDPART_OFS_APPEND, .size = SZ_64K, }, }; static struct flash_platform_data mx51_efika_spi_flash_data = { .name = "spi_flash", .parts = mx51_efika_spi_nor_partitions, .nr_parts = ARRAY_SIZE(mx51_efika_spi_nor_partitions), .type = "sst25vf032b", }; static struct regulator_consumer_supply sw1_consumers[] = { { .supply = "cpu_vcc", } }; static struct regulator_consumer_supply vdig_consumers[] = { /* sgtl5000 */ REGULATOR_SUPPLY("VDDA", "1-000a"), REGULATOR_SUPPLY("VDDD", "1-000a"), }; static struct regulator_consumer_supply vvideo_consumers[] = { /* sgtl5000 */ REGULATOR_SUPPLY("VDDIO", "1-000a"), }; static struct regulator_consumer_supply vsd_consumers[] = { REGULATOR_SUPPLY("vmmc", "sdhci-esdhc-imx51.0"), REGULATOR_SUPPLY("vmmc", "sdhci-esdhc-imx51.1"), }; static struct regulator_consumer_supply pwgt1_consumer[] = { { .supply = "pwgt1", } }; static struct regulator_consumer_supply pwgt2_consumer[] = { { .supply = "pwgt2", } }; static struct regulator_consumer_supply coincell_consumer[] = { { .supply = "coincell", } }; static struct regulator_init_data sw1_init = { .constraints = { .name = "SW1", .min_uV = 600000, .max_uV = 1375000, .valid_ops_mask = REGULATOR_CHANGE_VOLTAGE, .valid_modes_mask = 0, .always_on = 1, .boot_on = 1, .state_mem = { .uV = 850000, .mode = REGULATOR_MODE_NORMAL, .enabled = 1, }, }, .num_consumer_supplies = ARRAY_SIZE(sw1_consumers), .consumer_supplies = sw1_consumers, }; static struct regulator_init_data sw2_init = { .constraints = { .name = "SW2", .min_uV = 900000, .max_uV = 1850000, .valid_ops_mask = REGULATOR_CHANGE_VOLTAGE, .always_on = 1, .boot_on = 1, .state_mem = { .uV = 950000, .mode = REGULATOR_MODE_NORMAL, .enabled = 1, }, } }; static struct regulator_init_data sw3_init = { .constraints = { .name = "SW3", .min_uV = 1100000, .max_uV = 1850000, .valid_ops_mask = REGULATOR_CHANGE_VOLTAGE, .always_on = 1, .boot_on = 1, } }; static struct regulator_init_data sw4_init = { .constraints = { .name = "SW4", .min_uV = 1100000, .max_uV = 1850000, .valid_ops_mask = REGULATOR_CHANGE_VOLTAGE, .always_on = 1, .boot_on = 1, } }; static struct regulator_init_data viohi_init = { .constraints = { .name = "VIOHI", .boot_on = 1, .always_on = 1, } }; static struct regulator_init_data vusb_init = { .constraints = { .name = "VUSB", .boot_on = 1, .always_on = 1, } }; static struct regulator_init_data swbst_init = { .constraints = { .name = "SWBST", } }; static struct regulator_init_data vdig_init = { .constraints = { .name = "VDIG", .min_uV = 1050000, .max_uV = 1800000, .valid_ops_mask = REGULATOR_CHANGE_VOLTAGE | REGULATOR_CHANGE_STATUS, .boot_on = 1, .always_on = 1, }, .num_consumer_supplies = ARRAY_SIZE(vdig_consumers), .consumer_supplies = vdig_consumers, }; static struct regulator_init_data vpll_init = { .constraints = { .name = "VPLL", .min_uV = 1050000, .max_uV = 1800000, .valid_ops_mask = REGULATOR_CHANGE_VOLTAGE | REGULATOR_CHANGE_STATUS, .boot_on = 1, .always_on = 1, } }; static struct regulator_init_data vusb2_init = { .constraints = { .name = "VUSB2", .min_uV = 2400000, .max_uV = 2775000, .valid_ops_mask = REGULATOR_CHANGE_VOLTAGE, .boot_on = 1, .always_on = 1, } }; static struct regulator_init_data vvideo_init = { .constraints = { .name = "VVIDEO", .min_uV = 2775000, .max_uV = 2775000, .valid_ops_mask = REGULATOR_CHANGE_VOLTAGE | REGULATOR_CHANGE_STATUS, .boot_on = 1, .apply_uV = 1, }, .num_consumer_supplies = ARRAY_SIZE(vvideo_consumers), .consumer_supplies = vvideo_consumers, }; static struct regulator_init_data vaudio_init = { .constraints = { .name = "VAUDIO", .min_uV = 2300000, .max_uV = 3000000, .valid_ops_mask = REGULATOR_CHANGE_VOLTAGE | REGULATOR_CHANGE_STATUS, .boot_on = 1, } }; static struct regulator_init_data vsd_init = { .constraints = { .name = "VSD", .min_uV = 1800000, .max_uV = 3150000, .valid_ops_mask = REGULATOR_CHANGE_VOLTAGE, .boot_on = 1, }, .num_consumer_supplies = ARRAY_SIZE(vsd_consumers), .consumer_supplies = vsd_consumers, }; static struct regulator_init_data vcam_init = { .constraints = { .name = "VCAM", .min_uV = 2500000, .max_uV = 3000000, .valid_ops_mask = REGULATOR_CHANGE_VOLTAGE | REGULATOR_CHANGE_MODE | REGULATOR_CHANGE_STATUS, .valid_modes_mask = REGULATOR_MODE_FAST | REGULATOR_MODE_NORMAL, .boot_on = 1, } }; static struct regulator_init_data vgen1_init = { .constraints = { .name = "VGEN1", .min_uV = 1200000, .max_uV = 3150000, .valid_ops_mask = REGULATOR_CHANGE_VOLTAGE | REGULATOR_CHANGE_STATUS, .boot_on = 1, .always_on = 1, } }; static struct regulator_init_data vgen2_init = { .constraints = { .name = "VGEN2", .min_uV = 1200000, .max_uV = 3150000, .valid_ops_mask = REGULATOR_CHANGE_VOLTAGE | REGULATOR_CHANGE_STATUS, .boot_on = 1, .always_on = 1, } }; static struct regulator_init_data vgen3_init = { .constraints = { .name = "VGEN3", .min_uV = 1800000, .max_uV = 2900000, .valid_ops_mask = REGULATOR_CHANGE_VOLTAGE | REGULATOR_CHANGE_STATUS, .boot_on = 1, .always_on = 1, } }; static struct regulator_init_data gpo1_init = { .constraints = { .name = "GPO1", } }; static struct regulator_init_data gpo2_init = { .constraints = { .name = "GPO2", } }; static struct regulator_init_data gpo3_init = { .constraints = { .name = "GPO3", } }; static struct regulator_init_data gpo4_init = { .constraints = { .name = "GPO4", } }; static struct regulator_init_data pwgt1_init = { .constraints = { .valid_ops_mask = REGULATOR_CHANGE_STATUS, .boot_on = 1, }, .num_consumer_supplies = ARRAY_SIZE(pwgt1_consumer), .consumer_supplies = pwgt1_consumer, }; static struct regulator_init_data pwgt2_init = { .constraints = { .valid_ops_mask = REGULATOR_CHANGE_STATUS, .boot_on = 1, }, .num_consumer_supplies = ARRAY_SIZE(pwgt2_consumer), .consumer_supplies = pwgt2_consumer, }; static struct regulator_init_data vcoincell_init = { .constraints = { .name = "COINCELL", .min_uV = 3000000, .max_uV = 3000000, .valid_ops_mask = REGULATOR_CHANGE_VOLTAGE | REGULATOR_CHANGE_STATUS, }, .num_consumer_supplies = ARRAY_SIZE(coincell_consumer), .consumer_supplies = coincell_consumer, }; static struct mc13xxx_regulator_init_data mx51_efika_regulators[] = { { .id = MC13892_SW1, .init_data = &sw1_init }, { .id = MC13892_SW2, .init_data = &sw2_init }, { .id = MC13892_SW3, .init_data = &sw3_init }, { .id = MC13892_SW4, .init_data = &sw4_init }, { .id = MC13892_SWBST, .init_data = &swbst_init }, { .id = MC13892_VIOHI, .init_data = &viohi_init }, { .id = MC13892_VPLL, .init_data = &vpll_init }, { .id = MC13892_VDIG, .init_data = &vdig_init }, { .id = MC13892_VSD, .init_data = &vsd_init }, { .id = MC13892_VUSB2, .init_data = &vusb2_init }, { .id = MC13892_VVIDEO, .init_data = &vvideo_init }, { .id = MC13892_VAUDIO, .init_data = &vaudio_init }, { .id = MC13892_VCAM, .init_data = &vcam_init }, { .id = MC13892_VGEN1, .init_data = &vgen1_init }, { .id = MC13892_VGEN2, .init_data = &vgen2_init }, { .id = MC13892_VGEN3, .init_data = &vgen3_init }, { .id = MC13892_VUSB, .init_data = &vusb_init }, { .id = MC13892_GPO1, .init_data = &gpo1_init }, { .id = MC13892_GPO2, .init_data = &gpo2_init }, { .id = MC13892_GPO3, .init_data = &gpo3_init }, { .id = MC13892_GPO4, .init_data = &gpo4_init }, { .id = MC13892_PWGT1SPI, .init_data = &pwgt1_init }, { .id = MC13892_PWGT2SPI, .init_data = &pwgt2_init }, { .id = MC13892_VCOINCELL, .init_data = &vcoincell_init }, }; static struct mc13xxx_platform_data mx51_efika_mc13892_data = { .flags = MC13XXX_USE_RTC, .regulators = { .num_regulators = ARRAY_SIZE(mx51_efika_regulators), .regulators = mx51_efika_regulators, }, }; static struct spi_board_info mx51_efika_spi_board_info[] __initdata = { { .modalias = "m25p80", .max_speed_hz = 25000000, .bus_num = 0, .chip_select = 1, .platform_data = &mx51_efika_spi_flash_data, .irq = -1, }, { .modalias = "mc13892", .max_speed_hz = 1000000, .bus_num = 0, .chip_select = 0, .platform_data = &mx51_efika_mc13892_data, .irq = IMX_GPIO_TO_IRQ(EFIKAMX_PMIC), }, }; static int mx51_efika_spi_cs[] = { EFIKAMX_SPI_CS0, EFIKAMX_SPI_CS1, }; static const struct spi_imx_master mx51_efika_spi_pdata __initconst = { .chipselect = mx51_efika_spi_cs, .num_chipselect = ARRAY_SIZE(mx51_efika_spi_cs), }; void __init efika_board_common_init(void) { mxc_iomux_v3_setup_multiple_pads(mx51efika_pads, ARRAY_SIZE(mx51efika_pads)); imx51_add_imx_uart(0, &uart_pdata); mx51_efika_usb(); /* FIXME: comes from original code. check this. */ if (mx51_revision() < IMX_CHIP_REVISION_2_0) sw2_init.constraints.state_mem.uV = 1100000; else if (mx51_revision() == IMX_CHIP_REVISION_2_0) { sw2_init.constraints.state_mem.uV = 1250000; sw1_init.constraints.state_mem.uV = 1000000; } if (machine_is_mx51_efikasb()) vgen1_init.constraints.max_uV = 1200000; gpio_request(EFIKAMX_PMIC, "pmic irq"); gpio_direction_input(EFIKAMX_PMIC); spi_register_board_info(mx51_efika_spi_board_info, ARRAY_SIZE(mx51_efika_spi_board_info)); imx51_add_ecspi(0, &mx51_efika_spi_pdata); imx51_add_pata_imx(); #if defined(CONFIG_CPU_FREQ_IMX) get_cpu_op = mx51_get_cpu_op; #endif }
gpl-3.0
WisniaPL/LeEco-Le1S-Kernel
fs/afs/vnode.c
13744
24687
/* AFS vnode management * * Copyright (C) 2002, 2007 Red Hat, Inc. All Rights Reserved. * Written by David Howells (dhowells@redhat.com) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/init.h> #include <linux/fs.h> #include <linux/sched.h> #include "internal.h" #if 0 static noinline bool dump_tree_aux(struct rb_node *node, struct rb_node *parent, int depth, char lr) { struct afs_vnode *vnode; bool bad = false; if (!node) return false; if (node->rb_left) bad = dump_tree_aux(node->rb_left, node, depth + 2, '/'); vnode = rb_entry(node, struct afs_vnode, cb_promise); _debug("%c %*.*s%c%p {%d}", rb_is_red(node) ? 'R' : 'B', depth, depth, "", lr, vnode, vnode->cb_expires_at); if (rb_parent(node) != parent) { printk("BAD: %p != %p\n", rb_parent(node), parent); bad = true; } if (node->rb_right) bad |= dump_tree_aux(node->rb_right, node, depth + 2, '\\'); return bad; } static noinline void dump_tree(const char *name, struct afs_server *server) { _enter("%s", name); if (dump_tree_aux(server->cb_promises.rb_node, NULL, 0, '-')) BUG(); } #endif /* * insert a vnode into the backing server's vnode tree */ static void afs_install_vnode(struct afs_vnode *vnode, struct afs_server *server) { struct afs_server *old_server = vnode->server; struct afs_vnode *xvnode; struct rb_node *parent, **p; _enter("%p,%p", vnode, server); if (old_server) { spin_lock(&old_server->fs_lock); rb_erase(&vnode->server_rb, &old_server->fs_vnodes); spin_unlock(&old_server->fs_lock); } afs_get_server(server); vnode->server = server; afs_put_server(old_server); /* insert into the server's vnode tree in FID order */ spin_lock(&server->fs_lock); parent = NULL; p = &server->fs_vnodes.rb_node; while (*p) { parent = *p; xvnode = rb_entry(parent, struct afs_vnode, server_rb); if (vnode->fid.vid < xvnode->fid.vid) p = &(*p)->rb_left; else if (vnode->fid.vid > xvnode->fid.vid) p = &(*p)->rb_right; else if (vnode->fid.vnode < xvnode->fid.vnode) p = &(*p)->rb_left; else if (vnode->fid.vnode > xvnode->fid.vnode) p = &(*p)->rb_right; else if (vnode->fid.unique < xvnode->fid.unique) p = &(*p)->rb_left; else if (vnode->fid.unique > xvnode->fid.unique) p = &(*p)->rb_right; else BUG(); /* can't happen unless afs_iget() malfunctions */ } rb_link_node(&vnode->server_rb, parent, p); rb_insert_color(&vnode->server_rb, &server->fs_vnodes); spin_unlock(&server->fs_lock); _leave(""); } /* * insert a vnode into the promising server's update/expiration tree * - caller must hold vnode->lock */ static void afs_vnode_note_promise(struct afs_vnode *vnode, struct afs_server *server) { struct afs_server *old_server; struct afs_vnode *xvnode; struct rb_node *parent, **p; _enter("%p,%p", vnode, server); ASSERT(server != NULL); old_server = vnode->server; if (vnode->cb_promised) { if (server == old_server && vnode->cb_expires == vnode->cb_expires_at) { _leave(" [no change]"); return; } spin_lock(&old_server->cb_lock); if (vnode->cb_promised) { _debug("delete"); rb_erase(&vnode->cb_promise, &old_server->cb_promises); vnode->cb_promised = false; } spin_unlock(&old_server->cb_lock); } if (vnode->server != server) afs_install_vnode(vnode, server); vnode->cb_expires_at = vnode->cb_expires; _debug("PROMISE on %p {%lu}", vnode, (unsigned long) vnode->cb_expires_at); /* abuse an RB-tree to hold the expiration order (we may have multiple * items with the same expiration time) */ spin_lock(&server->cb_lock); parent = NULL; p = &server->cb_promises.rb_node; while (*p) { parent = *p; xvnode = rb_entry(parent, struct afs_vnode, cb_promise); if (vnode->cb_expires_at < xvnode->cb_expires_at) p = &(*p)->rb_left; else p = &(*p)->rb_right; } rb_link_node(&vnode->cb_promise, parent, p); rb_insert_color(&vnode->cb_promise, &server->cb_promises); vnode->cb_promised = true; spin_unlock(&server->cb_lock); _leave(""); } /* * handle remote file deletion by discarding the callback promise */ static void afs_vnode_deleted_remotely(struct afs_vnode *vnode) { struct afs_server *server; _enter("{%p}", vnode->server); set_bit(AFS_VNODE_DELETED, &vnode->flags); server = vnode->server; if (server) { if (vnode->cb_promised) { spin_lock(&server->cb_lock); if (vnode->cb_promised) { rb_erase(&vnode->cb_promise, &server->cb_promises); vnode->cb_promised = false; } spin_unlock(&server->cb_lock); } spin_lock(&server->fs_lock); rb_erase(&vnode->server_rb, &server->fs_vnodes); spin_unlock(&server->fs_lock); vnode->server = NULL; afs_put_server(server); } else { ASSERT(!vnode->cb_promised); } _leave(""); } /* * finish off updating the recorded status of a file after a successful * operation completion * - starts callback expiry timer * - adds to server's callback list */ void afs_vnode_finalise_status_update(struct afs_vnode *vnode, struct afs_server *server) { struct afs_server *oldserver = NULL; _enter("%p,%p", vnode, server); spin_lock(&vnode->lock); clear_bit(AFS_VNODE_CB_BROKEN, &vnode->flags); afs_vnode_note_promise(vnode, server); vnode->update_cnt--; ASSERTCMP(vnode->update_cnt, >=, 0); spin_unlock(&vnode->lock); wake_up_all(&vnode->update_waitq); afs_put_server(oldserver); _leave(""); } /* * finish off updating the recorded status of a file after an operation failed */ static void afs_vnode_status_update_failed(struct afs_vnode *vnode, int ret) { _enter("{%x:%u},%d", vnode->fid.vid, vnode->fid.vnode, ret); spin_lock(&vnode->lock); clear_bit(AFS_VNODE_CB_BROKEN, &vnode->flags); if (ret == -ENOENT) { /* the file was deleted on the server */ _debug("got NOENT from server - marking file deleted"); afs_vnode_deleted_remotely(vnode); } vnode->update_cnt--; ASSERTCMP(vnode->update_cnt, >=, 0); spin_unlock(&vnode->lock); wake_up_all(&vnode->update_waitq); _leave(""); } /* * fetch file status from the volume * - don't issue a fetch if: * - the changed bit is not set and there's a valid callback * - there are any outstanding ops that will fetch the status * - TODO implement local caching */ int afs_vnode_fetch_status(struct afs_vnode *vnode, struct afs_vnode *auth_vnode, struct key *key) { struct afs_server *server; unsigned long acl_order; int ret; DECLARE_WAITQUEUE(myself, current); _enter("%s,{%x:%u.%u}", vnode->volume->vlocation->vldb.name, vnode->fid.vid, vnode->fid.vnode, vnode->fid.unique); if (!test_bit(AFS_VNODE_CB_BROKEN, &vnode->flags) && vnode->cb_promised) { _leave(" [unchanged]"); return 0; } if (test_bit(AFS_VNODE_DELETED, &vnode->flags)) { _leave(" [deleted]"); return -ENOENT; } acl_order = 0; if (auth_vnode) acl_order = auth_vnode->acl_order; spin_lock(&vnode->lock); if (!test_bit(AFS_VNODE_CB_BROKEN, &vnode->flags) && vnode->cb_promised) { spin_unlock(&vnode->lock); _leave(" [unchanged]"); return 0; } ASSERTCMP(vnode->update_cnt, >=, 0); if (vnode->update_cnt > 0) { /* someone else started a fetch */ _debug("wait on fetch %d", vnode->update_cnt); set_current_state(TASK_UNINTERRUPTIBLE); ASSERT(myself.func != NULL); add_wait_queue(&vnode->update_waitq, &myself); /* wait for the status to be updated */ for (;;) { if (!test_bit(AFS_VNODE_CB_BROKEN, &vnode->flags)) break; if (test_bit(AFS_VNODE_DELETED, &vnode->flags)) break; /* check to see if it got updated and invalidated all * before we saw it */ if (vnode->update_cnt == 0) { remove_wait_queue(&vnode->update_waitq, &myself); set_current_state(TASK_RUNNING); goto get_anyway; } spin_unlock(&vnode->lock); schedule(); set_current_state(TASK_UNINTERRUPTIBLE); spin_lock(&vnode->lock); } remove_wait_queue(&vnode->update_waitq, &myself); spin_unlock(&vnode->lock); set_current_state(TASK_RUNNING); return test_bit(AFS_VNODE_DELETED, &vnode->flags) ? -ENOENT : 0; } get_anyway: /* okay... we're going to have to initiate the op */ vnode->update_cnt++; spin_unlock(&vnode->lock); /* merge AFS status fetches and clear outstanding callback on this * vnode */ do { /* pick a server to query */ server = afs_volume_pick_fileserver(vnode); if (IS_ERR(server)) goto no_server; _debug("USING SERVER: %p{%08x}", server, ntohl(server->addr.s_addr)); ret = afs_fs_fetch_file_status(server, key, vnode, NULL, &afs_sync_call); } while (!afs_volume_release_fileserver(vnode, server, ret)); /* adjust the flags */ if (ret == 0) { _debug("adjust"); if (auth_vnode) afs_cache_permit(vnode, key, acl_order); afs_vnode_finalise_status_update(vnode, server); afs_put_server(server); } else { _debug("failed [%d]", ret); afs_vnode_status_update_failed(vnode, ret); } ASSERTCMP(vnode->update_cnt, >=, 0); _leave(" = %d [cnt %d]", ret, vnode->update_cnt); return ret; no_server: spin_lock(&vnode->lock); vnode->update_cnt--; ASSERTCMP(vnode->update_cnt, >=, 0); spin_unlock(&vnode->lock); _leave(" = %ld [cnt %d]", PTR_ERR(server), vnode->update_cnt); return PTR_ERR(server); } /* * fetch file data from the volume * - TODO implement caching */ int afs_vnode_fetch_data(struct afs_vnode *vnode, struct key *key, off_t offset, size_t length, struct page *page) { struct afs_server *server; int ret; _enter("%s{%x:%u.%u},%x,,,", vnode->volume->vlocation->vldb.name, vnode->fid.vid, vnode->fid.vnode, vnode->fid.unique, key_serial(key)); /* this op will fetch the status */ spin_lock(&vnode->lock); vnode->update_cnt++; spin_unlock(&vnode->lock); /* merge in AFS status fetches and clear outstanding callback on this * vnode */ do { /* pick a server to query */ server = afs_volume_pick_fileserver(vnode); if (IS_ERR(server)) goto no_server; _debug("USING SERVER: %08x\n", ntohl(server->addr.s_addr)); ret = afs_fs_fetch_data(server, key, vnode, offset, length, page, &afs_sync_call); } while (!afs_volume_release_fileserver(vnode, server, ret)); /* adjust the flags */ if (ret == 0) { afs_vnode_finalise_status_update(vnode, server); afs_put_server(server); } else { afs_vnode_status_update_failed(vnode, ret); } _leave(" = %d", ret); return ret; no_server: spin_lock(&vnode->lock); vnode->update_cnt--; ASSERTCMP(vnode->update_cnt, >=, 0); spin_unlock(&vnode->lock); return PTR_ERR(server); } /* * make a file or a directory */ int afs_vnode_create(struct afs_vnode *vnode, struct key *key, const char *name, umode_t mode, struct afs_fid *newfid, struct afs_file_status *newstatus, struct afs_callback *newcb, struct afs_server **_server) { struct afs_server *server; int ret; _enter("%s{%x:%u.%u},%x,%s,,", vnode->volume->vlocation->vldb.name, vnode->fid.vid, vnode->fid.vnode, vnode->fid.unique, key_serial(key), name); /* this op will fetch the status on the directory we're creating in */ spin_lock(&vnode->lock); vnode->update_cnt++; spin_unlock(&vnode->lock); do { /* pick a server to query */ server = afs_volume_pick_fileserver(vnode); if (IS_ERR(server)) goto no_server; _debug("USING SERVER: %08x\n", ntohl(server->addr.s_addr)); ret = afs_fs_create(server, key, vnode, name, mode, newfid, newstatus, newcb, &afs_sync_call); } while (!afs_volume_release_fileserver(vnode, server, ret)); /* adjust the flags */ if (ret == 0) { afs_vnode_finalise_status_update(vnode, server); *_server = server; } else { afs_vnode_status_update_failed(vnode, ret); *_server = NULL; } _leave(" = %d [cnt %d]", ret, vnode->update_cnt); return ret; no_server: spin_lock(&vnode->lock); vnode->update_cnt--; ASSERTCMP(vnode->update_cnt, >=, 0); spin_unlock(&vnode->lock); _leave(" = %ld [cnt %d]", PTR_ERR(server), vnode->update_cnt); return PTR_ERR(server); } /* * remove a file or directory */ int afs_vnode_remove(struct afs_vnode *vnode, struct key *key, const char *name, bool isdir) { struct afs_server *server; int ret; _enter("%s{%x:%u.%u},%x,%s", vnode->volume->vlocation->vldb.name, vnode->fid.vid, vnode->fid.vnode, vnode->fid.unique, key_serial(key), name); /* this op will fetch the status on the directory we're removing from */ spin_lock(&vnode->lock); vnode->update_cnt++; spin_unlock(&vnode->lock); do { /* pick a server to query */ server = afs_volume_pick_fileserver(vnode); if (IS_ERR(server)) goto no_server; _debug("USING SERVER: %08x\n", ntohl(server->addr.s_addr)); ret = afs_fs_remove(server, key, vnode, name, isdir, &afs_sync_call); } while (!afs_volume_release_fileserver(vnode, server, ret)); /* adjust the flags */ if (ret == 0) { afs_vnode_finalise_status_update(vnode, server); afs_put_server(server); } else { afs_vnode_status_update_failed(vnode, ret); } _leave(" = %d [cnt %d]", ret, vnode->update_cnt); return ret; no_server: spin_lock(&vnode->lock); vnode->update_cnt--; ASSERTCMP(vnode->update_cnt, >=, 0); spin_unlock(&vnode->lock); _leave(" = %ld [cnt %d]", PTR_ERR(server), vnode->update_cnt); return PTR_ERR(server); } /* * create a hard link */ int afs_vnode_link(struct afs_vnode *dvnode, struct afs_vnode *vnode, struct key *key, const char *name) { struct afs_server *server; int ret; _enter("%s{%x:%u.%u},%s{%x:%u.%u},%x,%s", dvnode->volume->vlocation->vldb.name, dvnode->fid.vid, dvnode->fid.vnode, dvnode->fid.unique, vnode->volume->vlocation->vldb.name, vnode->fid.vid, vnode->fid.vnode, vnode->fid.unique, key_serial(key), name); /* this op will fetch the status on the directory we're removing from */ spin_lock(&vnode->lock); vnode->update_cnt++; spin_unlock(&vnode->lock); spin_lock(&dvnode->lock); dvnode->update_cnt++; spin_unlock(&dvnode->lock); do { /* pick a server to query */ server = afs_volume_pick_fileserver(dvnode); if (IS_ERR(server)) goto no_server; _debug("USING SERVER: %08x\n", ntohl(server->addr.s_addr)); ret = afs_fs_link(server, key, dvnode, vnode, name, &afs_sync_call); } while (!afs_volume_release_fileserver(dvnode, server, ret)); /* adjust the flags */ if (ret == 0) { afs_vnode_finalise_status_update(vnode, server); afs_vnode_finalise_status_update(dvnode, server); afs_put_server(server); } else { afs_vnode_status_update_failed(vnode, ret); afs_vnode_status_update_failed(dvnode, ret); } _leave(" = %d [cnt %d]", ret, vnode->update_cnt); return ret; no_server: spin_lock(&vnode->lock); vnode->update_cnt--; ASSERTCMP(vnode->update_cnt, >=, 0); spin_unlock(&vnode->lock); spin_lock(&dvnode->lock); dvnode->update_cnt--; ASSERTCMP(dvnode->update_cnt, >=, 0); spin_unlock(&dvnode->lock); _leave(" = %ld [cnt %d]", PTR_ERR(server), vnode->update_cnt); return PTR_ERR(server); } /* * create a symbolic link */ int afs_vnode_symlink(struct afs_vnode *vnode, struct key *key, const char *name, const char *content, struct afs_fid *newfid, struct afs_file_status *newstatus, struct afs_server **_server) { struct afs_server *server; int ret; _enter("%s{%x:%u.%u},%x,%s,%s,,,", vnode->volume->vlocation->vldb.name, vnode->fid.vid, vnode->fid.vnode, vnode->fid.unique, key_serial(key), name, content); /* this op will fetch the status on the directory we're creating in */ spin_lock(&vnode->lock); vnode->update_cnt++; spin_unlock(&vnode->lock); do { /* pick a server to query */ server = afs_volume_pick_fileserver(vnode); if (IS_ERR(server)) goto no_server; _debug("USING SERVER: %08x\n", ntohl(server->addr.s_addr)); ret = afs_fs_symlink(server, key, vnode, name, content, newfid, newstatus, &afs_sync_call); } while (!afs_volume_release_fileserver(vnode, server, ret)); /* adjust the flags */ if (ret == 0) { afs_vnode_finalise_status_update(vnode, server); *_server = server; } else { afs_vnode_status_update_failed(vnode, ret); *_server = NULL; } _leave(" = %d [cnt %d]", ret, vnode->update_cnt); return ret; no_server: spin_lock(&vnode->lock); vnode->update_cnt--; ASSERTCMP(vnode->update_cnt, >=, 0); spin_unlock(&vnode->lock); _leave(" = %ld [cnt %d]", PTR_ERR(server), vnode->update_cnt); return PTR_ERR(server); } /* * rename a file */ int afs_vnode_rename(struct afs_vnode *orig_dvnode, struct afs_vnode *new_dvnode, struct key *key, const char *orig_name, const char *new_name) { struct afs_server *server; int ret; _enter("%s{%x:%u.%u},%s{%u,%u,%u},%x,%s,%s", orig_dvnode->volume->vlocation->vldb.name, orig_dvnode->fid.vid, orig_dvnode->fid.vnode, orig_dvnode->fid.unique, new_dvnode->volume->vlocation->vldb.name, new_dvnode->fid.vid, new_dvnode->fid.vnode, new_dvnode->fid.unique, key_serial(key), orig_name, new_name); /* this op will fetch the status on both the directories we're dealing * with */ spin_lock(&orig_dvnode->lock); orig_dvnode->update_cnt++; spin_unlock(&orig_dvnode->lock); if (new_dvnode != orig_dvnode) { spin_lock(&new_dvnode->lock); new_dvnode->update_cnt++; spin_unlock(&new_dvnode->lock); } do { /* pick a server to query */ server = afs_volume_pick_fileserver(orig_dvnode); if (IS_ERR(server)) goto no_server; _debug("USING SERVER: %08x\n", ntohl(server->addr.s_addr)); ret = afs_fs_rename(server, key, orig_dvnode, orig_name, new_dvnode, new_name, &afs_sync_call); } while (!afs_volume_release_fileserver(orig_dvnode, server, ret)); /* adjust the flags */ if (ret == 0) { afs_vnode_finalise_status_update(orig_dvnode, server); if (new_dvnode != orig_dvnode) afs_vnode_finalise_status_update(new_dvnode, server); afs_put_server(server); } else { afs_vnode_status_update_failed(orig_dvnode, ret); if (new_dvnode != orig_dvnode) afs_vnode_status_update_failed(new_dvnode, ret); } _leave(" = %d [cnt %d]", ret, orig_dvnode->update_cnt); return ret; no_server: spin_lock(&orig_dvnode->lock); orig_dvnode->update_cnt--; ASSERTCMP(orig_dvnode->update_cnt, >=, 0); spin_unlock(&orig_dvnode->lock); if (new_dvnode != orig_dvnode) { spin_lock(&new_dvnode->lock); new_dvnode->update_cnt--; ASSERTCMP(new_dvnode->update_cnt, >=, 0); spin_unlock(&new_dvnode->lock); } _leave(" = %ld [cnt %d]", PTR_ERR(server), orig_dvnode->update_cnt); return PTR_ERR(server); } /* * write to a file */ int afs_vnode_store_data(struct afs_writeback *wb, pgoff_t first, pgoff_t last, unsigned offset, unsigned to) { struct afs_server *server; struct afs_vnode *vnode = wb->vnode; int ret; _enter("%s{%x:%u.%u},%x,%lx,%lx,%x,%x", vnode->volume->vlocation->vldb.name, vnode->fid.vid, vnode->fid.vnode, vnode->fid.unique, key_serial(wb->key), first, last, offset, to); /* this op will fetch the status */ spin_lock(&vnode->lock); vnode->update_cnt++; spin_unlock(&vnode->lock); do { /* pick a server to query */ server = afs_volume_pick_fileserver(vnode); if (IS_ERR(server)) goto no_server; _debug("USING SERVER: %08x\n", ntohl(server->addr.s_addr)); ret = afs_fs_store_data(server, wb, first, last, offset, to, &afs_sync_call); } while (!afs_volume_release_fileserver(vnode, server, ret)); /* adjust the flags */ if (ret == 0) { afs_vnode_finalise_status_update(vnode, server); afs_put_server(server); } else { afs_vnode_status_update_failed(vnode, ret); } _leave(" = %d", ret); return ret; no_server: spin_lock(&vnode->lock); vnode->update_cnt--; ASSERTCMP(vnode->update_cnt, >=, 0); spin_unlock(&vnode->lock); return PTR_ERR(server); } /* * set the attributes on a file */ int afs_vnode_setattr(struct afs_vnode *vnode, struct key *key, struct iattr *attr) { struct afs_server *server; int ret; _enter("%s{%x:%u.%u},%x", vnode->volume->vlocation->vldb.name, vnode->fid.vid, vnode->fid.vnode, vnode->fid.unique, key_serial(key)); /* this op will fetch the status */ spin_lock(&vnode->lock); vnode->update_cnt++; spin_unlock(&vnode->lock); do { /* pick a server to query */ server = afs_volume_pick_fileserver(vnode); if (IS_ERR(server)) goto no_server; _debug("USING SERVER: %08x\n", ntohl(server->addr.s_addr)); ret = afs_fs_setattr(server, key, vnode, attr, &afs_sync_call); } while (!afs_volume_release_fileserver(vnode, server, ret)); /* adjust the flags */ if (ret == 0) { afs_vnode_finalise_status_update(vnode, server); afs_put_server(server); } else { afs_vnode_status_update_failed(vnode, ret); } _leave(" = %d", ret); return ret; no_server: spin_lock(&vnode->lock); vnode->update_cnt--; ASSERTCMP(vnode->update_cnt, >=, 0); spin_unlock(&vnode->lock); return PTR_ERR(server); } /* * get the status of a volume */ int afs_vnode_get_volume_status(struct afs_vnode *vnode, struct key *key, struct afs_volume_status *vs) { struct afs_server *server; int ret; _enter("%s{%x:%u.%u},%x,", vnode->volume->vlocation->vldb.name, vnode->fid.vid, vnode->fid.vnode, vnode->fid.unique, key_serial(key)); do { /* pick a server to query */ server = afs_volume_pick_fileserver(vnode); if (IS_ERR(server)) goto no_server; _debug("USING SERVER: %08x\n", ntohl(server->addr.s_addr)); ret = afs_fs_get_volume_status(server, key, vnode, vs, &afs_sync_call); } while (!afs_volume_release_fileserver(vnode, server, ret)); /* adjust the flags */ if (ret == 0) afs_put_server(server); _leave(" = %d", ret); return ret; no_server: return PTR_ERR(server); } /* * get a lock on a file */ int afs_vnode_set_lock(struct afs_vnode *vnode, struct key *key, afs_lock_type_t type) { struct afs_server *server; int ret; _enter("%s{%x:%u.%u},%x,%u", vnode->volume->vlocation->vldb.name, vnode->fid.vid, vnode->fid.vnode, vnode->fid.unique, key_serial(key), type); do { /* pick a server to query */ server = afs_volume_pick_fileserver(vnode); if (IS_ERR(server)) goto no_server; _debug("USING SERVER: %08x\n", ntohl(server->addr.s_addr)); ret = afs_fs_set_lock(server, key, vnode, type, &afs_sync_call); } while (!afs_volume_release_fileserver(vnode, server, ret)); /* adjust the flags */ if (ret == 0) afs_put_server(server); _leave(" = %d", ret); return ret; no_server: return PTR_ERR(server); } /* * extend a lock on a file */ int afs_vnode_extend_lock(struct afs_vnode *vnode, struct key *key) { struct afs_server *server; int ret; _enter("%s{%x:%u.%u},%x", vnode->volume->vlocation->vldb.name, vnode->fid.vid, vnode->fid.vnode, vnode->fid.unique, key_serial(key)); do { /* pick a server to query */ server = afs_volume_pick_fileserver(vnode); if (IS_ERR(server)) goto no_server; _debug("USING SERVER: %08x\n", ntohl(server->addr.s_addr)); ret = afs_fs_extend_lock(server, key, vnode, &afs_sync_call); } while (!afs_volume_release_fileserver(vnode, server, ret)); /* adjust the flags */ if (ret == 0) afs_put_server(server); _leave(" = %d", ret); return ret; no_server: return PTR_ERR(server); } /* * release a lock on a file */ int afs_vnode_release_lock(struct afs_vnode *vnode, struct key *key) { struct afs_server *server; int ret; _enter("%s{%x:%u.%u},%x", vnode->volume->vlocation->vldb.name, vnode->fid.vid, vnode->fid.vnode, vnode->fid.unique, key_serial(key)); do { /* pick a server to query */ server = afs_volume_pick_fileserver(vnode); if (IS_ERR(server)) goto no_server; _debug("USING SERVER: %08x\n", ntohl(server->addr.s_addr)); ret = afs_fs_release_lock(server, key, vnode, &afs_sync_call); } while (!afs_volume_release_fileserver(vnode, server, ret)); /* adjust the flags */ if (ret == 0) afs_put_server(server); _leave(" = %d", ret); return ret; no_server: return PTR_ERR(server); }
gpl-3.0
k0nane/R915_kernel_GB
Kernel/arch/arm/plat-samsung/dev-i2c1.c
199
2323
/* linux/arch/arm/plat-s3c/dev-i2c1.c * * Copyright 2008-2009 Simtec Electronics * Ben Dooks <ben@simtec.co.uk> * http://armlinux.simtec.co.uk/ * * S3C series device definition for i2c device 1 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/gfp.h> #include <linux/kernel.h> #include <linux/string.h> #include <linux/platform_device.h> #include <linux/clk.h> #include <linux/err.h> #include <mach/irqs.h> #include <mach/map.h> #include <plat/regs-iic.h> #include <plat/iic.h> #include <plat/devs.h> #include <plat/cpu.h> #include <asm/io.h> static struct resource s3c_i2c_resource[] = { [0] = { .start = S3C_PA_IIC1, .end = S3C_PA_IIC1 + SZ_4K - 1, .flags = IORESOURCE_MEM, }, [1] = { .start = IRQ_IIC1, .end = IRQ_IIC1, .flags = IORESOURCE_IRQ, }, }; struct platform_device s3c_device_i2c1 = { .name = "s3c2410-i2c", .id = 1, .num_resources = ARRAY_SIZE(s3c_i2c_resource), .resource = s3c_i2c_resource, }; static struct s3c2410_platform_i2c default_i2c_data1 __initdata = { .flags = 0, .bus_num = 1, .slave_addr = 0x10, .frequency = 400*1000, .sda_delay = S3C2410_IICLC_SDA_DELAY5 | S3C2410_IICLC_FILTER_ON, }; void __init s3c_i2c1_set_platdata(struct s3c2410_platform_i2c *pd) { struct s3c2410_platform_i2c *npd; if (!pd) pd = &default_i2c_data1; npd = kmemdup(pd, sizeof(struct s3c2410_platform_i2c), GFP_KERNEL); if (!npd) printk(KERN_ERR "%s: no memory for platform data\n", __func__); else if (!npd->cfg_gpio) npd->cfg_gpio = s3c_i2c1_cfg_gpio; s3c_device_i2c1.dev.platform_data = npd; } void s3c_i2c1_force_stop() { struct resource *ioarea; void __iomem *regs; struct clk *clk; unsigned long iicstat; regs = ioremap(S3C_PA_IIC1, SZ_4K); if(regs == NULL) { printk(KERN_ERR "%s, cannot request IO\n", __func__); return; } clk = clk_get(&s3c_device_i2c1.dev, "i2c"); if(clk == NULL || IS_ERR(clk)) { printk(KERN_ERR "%s, cannot get cloock\n", __func__); return; } clk_enable(clk); iicstat = readl(regs + S3C2410_IICSTAT); writel(iicstat & ~S3C2410_IICSTAT_TXRXEN, regs + S3C2410_IICSTAT); clk_disable(clk); iounmap(regs); } EXPORT_SYMBOL(s3c_i2c1_force_stop);
gpl-3.0
CertifiedBlyndGuy/ewok-onyx
drivers/md/dm-thin-metadata.c
4808
32017
/* * Copyright (C) 2011 Red Hat, Inc. * * This file is released under the GPL. */ #include "dm-thin-metadata.h" #include "persistent-data/dm-btree.h" #include "persistent-data/dm-space-map.h" #include "persistent-data/dm-space-map-disk.h" #include "persistent-data/dm-transaction-manager.h" #include <linux/list.h> #include <linux/device-mapper.h> #include <linux/workqueue.h> /*-------------------------------------------------------------------------- * As far as the metadata goes, there is: * * - A superblock in block zero, taking up fewer than 512 bytes for * atomic writes. * * - A space map managing the metadata blocks. * * - A space map managing the data blocks. * * - A btree mapping our internal thin dev ids onto struct disk_device_details. * * - A hierarchical btree, with 2 levels which effectively maps (thin * dev id, virtual block) -> block_time. Block time is a 64-bit * field holding the time in the low 24 bits, and block in the top 48 * bits. * * BTrees consist solely of btree_nodes, that fill a block. Some are * internal nodes, as such their values are a __le64 pointing to other * nodes. Leaf nodes can store data of any reasonable size (ie. much * smaller than the block size). The nodes consist of the header, * followed by an array of keys, followed by an array of values. We have * to binary search on the keys so they're all held together to help the * cpu cache. * * Space maps have 2 btrees: * * - One maps a uint64_t onto a struct index_entry. Which points to a * bitmap block, and has some details about how many free entries there * are etc. * * - The bitmap blocks have a header (for the checksum). Then the rest * of the block is pairs of bits. With the meaning being: * * 0 - ref count is 0 * 1 - ref count is 1 * 2 - ref count is 2 * 3 - ref count is higher than 2 * * - If the count is higher than 2 then the ref count is entered in a * second btree that directly maps the block_address to a uint32_t ref * count. * * The space map metadata variant doesn't have a bitmaps btree. Instead * it has one single blocks worth of index_entries. This avoids * recursive issues with the bitmap btree needing to allocate space in * order to insert. With a small data block size such as 64k the * metadata support data devices that are hundreds of terrabytes. * * The space maps allocate space linearly from front to back. Space that * is freed in a transaction is never recycled within that transaction. * To try and avoid fragmenting _free_ space the allocator always goes * back and fills in gaps. * * All metadata io is in THIN_METADATA_BLOCK_SIZE sized/aligned chunks * from the block manager. *--------------------------------------------------------------------------*/ #define DM_MSG_PREFIX "thin metadata" #define THIN_SUPERBLOCK_MAGIC 27022010 #define THIN_SUPERBLOCK_LOCATION 0 #define THIN_VERSION 1 #define THIN_METADATA_CACHE_SIZE 64 #define SECTOR_TO_BLOCK_SHIFT 3 /* This should be plenty */ #define SPACE_MAP_ROOT_SIZE 128 /* * Little endian on-disk superblock and device details. */ struct thin_disk_superblock { __le32 csum; /* Checksum of superblock except for this field. */ __le32 flags; __le64 blocknr; /* This block number, dm_block_t. */ __u8 uuid[16]; __le64 magic; __le32 version; __le32 time; __le64 trans_id; /* * Root held by userspace transactions. */ __le64 held_root; __u8 data_space_map_root[SPACE_MAP_ROOT_SIZE]; __u8 metadata_space_map_root[SPACE_MAP_ROOT_SIZE]; /* * 2-level btree mapping (dev_id, (dev block, time)) -> data block */ __le64 data_mapping_root; /* * Device detail root mapping dev_id -> device_details */ __le64 device_details_root; __le32 data_block_size; /* In 512-byte sectors. */ __le32 metadata_block_size; /* In 512-byte sectors. */ __le64 metadata_nr_blocks; __le32 compat_flags; __le32 compat_ro_flags; __le32 incompat_flags; } __packed; struct disk_device_details { __le64 mapped_blocks; __le64 transaction_id; /* When created. */ __le32 creation_time; __le32 snapshotted_time; } __packed; struct dm_pool_metadata { struct hlist_node hash; struct block_device *bdev; struct dm_block_manager *bm; struct dm_space_map *metadata_sm; struct dm_space_map *data_sm; struct dm_transaction_manager *tm; struct dm_transaction_manager *nb_tm; /* * Two-level btree. * First level holds thin_dev_t. * Second level holds mappings. */ struct dm_btree_info info; /* * Non-blocking version of the above. */ struct dm_btree_info nb_info; /* * Just the top level for deleting whole devices. */ struct dm_btree_info tl_info; /* * Just the bottom level for creating new devices. */ struct dm_btree_info bl_info; /* * Describes the device details btree. */ struct dm_btree_info details_info; struct rw_semaphore root_lock; uint32_t time; int need_commit; dm_block_t root; dm_block_t details_root; struct list_head thin_devices; uint64_t trans_id; unsigned long flags; sector_t data_block_size; }; struct dm_thin_device { struct list_head list; struct dm_pool_metadata *pmd; dm_thin_id id; int open_count; int changed; uint64_t mapped_blocks; uint64_t transaction_id; uint32_t creation_time; uint32_t snapshotted_time; }; /*---------------------------------------------------------------- * superblock validator *--------------------------------------------------------------*/ #define SUPERBLOCK_CSUM_XOR 160774 static void sb_prepare_for_write(struct dm_block_validator *v, struct dm_block *b, size_t block_size) { struct thin_disk_superblock *disk_super = dm_block_data(b); disk_super->blocknr = cpu_to_le64(dm_block_location(b)); disk_super->csum = cpu_to_le32(dm_bm_checksum(&disk_super->flags, block_size - sizeof(__le32), SUPERBLOCK_CSUM_XOR)); } static int sb_check(struct dm_block_validator *v, struct dm_block *b, size_t block_size) { struct thin_disk_superblock *disk_super = dm_block_data(b); __le32 csum_le; if (dm_block_location(b) != le64_to_cpu(disk_super->blocknr)) { DMERR("sb_check failed: blocknr %llu: " "wanted %llu", le64_to_cpu(disk_super->blocknr), (unsigned long long)dm_block_location(b)); return -ENOTBLK; } if (le64_to_cpu(disk_super->magic) != THIN_SUPERBLOCK_MAGIC) { DMERR("sb_check failed: magic %llu: " "wanted %llu", le64_to_cpu(disk_super->magic), (unsigned long long)THIN_SUPERBLOCK_MAGIC); return -EILSEQ; } csum_le = cpu_to_le32(dm_bm_checksum(&disk_super->flags, block_size - sizeof(__le32), SUPERBLOCK_CSUM_XOR)); if (csum_le != disk_super->csum) { DMERR("sb_check failed: csum %u: wanted %u", le32_to_cpu(csum_le), le32_to_cpu(disk_super->csum)); return -EILSEQ; } return 0; } static struct dm_block_validator sb_validator = { .name = "superblock", .prepare_for_write = sb_prepare_for_write, .check = sb_check }; /*---------------------------------------------------------------- * Methods for the btree value types *--------------------------------------------------------------*/ static uint64_t pack_block_time(dm_block_t b, uint32_t t) { return (b << 24) | t; } static void unpack_block_time(uint64_t v, dm_block_t *b, uint32_t *t) { *b = v >> 24; *t = v & ((1 << 24) - 1); } static void data_block_inc(void *context, void *value_le) { struct dm_space_map *sm = context; __le64 v_le; uint64_t b; uint32_t t; memcpy(&v_le, value_le, sizeof(v_le)); unpack_block_time(le64_to_cpu(v_le), &b, &t); dm_sm_inc_block(sm, b); } static void data_block_dec(void *context, void *value_le) { struct dm_space_map *sm = context; __le64 v_le; uint64_t b; uint32_t t; memcpy(&v_le, value_le, sizeof(v_le)); unpack_block_time(le64_to_cpu(v_le), &b, &t); dm_sm_dec_block(sm, b); } static int data_block_equal(void *context, void *value1_le, void *value2_le) { __le64 v1_le, v2_le; uint64_t b1, b2; uint32_t t; memcpy(&v1_le, value1_le, sizeof(v1_le)); memcpy(&v2_le, value2_le, sizeof(v2_le)); unpack_block_time(le64_to_cpu(v1_le), &b1, &t); unpack_block_time(le64_to_cpu(v2_le), &b2, &t); return b1 == b2; } static void subtree_inc(void *context, void *value) { struct dm_btree_info *info = context; __le64 root_le; uint64_t root; memcpy(&root_le, value, sizeof(root_le)); root = le64_to_cpu(root_le); dm_tm_inc(info->tm, root); } static void subtree_dec(void *context, void *value) { struct dm_btree_info *info = context; __le64 root_le; uint64_t root; memcpy(&root_le, value, sizeof(root_le)); root = le64_to_cpu(root_le); if (dm_btree_del(info, root)) DMERR("btree delete failed\n"); } static int subtree_equal(void *context, void *value1_le, void *value2_le) { __le64 v1_le, v2_le; memcpy(&v1_le, value1_le, sizeof(v1_le)); memcpy(&v2_le, value2_le, sizeof(v2_le)); return v1_le == v2_le; } /*----------------------------------------------------------------*/ static int superblock_all_zeroes(struct dm_block_manager *bm, int *result) { int r; unsigned i; struct dm_block *b; __le64 *data_le, zero = cpu_to_le64(0); unsigned block_size = dm_bm_block_size(bm) / sizeof(__le64); /* * We can't use a validator here - it may be all zeroes. */ r = dm_bm_read_lock(bm, THIN_SUPERBLOCK_LOCATION, NULL, &b); if (r) return r; data_le = dm_block_data(b); *result = 1; for (i = 0; i < block_size; i++) { if (data_le[i] != zero) { *result = 0; break; } } return dm_bm_unlock(b); } static int init_pmd(struct dm_pool_metadata *pmd, struct dm_block_manager *bm, dm_block_t nr_blocks, int create) { int r; struct dm_space_map *sm, *data_sm; struct dm_transaction_manager *tm; struct dm_block *sblock; if (create) { r = dm_tm_create_with_sm(bm, THIN_SUPERBLOCK_LOCATION, &sb_validator, &tm, &sm, &sblock); if (r < 0) { DMERR("tm_create_with_sm failed"); return r; } data_sm = dm_sm_disk_create(tm, nr_blocks); if (IS_ERR(data_sm)) { DMERR("sm_disk_create failed"); dm_tm_unlock(tm, sblock); r = PTR_ERR(data_sm); goto bad; } } else { struct thin_disk_superblock *disk_super = NULL; size_t space_map_root_offset = offsetof(struct thin_disk_superblock, metadata_space_map_root); r = dm_tm_open_with_sm(bm, THIN_SUPERBLOCK_LOCATION, &sb_validator, space_map_root_offset, SPACE_MAP_ROOT_SIZE, &tm, &sm, &sblock); if (r < 0) { DMERR("tm_open_with_sm failed"); return r; } disk_super = dm_block_data(sblock); data_sm = dm_sm_disk_open(tm, disk_super->data_space_map_root, sizeof(disk_super->data_space_map_root)); if (IS_ERR(data_sm)) { DMERR("sm_disk_open failed"); r = PTR_ERR(data_sm); goto bad; } } r = dm_tm_unlock(tm, sblock); if (r < 0) { DMERR("couldn't unlock superblock"); goto bad_data_sm; } pmd->bm = bm; pmd->metadata_sm = sm; pmd->data_sm = data_sm; pmd->tm = tm; pmd->nb_tm = dm_tm_create_non_blocking_clone(tm); if (!pmd->nb_tm) { DMERR("could not create clone tm"); r = -ENOMEM; goto bad_data_sm; } pmd->info.tm = tm; pmd->info.levels = 2; pmd->info.value_type.context = pmd->data_sm; pmd->info.value_type.size = sizeof(__le64); pmd->info.value_type.inc = data_block_inc; pmd->info.value_type.dec = data_block_dec; pmd->info.value_type.equal = data_block_equal; memcpy(&pmd->nb_info, &pmd->info, sizeof(pmd->nb_info)); pmd->nb_info.tm = pmd->nb_tm; pmd->tl_info.tm = tm; pmd->tl_info.levels = 1; pmd->tl_info.value_type.context = &pmd->info; pmd->tl_info.value_type.size = sizeof(__le64); pmd->tl_info.value_type.inc = subtree_inc; pmd->tl_info.value_type.dec = subtree_dec; pmd->tl_info.value_type.equal = subtree_equal; pmd->bl_info.tm = tm; pmd->bl_info.levels = 1; pmd->bl_info.value_type.context = pmd->data_sm; pmd->bl_info.value_type.size = sizeof(__le64); pmd->bl_info.value_type.inc = data_block_inc; pmd->bl_info.value_type.dec = data_block_dec; pmd->bl_info.value_type.equal = data_block_equal; pmd->details_info.tm = tm; pmd->details_info.levels = 1; pmd->details_info.value_type.context = NULL; pmd->details_info.value_type.size = sizeof(struct disk_device_details); pmd->details_info.value_type.inc = NULL; pmd->details_info.value_type.dec = NULL; pmd->details_info.value_type.equal = NULL; pmd->root = 0; init_rwsem(&pmd->root_lock); pmd->time = 0; pmd->need_commit = 0; pmd->details_root = 0; pmd->trans_id = 0; pmd->flags = 0; INIT_LIST_HEAD(&pmd->thin_devices); return 0; bad_data_sm: dm_sm_destroy(data_sm); bad: dm_tm_destroy(tm); dm_sm_destroy(sm); return r; } static int __begin_transaction(struct dm_pool_metadata *pmd) { int r; u32 features; struct thin_disk_superblock *disk_super; struct dm_block *sblock; /* * __maybe_commit_transaction() resets these */ WARN_ON(pmd->need_commit); /* * We re-read the superblock every time. Shouldn't need to do this * really. */ r = dm_bm_read_lock(pmd->bm, THIN_SUPERBLOCK_LOCATION, &sb_validator, &sblock); if (r) return r; disk_super = dm_block_data(sblock); pmd->time = le32_to_cpu(disk_super->time); pmd->root = le64_to_cpu(disk_super->data_mapping_root); pmd->details_root = le64_to_cpu(disk_super->device_details_root); pmd->trans_id = le64_to_cpu(disk_super->trans_id); pmd->flags = le32_to_cpu(disk_super->flags); pmd->data_block_size = le32_to_cpu(disk_super->data_block_size); features = le32_to_cpu(disk_super->incompat_flags) & ~THIN_FEATURE_INCOMPAT_SUPP; if (features) { DMERR("could not access metadata due to " "unsupported optional features (%lx).", (unsigned long)features); r = -EINVAL; goto out; } /* * Check for read-only metadata to skip the following RDWR checks. */ if (get_disk_ro(pmd->bdev->bd_disk)) goto out; features = le32_to_cpu(disk_super->compat_ro_flags) & ~THIN_FEATURE_COMPAT_RO_SUPP; if (features) { DMERR("could not access metadata RDWR due to " "unsupported optional features (%lx).", (unsigned long)features); r = -EINVAL; } out: dm_bm_unlock(sblock); return r; } static int __write_changed_details(struct dm_pool_metadata *pmd) { int r; struct dm_thin_device *td, *tmp; struct disk_device_details details; uint64_t key; list_for_each_entry_safe(td, tmp, &pmd->thin_devices, list) { if (!td->changed) continue; key = td->id; details.mapped_blocks = cpu_to_le64(td->mapped_blocks); details.transaction_id = cpu_to_le64(td->transaction_id); details.creation_time = cpu_to_le32(td->creation_time); details.snapshotted_time = cpu_to_le32(td->snapshotted_time); __dm_bless_for_disk(&details); r = dm_btree_insert(&pmd->details_info, pmd->details_root, &key, &details, &pmd->details_root); if (r) return r; if (td->open_count) td->changed = 0; else { list_del(&td->list); kfree(td); } pmd->need_commit = 1; } return 0; } static int __commit_transaction(struct dm_pool_metadata *pmd) { /* * FIXME: Associated pool should be made read-only on failure. */ int r; size_t metadata_len, data_len; struct thin_disk_superblock *disk_super; struct dm_block *sblock; /* * We need to know if the thin_disk_superblock exceeds a 512-byte sector. */ BUILD_BUG_ON(sizeof(struct thin_disk_superblock) > 512); r = __write_changed_details(pmd); if (r < 0) goto out; if (!pmd->need_commit) goto out; r = dm_sm_commit(pmd->data_sm); if (r < 0) goto out; r = dm_tm_pre_commit(pmd->tm); if (r < 0) goto out; r = dm_sm_root_size(pmd->metadata_sm, &metadata_len); if (r < 0) goto out; r = dm_sm_root_size(pmd->data_sm, &data_len); if (r < 0) goto out; r = dm_bm_write_lock(pmd->bm, THIN_SUPERBLOCK_LOCATION, &sb_validator, &sblock); if (r) goto out; disk_super = dm_block_data(sblock); disk_super->time = cpu_to_le32(pmd->time); disk_super->data_mapping_root = cpu_to_le64(pmd->root); disk_super->device_details_root = cpu_to_le64(pmd->details_root); disk_super->trans_id = cpu_to_le64(pmd->trans_id); disk_super->flags = cpu_to_le32(pmd->flags); r = dm_sm_copy_root(pmd->metadata_sm, &disk_super->metadata_space_map_root, metadata_len); if (r < 0) goto out_locked; r = dm_sm_copy_root(pmd->data_sm, &disk_super->data_space_map_root, data_len); if (r < 0) goto out_locked; r = dm_tm_commit(pmd->tm, sblock); if (!r) pmd->need_commit = 0; out: return r; out_locked: dm_bm_unlock(sblock); return r; } struct dm_pool_metadata *dm_pool_metadata_open(struct block_device *bdev, sector_t data_block_size) { int r; struct thin_disk_superblock *disk_super; struct dm_pool_metadata *pmd; sector_t bdev_size = i_size_read(bdev->bd_inode) >> SECTOR_SHIFT; struct dm_block_manager *bm; int create; struct dm_block *sblock; pmd = kmalloc(sizeof(*pmd), GFP_KERNEL); if (!pmd) { DMERR("could not allocate metadata struct"); return ERR_PTR(-ENOMEM); } /* * Max hex locks: * 3 for btree insert + * 2 for btree lookup used within space map */ bm = dm_block_manager_create(bdev, THIN_METADATA_BLOCK_SIZE, THIN_METADATA_CACHE_SIZE, 5); if (!bm) { DMERR("could not create block manager"); kfree(pmd); return ERR_PTR(-ENOMEM); } r = superblock_all_zeroes(bm, &create); if (r) { dm_block_manager_destroy(bm); kfree(pmd); return ERR_PTR(r); } r = init_pmd(pmd, bm, 0, create); if (r) { dm_block_manager_destroy(bm); kfree(pmd); return ERR_PTR(r); } pmd->bdev = bdev; if (!create) { r = __begin_transaction(pmd); if (r < 0) goto bad; return pmd; } /* * Create. */ r = dm_bm_write_lock(pmd->bm, THIN_SUPERBLOCK_LOCATION, &sb_validator, &sblock); if (r) goto bad; if (bdev_size > THIN_METADATA_MAX_SECTORS) bdev_size = THIN_METADATA_MAX_SECTORS; disk_super = dm_block_data(sblock); disk_super->magic = cpu_to_le64(THIN_SUPERBLOCK_MAGIC); disk_super->version = cpu_to_le32(THIN_VERSION); disk_super->time = 0; disk_super->metadata_block_size = cpu_to_le32(THIN_METADATA_BLOCK_SIZE >> SECTOR_SHIFT); disk_super->metadata_nr_blocks = cpu_to_le64(bdev_size >> SECTOR_TO_BLOCK_SHIFT); disk_super->data_block_size = cpu_to_le32(data_block_size); r = dm_bm_unlock(sblock); if (r < 0) goto bad; r = dm_btree_empty(&pmd->info, &pmd->root); if (r < 0) goto bad; r = dm_btree_empty(&pmd->details_info, &pmd->details_root); if (r < 0) { DMERR("couldn't create devices root"); goto bad; } pmd->flags = 0; pmd->need_commit = 1; r = dm_pool_commit_metadata(pmd); if (r < 0) { DMERR("%s: dm_pool_commit_metadata() failed, error = %d", __func__, r); goto bad; } return pmd; bad: if (dm_pool_metadata_close(pmd) < 0) DMWARN("%s: dm_pool_metadata_close() failed.", __func__); return ERR_PTR(r); } int dm_pool_metadata_close(struct dm_pool_metadata *pmd) { int r; unsigned open_devices = 0; struct dm_thin_device *td, *tmp; down_read(&pmd->root_lock); list_for_each_entry_safe(td, tmp, &pmd->thin_devices, list) { if (td->open_count) open_devices++; else { list_del(&td->list); kfree(td); } } up_read(&pmd->root_lock); if (open_devices) { DMERR("attempt to close pmd when %u device(s) are still open", open_devices); return -EBUSY; } r = __commit_transaction(pmd); if (r < 0) DMWARN("%s: __commit_transaction() failed, error = %d", __func__, r); dm_tm_destroy(pmd->tm); dm_tm_destroy(pmd->nb_tm); dm_block_manager_destroy(pmd->bm); dm_sm_destroy(pmd->metadata_sm); dm_sm_destroy(pmd->data_sm); kfree(pmd); return 0; } /* * __open_device: Returns @td corresponding to device with id @dev, * creating it if @create is set and incrementing @td->open_count. * On failure, @td is undefined. */ static int __open_device(struct dm_pool_metadata *pmd, dm_thin_id dev, int create, struct dm_thin_device **td) { int r, changed = 0; struct dm_thin_device *td2; uint64_t key = dev; struct disk_device_details details_le; /* * If the device is already open, return it. */ list_for_each_entry(td2, &pmd->thin_devices, list) if (td2->id == dev) { /* * May not create an already-open device. */ if (create) return -EEXIST; td2->open_count++; *td = td2; return 0; } /* * Check the device exists. */ r = dm_btree_lookup(&pmd->details_info, pmd->details_root, &key, &details_le); if (r) { if (r != -ENODATA || !create) return r; /* * Create new device. */ changed = 1; details_le.mapped_blocks = 0; details_le.transaction_id = cpu_to_le64(pmd->trans_id); details_le.creation_time = cpu_to_le32(pmd->time); details_le.snapshotted_time = cpu_to_le32(pmd->time); } *td = kmalloc(sizeof(**td), GFP_NOIO); if (!*td) return -ENOMEM; (*td)->pmd = pmd; (*td)->id = dev; (*td)->open_count = 1; (*td)->changed = changed; (*td)->mapped_blocks = le64_to_cpu(details_le.mapped_blocks); (*td)->transaction_id = le64_to_cpu(details_le.transaction_id); (*td)->creation_time = le32_to_cpu(details_le.creation_time); (*td)->snapshotted_time = le32_to_cpu(details_le.snapshotted_time); list_add(&(*td)->list, &pmd->thin_devices); return 0; } static void __close_device(struct dm_thin_device *td) { --td->open_count; } static int __create_thin(struct dm_pool_metadata *pmd, dm_thin_id dev) { int r; dm_block_t dev_root; uint64_t key = dev; struct disk_device_details details_le; struct dm_thin_device *td; __le64 value; r = dm_btree_lookup(&pmd->details_info, pmd->details_root, &key, &details_le); if (!r) return -EEXIST; /* * Create an empty btree for the mappings. */ r = dm_btree_empty(&pmd->bl_info, &dev_root); if (r) return r; /* * Insert it into the main mapping tree. */ value = cpu_to_le64(dev_root); __dm_bless_for_disk(&value); r = dm_btree_insert(&pmd->tl_info, pmd->root, &key, &value, &pmd->root); if (r) { dm_btree_del(&pmd->bl_info, dev_root); return r; } r = __open_device(pmd, dev, 1, &td); if (r) { dm_btree_remove(&pmd->tl_info, pmd->root, &key, &pmd->root); dm_btree_del(&pmd->bl_info, dev_root); return r; } __close_device(td); return r; } int dm_pool_create_thin(struct dm_pool_metadata *pmd, dm_thin_id dev) { int r; down_write(&pmd->root_lock); r = __create_thin(pmd, dev); up_write(&pmd->root_lock); return r; } static int __set_snapshot_details(struct dm_pool_metadata *pmd, struct dm_thin_device *snap, dm_thin_id origin, uint32_t time) { int r; struct dm_thin_device *td; r = __open_device(pmd, origin, 0, &td); if (r) return r; td->changed = 1; td->snapshotted_time = time; snap->mapped_blocks = td->mapped_blocks; snap->snapshotted_time = time; __close_device(td); return 0; } static int __create_snap(struct dm_pool_metadata *pmd, dm_thin_id dev, dm_thin_id origin) { int r; dm_block_t origin_root; uint64_t key = origin, dev_key = dev; struct dm_thin_device *td; struct disk_device_details details_le; __le64 value; /* check this device is unused */ r = dm_btree_lookup(&pmd->details_info, pmd->details_root, &dev_key, &details_le); if (!r) return -EEXIST; /* find the mapping tree for the origin */ r = dm_btree_lookup(&pmd->tl_info, pmd->root, &key, &value); if (r) return r; origin_root = le64_to_cpu(value); /* clone the origin, an inc will do */ dm_tm_inc(pmd->tm, origin_root); /* insert into the main mapping tree */ value = cpu_to_le64(origin_root); __dm_bless_for_disk(&value); key = dev; r = dm_btree_insert(&pmd->tl_info, pmd->root, &key, &value, &pmd->root); if (r) { dm_tm_dec(pmd->tm, origin_root); return r; } pmd->time++; r = __open_device(pmd, dev, 1, &td); if (r) goto bad; r = __set_snapshot_details(pmd, td, origin, pmd->time); __close_device(td); if (r) goto bad; return 0; bad: dm_btree_remove(&pmd->tl_info, pmd->root, &key, &pmd->root); dm_btree_remove(&pmd->details_info, pmd->details_root, &key, &pmd->details_root); return r; } int dm_pool_create_snap(struct dm_pool_metadata *pmd, dm_thin_id dev, dm_thin_id origin) { int r; down_write(&pmd->root_lock); r = __create_snap(pmd, dev, origin); up_write(&pmd->root_lock); return r; } static int __delete_device(struct dm_pool_metadata *pmd, dm_thin_id dev) { int r; uint64_t key = dev; struct dm_thin_device *td; /* TODO: failure should mark the transaction invalid */ r = __open_device(pmd, dev, 0, &td); if (r) return r; if (td->open_count > 1) { __close_device(td); return -EBUSY; } list_del(&td->list); kfree(td); r = dm_btree_remove(&pmd->details_info, pmd->details_root, &key, &pmd->details_root); if (r) return r; r = dm_btree_remove(&pmd->tl_info, pmd->root, &key, &pmd->root); if (r) return r; pmd->need_commit = 1; return 0; } int dm_pool_delete_thin_device(struct dm_pool_metadata *pmd, dm_thin_id dev) { int r; down_write(&pmd->root_lock); r = __delete_device(pmd, dev); up_write(&pmd->root_lock); return r; } int dm_pool_set_metadata_transaction_id(struct dm_pool_metadata *pmd, uint64_t current_id, uint64_t new_id) { down_write(&pmd->root_lock); if (pmd->trans_id != current_id) { up_write(&pmd->root_lock); DMERR("mismatched transaction id"); return -EINVAL; } pmd->trans_id = new_id; pmd->need_commit = 1; up_write(&pmd->root_lock); return 0; } int dm_pool_get_metadata_transaction_id(struct dm_pool_metadata *pmd, uint64_t *result) { down_read(&pmd->root_lock); *result = pmd->trans_id; up_read(&pmd->root_lock); return 0; } static int __get_held_metadata_root(struct dm_pool_metadata *pmd, dm_block_t *result) { int r; struct thin_disk_superblock *disk_super; struct dm_block *sblock; r = dm_bm_write_lock(pmd->bm, THIN_SUPERBLOCK_LOCATION, &sb_validator, &sblock); if (r) return r; disk_super = dm_block_data(sblock); *result = le64_to_cpu(disk_super->held_root); return dm_bm_unlock(sblock); } int dm_pool_get_held_metadata_root(struct dm_pool_metadata *pmd, dm_block_t *result) { int r; down_read(&pmd->root_lock); r = __get_held_metadata_root(pmd, result); up_read(&pmd->root_lock); return r; } int dm_pool_open_thin_device(struct dm_pool_metadata *pmd, dm_thin_id dev, struct dm_thin_device **td) { int r; down_write(&pmd->root_lock); r = __open_device(pmd, dev, 0, td); up_write(&pmd->root_lock); return r; } int dm_pool_close_thin_device(struct dm_thin_device *td) { down_write(&td->pmd->root_lock); __close_device(td); up_write(&td->pmd->root_lock); return 0; } dm_thin_id dm_thin_dev_id(struct dm_thin_device *td) { return td->id; } static int __snapshotted_since(struct dm_thin_device *td, uint32_t time) { return td->snapshotted_time > time; } int dm_thin_find_block(struct dm_thin_device *td, dm_block_t block, int can_block, struct dm_thin_lookup_result *result) { int r; uint64_t block_time = 0; __le64 value; struct dm_pool_metadata *pmd = td->pmd; dm_block_t keys[2] = { td->id, block }; if (can_block) { down_read(&pmd->root_lock); r = dm_btree_lookup(&pmd->info, pmd->root, keys, &value); if (!r) block_time = le64_to_cpu(value); up_read(&pmd->root_lock); } else if (down_read_trylock(&pmd->root_lock)) { r = dm_btree_lookup(&pmd->nb_info, pmd->root, keys, &value); if (!r) block_time = le64_to_cpu(value); up_read(&pmd->root_lock); } else return -EWOULDBLOCK; if (!r) { dm_block_t exception_block; uint32_t exception_time; unpack_block_time(block_time, &exception_block, &exception_time); result->block = exception_block; result->shared = __snapshotted_since(td, exception_time); } return r; } static int __insert(struct dm_thin_device *td, dm_block_t block, dm_block_t data_block) { int r, inserted; __le64 value; struct dm_pool_metadata *pmd = td->pmd; dm_block_t keys[2] = { td->id, block }; pmd->need_commit = 1; value = cpu_to_le64(pack_block_time(data_block, pmd->time)); __dm_bless_for_disk(&value); r = dm_btree_insert_notify(&pmd->info, pmd->root, keys, &value, &pmd->root, &inserted); if (r) return r; if (inserted) { td->mapped_blocks++; td->changed = 1; } return 0; } int dm_thin_insert_block(struct dm_thin_device *td, dm_block_t block, dm_block_t data_block) { int r; down_write(&td->pmd->root_lock); r = __insert(td, block, data_block); up_write(&td->pmd->root_lock); return r; } static int __remove(struct dm_thin_device *td, dm_block_t block) { int r; struct dm_pool_metadata *pmd = td->pmd; dm_block_t keys[2] = { td->id, block }; r = dm_btree_remove(&pmd->info, pmd->root, keys, &pmd->root); if (r) return r; td->mapped_blocks--; td->changed = 1; pmd->need_commit = 1; return 0; } int dm_thin_remove_block(struct dm_thin_device *td, dm_block_t block) { int r; down_write(&td->pmd->root_lock); r = __remove(td, block); up_write(&td->pmd->root_lock); return r; } int dm_pool_alloc_data_block(struct dm_pool_metadata *pmd, dm_block_t *result) { int r; down_write(&pmd->root_lock); r = dm_sm_new_block(pmd->data_sm, result); pmd->need_commit = 1; up_write(&pmd->root_lock); return r; } int dm_pool_commit_metadata(struct dm_pool_metadata *pmd) { int r; down_write(&pmd->root_lock); r = __commit_transaction(pmd); if (r <= 0) goto out; /* * Open the next transaction. */ r = __begin_transaction(pmd); out: up_write(&pmd->root_lock); return r; } int dm_pool_get_free_block_count(struct dm_pool_metadata *pmd, dm_block_t *result) { int r; down_read(&pmd->root_lock); r = dm_sm_get_nr_free(pmd->data_sm, result); up_read(&pmd->root_lock); return r; } int dm_pool_get_free_metadata_block_count(struct dm_pool_metadata *pmd, dm_block_t *result) { int r; down_read(&pmd->root_lock); r = dm_sm_get_nr_free(pmd->metadata_sm, result); up_read(&pmd->root_lock); return r; } int dm_pool_get_metadata_dev_size(struct dm_pool_metadata *pmd, dm_block_t *result) { int r; down_read(&pmd->root_lock); r = dm_sm_get_nr_blocks(pmd->metadata_sm, result); up_read(&pmd->root_lock); return r; } int dm_pool_get_data_block_size(struct dm_pool_metadata *pmd, sector_t *result) { down_read(&pmd->root_lock); *result = pmd->data_block_size; up_read(&pmd->root_lock); return 0; } int dm_pool_get_data_dev_size(struct dm_pool_metadata *pmd, dm_block_t *result) { int r; down_read(&pmd->root_lock); r = dm_sm_get_nr_blocks(pmd->data_sm, result); up_read(&pmd->root_lock); return r; } int dm_thin_get_mapped_count(struct dm_thin_device *td, dm_block_t *result) { struct dm_pool_metadata *pmd = td->pmd; down_read(&pmd->root_lock); *result = td->mapped_blocks; up_read(&pmd->root_lock); return 0; } static int __highest_block(struct dm_thin_device *td, dm_block_t *result) { int r; __le64 value_le; dm_block_t thin_root; struct dm_pool_metadata *pmd = td->pmd; r = dm_btree_lookup(&pmd->tl_info, pmd->root, &td->id, &value_le); if (r) return r; thin_root = le64_to_cpu(value_le); return dm_btree_find_highest_key(&pmd->bl_info, thin_root, result); } int dm_thin_get_highest_mapped_block(struct dm_thin_device *td, dm_block_t *result) { int r; struct dm_pool_metadata *pmd = td->pmd; down_read(&pmd->root_lock); r = __highest_block(td, result); up_read(&pmd->root_lock); return r; } static int __resize_data_dev(struct dm_pool_metadata *pmd, dm_block_t new_count) { int r; dm_block_t old_count; r = dm_sm_get_nr_blocks(pmd->data_sm, &old_count); if (r) return r; if (new_count == old_count) return 0; if (new_count < old_count) { DMERR("cannot reduce size of data device"); return -EINVAL; } r = dm_sm_extend(pmd->data_sm, new_count - old_count); if (!r) pmd->need_commit = 1; return r; } int dm_pool_resize_data_dev(struct dm_pool_metadata *pmd, dm_block_t new_count) { int r; down_write(&pmd->root_lock); r = __resize_data_dev(pmd, new_count); up_write(&pmd->root_lock); return r; }
gpl-3.0
slfl/HUAWEI89_WE_KK_700
kernel/drivers/rtc/rtc-m41t93.c
4809
5700
/* * * Driver for ST M41T93 SPI RTC * * (c) 2010 Nikolaus Voss, Weinmann Medical GmbH * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/bcd.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/platform_device.h> #include <linux/rtc.h> #include <linux/spi/spi.h> #define M41T93_REG_SSEC 0 #define M41T93_REG_ST_SEC 1 #define M41T93_REG_MIN 2 #define M41T93_REG_CENT_HOUR 3 #define M41T93_REG_WDAY 4 #define M41T93_REG_DAY 5 #define M41T93_REG_MON 6 #define M41T93_REG_YEAR 7 #define M41T93_REG_ALM_HOUR_HT 0xc #define M41T93_REG_FLAGS 0xf #define M41T93_FLAG_ST (1 << 7) #define M41T93_FLAG_OF (1 << 2) #define M41T93_FLAG_BL (1 << 4) #define M41T93_FLAG_HT (1 << 6) static inline int m41t93_set_reg(struct spi_device *spi, u8 addr, u8 data) { u8 buf[2]; /* MSB must be '1' to write */ buf[0] = addr | 0x80; buf[1] = data; return spi_write(spi, buf, sizeof(buf)); } static int m41t93_set_time(struct device *dev, struct rtc_time *tm) { struct spi_device *spi = to_spi_device(dev); u8 buf[9] = {0x80}; /* write cmd + 8 data bytes */ u8 * const data = &buf[1]; /* ptr to first data byte */ dev_dbg(dev, "%s secs=%d, mins=%d, " "hours=%d, mday=%d, mon=%d, year=%d, wday=%d\n", "write", tm->tm_sec, tm->tm_min, tm->tm_hour, tm->tm_mday, tm->tm_mon, tm->tm_year, tm->tm_wday); if (tm->tm_year < 100) { dev_warn(&spi->dev, "unsupported date (before 2000-01-01).\n"); return -EINVAL; } data[M41T93_REG_SSEC] = 0; data[M41T93_REG_ST_SEC] = bin2bcd(tm->tm_sec); data[M41T93_REG_MIN] = bin2bcd(tm->tm_min); data[M41T93_REG_CENT_HOUR] = bin2bcd(tm->tm_hour) | ((tm->tm_year/100-1) << 6); data[M41T93_REG_DAY] = bin2bcd(tm->tm_mday); data[M41T93_REG_WDAY] = bin2bcd(tm->tm_wday + 1); data[M41T93_REG_MON] = bin2bcd(tm->tm_mon + 1); data[M41T93_REG_YEAR] = bin2bcd(tm->tm_year % 100); return spi_write(spi, buf, sizeof(buf)); } static int m41t93_get_time(struct device *dev, struct rtc_time *tm) { struct spi_device *spi = to_spi_device(dev); const u8 start_addr = 0; u8 buf[8]; int century_after_1900; int tmp; int ret = 0; /* Check status of clock. Two states must be considered: 1. halt bit (HT) is set: the clock is running but update of readout registers has been disabled due to power failure. This is normal case after poweron. Time is valid after resetting HT bit. 2. oscillator fail bit (OF) is set. Oscillator has be stopped and time is invalid: a) OF can be immeditely reset. b) OF cannot be immediately reset: oscillator has to be restarted. */ tmp = spi_w8r8(spi, M41T93_REG_ALM_HOUR_HT); if (tmp < 0) return tmp; if (tmp & M41T93_FLAG_HT) { dev_dbg(&spi->dev, "HT bit is set, reenable clock update.\n"); m41t93_set_reg(spi, M41T93_REG_ALM_HOUR_HT, tmp & ~M41T93_FLAG_HT); } tmp = spi_w8r8(spi, M41T93_REG_FLAGS); if (tmp < 0) return tmp; if (tmp & M41T93_FLAG_OF) { ret = -EINVAL; dev_warn(&spi->dev, "OF bit is set, resetting.\n"); m41t93_set_reg(spi, M41T93_REG_FLAGS, tmp & ~M41T93_FLAG_OF); tmp = spi_w8r8(spi, M41T93_REG_FLAGS); if (tmp < 0) return tmp; else if (tmp & M41T93_FLAG_OF) { u8 reset_osc = buf[M41T93_REG_ST_SEC] | M41T93_FLAG_ST; dev_warn(&spi->dev, "OF bit is still set, kickstarting clock.\n"); m41t93_set_reg(spi, M41T93_REG_ST_SEC, reset_osc); reset_osc &= ~M41T93_FLAG_ST; m41t93_set_reg(spi, M41T93_REG_ST_SEC, reset_osc); } } if (tmp & M41T93_FLAG_BL) dev_warn(&spi->dev, "BL bit is set, replace battery.\n"); /* read actual time/date */ tmp = spi_write_then_read(spi, &start_addr, 1, buf, sizeof(buf)); if (tmp < 0) return tmp; tm->tm_sec = bcd2bin(buf[M41T93_REG_ST_SEC]); tm->tm_min = bcd2bin(buf[M41T93_REG_MIN]); tm->tm_hour = bcd2bin(buf[M41T93_REG_CENT_HOUR] & 0x3f); tm->tm_mday = bcd2bin(buf[M41T93_REG_DAY]); tm->tm_mon = bcd2bin(buf[M41T93_REG_MON]) - 1; tm->tm_wday = bcd2bin(buf[M41T93_REG_WDAY] & 0x0f) - 1; century_after_1900 = (buf[M41T93_REG_CENT_HOUR] >> 6) + 1; tm->tm_year = bcd2bin(buf[M41T93_REG_YEAR]) + century_after_1900 * 100; dev_dbg(dev, "%s secs=%d, mins=%d, " "hours=%d, mday=%d, mon=%d, year=%d, wday=%d\n", "read", tm->tm_sec, tm->tm_min, tm->tm_hour, tm->tm_mday, tm->tm_mon, tm->tm_year, tm->tm_wday); return ret < 0 ? ret : rtc_valid_tm(tm); } static const struct rtc_class_ops m41t93_rtc_ops = { .read_time = m41t93_get_time, .set_time = m41t93_set_time, }; static struct spi_driver m41t93_driver; static int __devinit m41t93_probe(struct spi_device *spi) { struct rtc_device *rtc; int res; spi->bits_per_word = 8; spi_setup(spi); res = spi_w8r8(spi, M41T93_REG_WDAY); if (res < 0 || (res & 0xf8) != 0) { dev_err(&spi->dev, "not found 0x%x.\n", res); return -ENODEV; } rtc = rtc_device_register(m41t93_driver.driver.name, &spi->dev, &m41t93_rtc_ops, THIS_MODULE); if (IS_ERR(rtc)) return PTR_ERR(rtc); dev_set_drvdata(&spi->dev, rtc); return 0; } static int __devexit m41t93_remove(struct spi_device *spi) { struct rtc_device *rtc = spi_get_drvdata(spi); if (rtc) rtc_device_unregister(rtc); return 0; } static struct spi_driver m41t93_driver = { .driver = { .name = "rtc-m41t93", .owner = THIS_MODULE, }, .probe = m41t93_probe, .remove = __devexit_p(m41t93_remove), }; module_spi_driver(m41t93_driver); MODULE_AUTHOR("Nikolaus Voss <n.voss@weinmann.de>"); MODULE_DESCRIPTION("Driver for ST M41T93 SPI RTC"); MODULE_LICENSE("GPL"); MODULE_ALIAS("spi:rtc-m41t93");
gpl-3.0
MinFu/shadowsocks-android
src/main/jni/iptables/utils/nfnl_osf.c
463
10177
/* * Copyright (c) 2005 Evgeniy Polyakov <johnpol@2ka.mxt.ru> * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <sys/types.h> #include <sys/socket.h> #include <sys/poll.h> #include <sys/time.h> #include <arpa/inet.h> #include <ctype.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdarg.h> #include <time.h> #include <unistd.h> #include <netinet/ip.h> #include <netinet/tcp.h> #include <linux/connector.h> #include <linux/types.h> #include <linux/netlink.h> #include <linux/rtnetlink.h> #include <linux/unistd.h> #include <libnfnetlink/libnfnetlink.h> #include <linux/netfilter/nfnetlink.h> #include <linux/netfilter/xt_osf.h> #define OPTDEL ',' #define OSFPDEL ':' #define MAXOPTSTRLEN 128 #ifndef NIPQUAD #define NIPQUAD(addr) \ ((unsigned char *)&addr)[0], \ ((unsigned char *)&addr)[1], \ ((unsigned char *)&addr)[2], \ ((unsigned char *)&addr)[3] #endif static struct nfnl_handle *nfnlh; static struct nfnl_subsys_handle *nfnlssh; static struct xt_osf_opt IANA_opts[] = { { .kind = 0, .length = 1,}, { .kind=1, .length=1,}, { .kind=2, .length=4,}, { .kind=3, .length=3,}, { .kind=4, .length=2,}, { .kind=5, .length=1,}, /* SACK length is not defined */ { .kind=6, .length=6,}, { .kind=7, .length=6,}, { .kind=8, .length=10,}, { .kind=9, .length=2,}, { .kind=10, .length=3,}, { .kind=11, .length=1,}, /* CC: Suppose 1 */ { .kind=12, .length=1,}, /* the same */ { .kind=13, .length=1,}, /* and here too */ { .kind=14, .length=3,}, { .kind=15, .length=1,}, /* TCP Alternate Checksum Data. Length is not defined */ { .kind=16, .length=1,}, { .kind=17, .length=1,}, { .kind=18, .length=3,}, { .kind=19, .length=18,}, { .kind=20, .length=1,}, { .kind=21, .length=1,}, { .kind=22, .length=1,}, { .kind=23, .length=1,}, { .kind=24, .length=1,}, { .kind=25, .length=1,}, { .kind=26, .length=1,}, }; static FILE *osf_log_stream; static void uloga(const char *f, ...) { va_list ap; if (!osf_log_stream) osf_log_stream = stdout; va_start(ap, f); vfprintf(osf_log_stream, f, ap); va_end(ap); fflush(osf_log_stream); } static void ulog(const char *f, ...) { char str[64]; struct tm tm; struct timeval tv; va_list ap; if (!osf_log_stream) osf_log_stream = stdout; gettimeofday(&tv, NULL); localtime_r((time_t *)&tv.tv_sec, &tm); strftime(str, sizeof(str), "%F %R:%S", &tm); fprintf(osf_log_stream, "%s.%lu %ld ", str, tv.tv_usec, syscall(__NR_gettid)); va_start(ap, f); vfprintf(osf_log_stream, f, ap); va_end(ap); fflush(osf_log_stream); } #define ulog_err(f, a...) uloga(f ": %s [%d].\n", ##a, strerror(errno), errno) static char *xt_osf_strchr(char *ptr, char c) { char *tmp; tmp = strchr(ptr, c); if (tmp) *tmp = '\0'; while (tmp && tmp + 1 && isspace(*(tmp + 1))) tmp++; return tmp; } static void xt_osf_parse_opt(struct xt_osf_opt *opt, __u16 *optnum, char *obuf, int olen) { int i, op; char *ptr, wc; unsigned long val; ptr = &obuf[0]; i = 0; while (ptr != NULL && i < olen && *ptr != 0) { val = 0; op = 0; wc = OSF_WSS_PLAIN; switch (obuf[i]) { case 'N': op = OSFOPT_NOP; ptr = xt_osf_strchr(&obuf[i], OPTDEL); if (ptr) { *ptr = '\0'; ptr++; i += (int)(ptr - &obuf[i]); } else i++; break; case 'S': op = OSFOPT_SACKP; ptr = xt_osf_strchr(&obuf[i], OPTDEL); if (ptr) { *ptr = '\0'; ptr++; i += (int)(ptr - &obuf[i]); } else i++; break; case 'T': op = OSFOPT_TS; ptr = xt_osf_strchr(&obuf[i], OPTDEL); if (ptr) { *ptr = '\0'; ptr++; i += (int)(ptr - &obuf[i]); } else i++; break; case 'W': op = OSFOPT_WSO; ptr = xt_osf_strchr(&obuf[i], OPTDEL); if (ptr) { switch (obuf[i + 1]) { case '%': wc = OSF_WSS_MODULO; break; case 'S': wc = OSF_WSS_MSS; break; case 'T': wc = OSF_WSS_MTU; break; default: wc = OSF_WSS_PLAIN; break; } *ptr = '\0'; ptr++; if (wc) val = strtoul(&obuf[i + 2], NULL, 10); else val = strtoul(&obuf[i + 1], NULL, 10); i += (int)(ptr - &obuf[i]); } else i++; break; case 'M': op = OSFOPT_MSS; ptr = xt_osf_strchr(&obuf[i], OPTDEL); if (ptr) { if (obuf[i + 1] == '%') wc = OSF_WSS_MODULO; *ptr = '\0'; ptr++; if (wc) val = strtoul(&obuf[i + 2], NULL, 10); else val = strtoul(&obuf[i + 1], NULL, 10); i += (int)(ptr - &obuf[i]); } else i++; break; case 'E': op = OSFOPT_EOL; ptr = xt_osf_strchr(&obuf[i], OPTDEL); if (ptr) { *ptr = '\0'; ptr++; i += (int)(ptr - &obuf[i]); } else i++; break; default: op = OSFOPT_EMPTY; ptr = xt_osf_strchr(&obuf[i], OPTDEL); if (ptr) { ptr++; i += (int)(ptr - &obuf[i]); } else i++; break; } if (op != OSFOPT_EMPTY) { opt[*optnum].kind = IANA_opts[op].kind; opt[*optnum].length = IANA_opts[op].length; opt[*optnum].wc.wc = wc; opt[*optnum].wc.val = val; (*optnum)++; } } } static int osf_load_line(char *buffer, int len, int del) { int i, cnt = 0; char obuf[MAXOPTSTRLEN]; struct xt_osf_user_finger f; char *pbeg, *pend; char buf[NFNL_HEADER_LEN + NFA_LENGTH(sizeof(struct xt_osf_user_finger))]; struct nlmsghdr *nmh = (struct nlmsghdr *) buf; memset(&f, 0, sizeof(struct xt_osf_user_finger)); ulog("Loading '%s'.\n", buffer); for (i = 0; i < len && buffer[i] != '\0'; ++i) { if (buffer[i] == ':') cnt++; } if (cnt != 8) { ulog("Wrong input line '%s': cnt: %d, must be 8, i: %d, must be %d.\n", buffer, cnt, i, len); return -EINVAL; } memset(obuf, 0, sizeof(obuf)); pbeg = buffer; pend = xt_osf_strchr(pbeg, OSFPDEL); if (pend) { *pend = '\0'; if (pbeg[0] == 'S') { f.wss.wc = OSF_WSS_MSS; if (pbeg[1] == '%') f.wss.val = strtoul(&pbeg[2], NULL, 10); else if (pbeg[1] == '*') f.wss.val = 0; else f.wss.val = strtoul(&pbeg[1], NULL, 10); } else if (pbeg[0] == 'T') { f.wss.wc = OSF_WSS_MTU; if (pbeg[1] == '%') f.wss.val = strtoul(&pbeg[2], NULL, 10); else if (pbeg[1] == '*') f.wss.val = 0; else f.wss.val = strtoul(&pbeg[1], NULL, 10); } else if (pbeg[0] == '%') { f.wss.wc = OSF_WSS_MODULO; f.wss.val = strtoul(&pbeg[1], NULL, 10); } else if (isdigit(pbeg[0])) { f.wss.wc = OSF_WSS_PLAIN; f.wss.val = strtoul(&pbeg[0], NULL, 10); } pbeg = pend + 1; } pend = xt_osf_strchr(pbeg, OSFPDEL); if (pend) { *pend = '\0'; f.ttl = strtoul(pbeg, NULL, 10); pbeg = pend + 1; } pend = xt_osf_strchr(pbeg, OSFPDEL); if (pend) { *pend = '\0'; f.df = strtoul(pbeg, NULL, 10); pbeg = pend + 1; } pend = xt_osf_strchr(pbeg, OSFPDEL); if (pend) { *pend = '\0'; f.ss = strtoul(pbeg, NULL, 10); pbeg = pend + 1; } pend = xt_osf_strchr(pbeg, OSFPDEL); if (pend) { *pend = '\0'; cnt = snprintf(obuf, sizeof(obuf), "%s,", pbeg); pbeg = pend + 1; } pend = xt_osf_strchr(pbeg, OSFPDEL); if (pend) { *pend = '\0'; if (pbeg[0] == '@' || pbeg[0] == '*') cnt = snprintf(f.genre, sizeof(f.genre), "%s", pbeg + 1); else cnt = snprintf(f.genre, sizeof(f.genre), "%s", pbeg); pbeg = pend + 1; } pend = xt_osf_strchr(pbeg, OSFPDEL); if (pend) { *pend = '\0'; cnt = snprintf(f.version, sizeof(f.version), "%s", pbeg); pbeg = pend + 1; } pend = xt_osf_strchr(pbeg, OSFPDEL); if (pend) { *pend = '\0'; cnt = snprintf(f.subtype, sizeof(f.subtype), "%s", pbeg); pbeg = pend + 1; } xt_osf_parse_opt(f.opt, &f.opt_num, obuf, sizeof(obuf)); memset(buf, 0, sizeof(buf)); if (del) nfnl_fill_hdr(nfnlssh, nmh, 0, AF_UNSPEC, 0, OSF_MSG_REMOVE, NLM_F_REQUEST); else nfnl_fill_hdr(nfnlssh, nmh, 0, AF_UNSPEC, 0, OSF_MSG_ADD, NLM_F_REQUEST | NLM_F_CREATE); nfnl_addattr_l(nmh, sizeof(buf), OSF_ATTR_FINGER, &f, sizeof(struct xt_osf_user_finger)); return nfnl_talk(nfnlh, nmh, 0, 0, NULL, NULL, NULL); } static int osf_load_entries(char *path, int del) { FILE *inf; int err = 0; char buf[1024]; inf = fopen(path, "r"); if (!inf) { ulog_err("Failed to open file '%s'", path); return -1; } while(fgets(buf, sizeof(buf), inf)) { int len; if (buf[0] == '#' || buf[0] == '\n' || buf[0] == '\r') continue; len = strlen(buf) - 1; if (len <= 0) continue; buf[len] = '\0'; err = osf_load_line(buf, len, del); if (err) break; memset(buf, 0, sizeof(buf)); } fclose(inf); return err; } int main(int argc, char *argv[]) { int ch, del = 0, err; char *fingerprints = NULL; while ((ch = getopt(argc, argv, "f:dh")) != -1) { switch (ch) { case 'f': fingerprints = optarg; break; case 'd': del = 1; break; default: fprintf(stderr, "Usage: %s -f fingerprints -d <del rules> -h\n", argv[0]); return -1; } } if (!fingerprints) { err = -ENOENT; goto err_out_exit; } nfnlh = nfnl_open(); if (!nfnlh) { err = -EINVAL; ulog_err("Failed to create nfnl handler"); goto err_out_exit; } #ifndef NFNL_SUBSYS_OSF #define NFNL_SUBSYS_OSF 5 #endif nfnlssh = nfnl_subsys_open(nfnlh, NFNL_SUBSYS_OSF, OSF_MSG_MAX, 0); if (!nfnlssh) { err = -EINVAL; ulog_err("Faied to create nfnl subsystem"); goto err_out_close; } err = osf_load_entries(fingerprints, del); if (err) goto err_out_close_subsys; nfnl_subsys_close(nfnlssh); nfnl_close(nfnlh); return 0; err_out_close_subsys: nfnl_subsys_close(nfnlssh); err_out_close: nfnl_close(nfnlh); err_out_exit: return err; }
gpl-3.0
autc04/Retro68
gcc/gcc/testsuite/gcc.dg/format/multattr-3.c
211
1605
/* Test for multiple format_arg attributes. Test for both branches getting checked. */ /* Origin: Joseph Myers <jsm28@cam.ac.uk> */ /* { dg-do compile } */ /* { dg-options "-std=gnu99 -Wformat" } */ #include "format.h" extern char *ngettext (const char *, const char *, unsigned long int) __attribute__((__format_arg__(1))) __attribute__((__format_arg__(2))); void foo (long l, int nfoo) { printf (ngettext ("%d foo", "%d foos", nfoo), nfoo); printf (ngettext ("%d foo", "%d foos", l), l); /* { dg-warning "int" "wrong type in conditional expr" } */ printf (ngettext ("%d foo", "%ld foos", l), l); /* { dg-warning "int" "wrong type in conditional expr" } */ printf (ngettext ("%ld foo", "%d foos", l), l); /* { dg-warning "int" "wrong type in conditional expr" } */ /* Should allow one case to have extra arguments. */ printf (ngettext ("1 foo", "%d foos", nfoo), nfoo); printf (ngettext ("1 foo", "many foos", nfoo), nfoo); /* { dg-warning "too many" "too many args in all branches" } */ printf (ngettext ("", "%d foos", nfoo), nfoo); printf (ngettext ("1 foo", (nfoo > 0) ? "%d foos" : "no foos", nfoo), nfoo); printf (ngettext ("%d foo", (nfoo > 0) ? "%d foos" : "no foos", nfoo), nfoo); printf (ngettext ("%ld foo", (nfoo > 0) ? "%d foos" : "no foos", nfoo), nfoo); /* { dg-warning "long int" "wrong type" } */ printf (ngettext ("%d foo", (nfoo > 0) ? "%ld foos" : "no foos", nfoo), nfoo); /* { dg-warning "long int" "wrong type" } */ printf (ngettext ("%d foo", (nfoo > 0) ? "%d foos" : "%ld foos", nfoo), nfoo); /* { dg-warning "long int" "wrong type" } */ }
gpl-3.0
k0nane/R915_kernel_GB
Kernel/arch/arm/mach-pxa/raumfeld.c
727
25076
/* * arch/arm/mach-pxa/raumfeld.c * * Support for the following Raumfeld devices: * * * Controller * * Connector * * Speaker S/M * * See http://www.raumfeld.com for details. * * Copyright (c) 2009 Daniel Mack <daniel@caiaq.de> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/init.h> #include <linux/kernel.h> #include <linux/sysdev.h> #include <linux/platform_device.h> #include <linux/interrupt.h> #include <linux/gpio.h> #include <linux/smsc911x.h> #include <linux/input.h> #include <linux/rotary_encoder.h> #include <linux/gpio_keys.h> #include <linux/input/eeti_ts.h> #include <linux/leds.h> #include <linux/w1-gpio.h> #include <linux/sched.h> #include <linux/pwm_backlight.h> #include <linux/i2c.h> #include <linux/spi/spi.h> #include <linux/spi/spi_gpio.h> #include <linux/lis3lv02d.h> #include <linux/pda_power.h> #include <linux/power_supply.h> #include <linux/regulator/max8660.h> #include <linux/regulator/machine.h> #include <linux/regulator/fixed.h> #include <linux/regulator/consumer.h> #include <linux/delay.h> #include <asm/mach-types.h> #include <asm/mach/arch.h> #include <mach/hardware.h> #include <mach/pxa3xx-regs.h> #include <mach/mfp-pxa3xx.h> #include <mach/mfp-pxa300.h> #include <mach/ohci.h> #include <mach/pxafb.h> #include <mach/mmc.h> #include <plat/i2c.h> #include <plat/pxa3xx_nand.h> #include "generic.h" #include "devices.h" #include "clock.h" /* common GPIO definitions */ /* inputs */ #define GPIO_ON_OFF (14) #define GPIO_VOLENC_A (19) #define GPIO_VOLENC_B (20) #define GPIO_CHARGE_DONE (23) #define GPIO_CHARGE_IND (27) #define GPIO_TOUCH_IRQ (32) #define GPIO_ETH_IRQ (40) #define GPIO_SPI_MISO (98) #define GPIO_ACCEL_IRQ (104) #define GPIO_RESCUE_BOOT (115) #define GPIO_DOCK_DETECT (116) #define GPIO_KEY1 (117) #define GPIO_KEY2 (118) #define GPIO_KEY3 (119) #define GPIO_CHARGE_USB_OK (112) #define GPIO_CHARGE_DC_OK (101) #define GPIO_CHARGE_USB_SUSP (102) /* outputs */ #define GPIO_SHUTDOWN_SUPPLY (16) #define GPIO_SHUTDOWN_BATT (18) #define GPIO_CHRG_PEN2 (31) #define GPIO_TFT_VA_EN (33) #define GPIO_SPDIF_CS (34) #define GPIO_LED2 (35) #define GPIO_LED1 (36) #define GPIO_SPDIF_RESET (38) #define GPIO_SPI_CLK (95) #define GPIO_MCLK_DAC_CS (96) #define GPIO_SPI_MOSI (97) #define GPIO_W1_PULLUP_ENABLE (105) #define GPIO_DISPLAY_ENABLE (106) #define GPIO_MCLK_RESET (111) #define GPIO_W2W_RESET (113) #define GPIO_W2W_PDN (114) #define GPIO_CODEC_RESET (120) #define GPIO_AUDIO_VA_ENABLE (124) #define GPIO_ACCEL_CS (125) #define GPIO_ONE_WIRE (126) /* * GPIO configurations */ static mfp_cfg_t raumfeld_controller_pin_config[] __initdata = { /* UART1 */ GPIO77_UART1_RXD, GPIO78_UART1_TXD, GPIO79_UART1_CTS, GPIO81_UART1_DSR, GPIO83_UART1_DTR, GPIO84_UART1_RTS, /* UART3 */ GPIO110_UART3_RXD, /* USB Host */ GPIO0_2_USBH_PEN, GPIO1_2_USBH_PWR, /* I2C */ GPIO21_I2C_SCL | MFP_LPM_FLOAT | MFP_PULL_FLOAT, GPIO22_I2C_SDA | MFP_LPM_FLOAT | MFP_PULL_FLOAT, /* SPI */ GPIO34_GPIO, /* SPDIF_CS */ GPIO96_GPIO, /* MCLK_CS */ GPIO125_GPIO, /* ACCEL_CS */ /* MMC */ GPIO3_MMC1_DAT0, GPIO4_MMC1_DAT1, GPIO5_MMC1_DAT2, GPIO6_MMC1_DAT3, GPIO7_MMC1_CLK, GPIO8_MMC1_CMD, /* One-wire */ GPIO126_GPIO | MFP_LPM_FLOAT, GPIO105_GPIO | MFP_PULL_LOW | MFP_LPM_PULL_LOW, /* CHRG_USB_OK */ GPIO101_GPIO | MFP_PULL_HIGH, /* CHRG_USB_OK */ GPIO112_GPIO | MFP_PULL_HIGH, /* CHRG_USB_SUSP */ GPIO102_GPIO, /* DISPLAY_ENABLE */ GPIO106_GPIO, /* DOCK_DETECT */ GPIO116_GPIO | MFP_LPM_FLOAT | MFP_PULL_FLOAT, /* LCD */ GPIO54_LCD_LDD_0, GPIO55_LCD_LDD_1, GPIO56_LCD_LDD_2, GPIO57_LCD_LDD_3, GPIO58_LCD_LDD_4, GPIO59_LCD_LDD_5, GPIO60_LCD_LDD_6, GPIO61_LCD_LDD_7, GPIO62_LCD_LDD_8, GPIO63_LCD_LDD_9, GPIO64_LCD_LDD_10, GPIO65_LCD_LDD_11, GPIO66_LCD_LDD_12, GPIO67_LCD_LDD_13, GPIO68_LCD_LDD_14, GPIO69_LCD_LDD_15, GPIO70_LCD_LDD_16, GPIO71_LCD_LDD_17, GPIO72_LCD_FCLK, GPIO73_LCD_LCLK, GPIO74_LCD_PCLK, GPIO75_LCD_BIAS, }; static mfp_cfg_t raumfeld_connector_pin_config[] __initdata = { /* UART1 */ GPIO77_UART1_RXD, GPIO78_UART1_TXD, GPIO79_UART1_CTS, GPIO81_UART1_DSR, GPIO83_UART1_DTR, GPIO84_UART1_RTS, /* UART3 */ GPIO110_UART3_RXD, /* USB Host */ GPIO0_2_USBH_PEN, GPIO1_2_USBH_PWR, /* I2C */ GPIO21_I2C_SCL | MFP_LPM_FLOAT | MFP_PULL_FLOAT, GPIO22_I2C_SDA | MFP_LPM_FLOAT | MFP_PULL_FLOAT, /* SPI */ GPIO34_GPIO, /* SPDIF_CS */ GPIO96_GPIO, /* MCLK_CS */ GPIO125_GPIO, /* ACCEL_CS */ /* MMC */ GPIO3_MMC1_DAT0, GPIO4_MMC1_DAT1, GPIO5_MMC1_DAT2, GPIO6_MMC1_DAT3, GPIO7_MMC1_CLK, GPIO8_MMC1_CMD, /* Ethernet */ GPIO1_nCS2, /* CS */ GPIO40_GPIO | MFP_PULL_HIGH, /* IRQ */ /* SSP for I2S */ GPIO85_SSP1_SCLK, GPIO89_SSP1_EXTCLK, GPIO86_SSP1_FRM, GPIO87_SSP1_TXD, GPIO88_SSP1_RXD, GPIO90_SSP1_SYSCLK, /* SSP2 for S/PDIF */ GPIO25_SSP2_SCLK, GPIO26_SSP2_FRM, GPIO27_SSP2_TXD, GPIO29_SSP2_EXTCLK, /* LEDs */ GPIO35_GPIO | MFP_LPM_PULL_LOW, GPIO36_GPIO | MFP_LPM_DRIVE_HIGH, }; static mfp_cfg_t raumfeld_speaker_pin_config[] __initdata = { /* UART1 */ GPIO77_UART1_RXD, GPIO78_UART1_TXD, GPIO79_UART1_CTS, GPIO81_UART1_DSR, GPIO83_UART1_DTR, GPIO84_UART1_RTS, /* UART3 */ GPIO110_UART3_RXD, /* USB Host */ GPIO0_2_USBH_PEN, GPIO1_2_USBH_PWR, /* I2C */ GPIO21_I2C_SCL | MFP_LPM_FLOAT | MFP_PULL_FLOAT, GPIO22_I2C_SDA | MFP_LPM_FLOAT | MFP_PULL_FLOAT, /* SPI */ GPIO34_GPIO, /* SPDIF_CS */ GPIO96_GPIO, /* MCLK_CS */ GPIO125_GPIO, /* ACCEL_CS */ /* MMC */ GPIO3_MMC1_DAT0, GPIO4_MMC1_DAT1, GPIO5_MMC1_DAT2, GPIO6_MMC1_DAT3, GPIO7_MMC1_CLK, GPIO8_MMC1_CMD, /* Ethernet */ GPIO1_nCS2, /* CS */ GPIO40_GPIO | MFP_PULL_HIGH, /* IRQ */ /* SSP for I2S */ GPIO85_SSP1_SCLK, GPIO89_SSP1_EXTCLK, GPIO86_SSP1_FRM, GPIO87_SSP1_TXD, GPIO88_SSP1_RXD, GPIO90_SSP1_SYSCLK, /* LEDs */ GPIO35_GPIO | MFP_LPM_PULL_LOW, GPIO36_GPIO | MFP_LPM_DRIVE_HIGH, }; /* * SMSC LAN9220 Ethernet */ static struct resource smc91x_resources[] = { { .start = PXA3xx_CS2_PHYS, .end = PXA3xx_CS2_PHYS + 0xfffff, .flags = IORESOURCE_MEM, }, { .start = gpio_to_irq(GPIO_ETH_IRQ), .end = gpio_to_irq(GPIO_ETH_IRQ), .flags = IORESOURCE_IRQ | IRQF_TRIGGER_FALLING, } }; static struct smsc911x_platform_config raumfeld_smsc911x_config = { .phy_interface = PHY_INTERFACE_MODE_MII, .irq_polarity = SMSC911X_IRQ_POLARITY_ACTIVE_LOW, .irq_type = SMSC911X_IRQ_TYPE_OPEN_DRAIN, .flags = SMSC911X_USE_32BIT | SMSC911X_SAVE_MAC_ADDRESS, }; static struct platform_device smc91x_device = { .name = "smsc911x", .id = -1, .num_resources = ARRAY_SIZE(smc91x_resources), .resource = smc91x_resources, .dev = { .platform_data = &raumfeld_smsc911x_config, } }; /** * NAND */ static struct mtd_partition raumfeld_nand_partitions[] = { { .name = "Bootloader", .offset = 0, .size = 0xa0000, .mask_flags = MTD_WRITEABLE, /* force read-only */ }, { .name = "BootloaderEnvironment", .offset = 0xa0000, .size = 0x20000, }, { .name = "BootloaderSplashScreen", .offset = 0xc0000, .size = 0x60000, }, { .name = "UBI", .offset = 0x120000, .size = MTDPART_SIZ_FULL, }, }; static struct pxa3xx_nand_platform_data raumfeld_nand_info = { .enable_arbiter = 1, .keep_config = 1, .parts = raumfeld_nand_partitions, .nr_parts = ARRAY_SIZE(raumfeld_nand_partitions), }; /** * USB (OHCI) support */ static struct pxaohci_platform_data raumfeld_ohci_info = { .port_mode = PMM_GLOBAL_MODE, .flags = ENABLE_PORT1, }; /** * Rotary encoder input device */ static struct rotary_encoder_platform_data raumfeld_rotary_encoder_info = { .steps = 24, .axis = REL_X, .relative_axis = 1, .gpio_a = GPIO_VOLENC_A, .gpio_b = GPIO_VOLENC_B, .inverted_a = 1, .inverted_b = 0, }; static struct platform_device rotary_encoder_device = { .name = "rotary-encoder", .id = 0, .dev = { .platform_data = &raumfeld_rotary_encoder_info, } }; /** * GPIO buttons */ static struct gpio_keys_button gpio_keys_button[] = { { .code = KEY_F1, .type = EV_KEY, .gpio = GPIO_KEY1, .active_low = 1, .wakeup = 0, .debounce_interval = 5, /* ms */ .desc = "Button 1", }, { .code = KEY_F2, .type = EV_KEY, .gpio = GPIO_KEY2, .active_low = 1, .wakeup = 0, .debounce_interval = 5, /* ms */ .desc = "Button 2", }, { .code = KEY_F3, .type = EV_KEY, .gpio = GPIO_KEY3, .active_low = 1, .wakeup = 0, .debounce_interval = 5, /* ms */ .desc = "Button 3", }, { .code = KEY_F4, .type = EV_KEY, .gpio = GPIO_RESCUE_BOOT, .active_low = 0, .wakeup = 0, .debounce_interval = 5, /* ms */ .desc = "rescue boot button", }, { .code = KEY_F5, .type = EV_KEY, .gpio = GPIO_DOCK_DETECT, .active_low = 1, .wakeup = 0, .debounce_interval = 5, /* ms */ .desc = "dock detect", }, { .code = KEY_F6, .type = EV_KEY, .gpio = GPIO_ON_OFF, .active_low = 0, .wakeup = 0, .debounce_interval = 5, /* ms */ .desc = "on_off button", }, }; static struct gpio_keys_platform_data gpio_keys_platform_data = { .buttons = gpio_keys_button, .nbuttons = ARRAY_SIZE(gpio_keys_button), .rep = 0, }; static struct platform_device raumfeld_gpio_keys_device = { .name = "gpio-keys", .id = -1, .dev = { .platform_data = &gpio_keys_platform_data, } }; /** * GPIO LEDs */ static struct gpio_led raumfeld_leds[] = { { .name = "raumfeld:1", .gpio = GPIO_LED1, .active_low = 1, .default_state = LEDS_GPIO_DEFSTATE_ON, }, { .name = "raumfeld:2", .gpio = GPIO_LED2, .active_low = 0, .default_state = LEDS_GPIO_DEFSTATE_OFF, } }; static struct gpio_led_platform_data raumfeld_led_platform_data = { .leds = raumfeld_leds, .num_leds = ARRAY_SIZE(raumfeld_leds), }; static struct platform_device raumfeld_led_device = { .name = "leds-gpio", .id = -1, .dev = { .platform_data = &raumfeld_led_platform_data, }, }; /** * One-wire (W1 bus) support */ static void w1_enable_external_pullup(int enable) { gpio_set_value(GPIO_W1_PULLUP_ENABLE, enable); msleep(100); } static struct w1_gpio_platform_data w1_gpio_platform_data = { .pin = GPIO_ONE_WIRE, .is_open_drain = 0, .enable_external_pullup = w1_enable_external_pullup, }; struct platform_device raumfeld_w1_gpio_device = { .name = "w1-gpio", .dev = { .platform_data = &w1_gpio_platform_data } }; static void __init raumfeld_w1_init(void) { int ret = gpio_request(GPIO_W1_PULLUP_ENABLE, "W1 external pullup enable"); if (ret < 0) pr_warning("Unable to request GPIO_W1_PULLUP_ENABLE\n"); else gpio_direction_output(GPIO_W1_PULLUP_ENABLE, 0); platform_device_register(&raumfeld_w1_gpio_device); } /** * Framebuffer device */ /* PWM controlled backlight */ static struct platform_pwm_backlight_data raumfeld_pwm_backlight_data = { .pwm_id = 0, .max_brightness = 100, .dft_brightness = 100, /* 10000 ns = 10 ms ^= 100 kHz */ .pwm_period_ns = 10000, }; static struct platform_device raumfeld_pwm_backlight_device = { .name = "pwm-backlight", .dev = { .parent = &pxa27x_device_pwm0.dev, .platform_data = &raumfeld_pwm_backlight_data, } }; /* LT3593 controlled backlight */ static struct gpio_led raumfeld_lt3593_led = { .name = "backlight", .gpio = mfp_to_gpio(MFP_PIN_GPIO17), .default_state = LEDS_GPIO_DEFSTATE_ON, }; static struct gpio_led_platform_data raumfeld_lt3593_platform_data = { .leds = &raumfeld_lt3593_led, .num_leds = 1, }; static struct platform_device raumfeld_lt3593_device = { .name = "leds-lt3593", .id = -1, .dev = { .platform_data = &raumfeld_lt3593_platform_data, }, }; static struct pxafb_mode_info sharp_lq043t3dx02_mode = { .pixclock = 111000, .xres = 480, .yres = 272, .bpp = 16, .hsync_len = 4, .left_margin = 2, .right_margin = 1, .vsync_len = 1, .upper_margin = 3, .lower_margin = 1, .sync = 0, }; static struct pxafb_mach_info raumfeld_sharp_lcd_info = { .modes = &sharp_lq043t3dx02_mode, .num_modes = 1, .video_mem_size = 0x400000, .lcd_conn = LCD_COLOR_TFT_16BPP | LCD_PCLK_EDGE_FALL, }; static void __init raumfeld_lcd_init(void) { int ret; set_pxa_fb_info(&raumfeld_sharp_lcd_info); /* Earlier devices had the backlight regulator controlled * via PWM, later versions use another controller for that */ if ((system_rev & 0xff) < 2) { mfp_cfg_t raumfeld_pwm_pin_config = GPIO17_PWM0_OUT; pxa3xx_mfp_config(&raumfeld_pwm_pin_config, 1); platform_device_register(&raumfeld_pwm_backlight_device); } else platform_device_register(&raumfeld_lt3593_device); ret = gpio_request(GPIO_TFT_VA_EN, "display VA enable"); if (ret < 0) pr_warning("Unable to request GPIO_TFT_VA_EN\n"); else gpio_direction_output(GPIO_TFT_VA_EN, 1); ret = gpio_request(GPIO_DISPLAY_ENABLE, "display enable"); if (ret < 0) pr_warning("Unable to request GPIO_DISPLAY_ENABLE\n"); else gpio_direction_output(GPIO_DISPLAY_ENABLE, 1); } /** * SPI devices */ struct spi_gpio_platform_data raumfeld_spi_platform_data = { .sck = GPIO_SPI_CLK, .mosi = GPIO_SPI_MOSI, .miso = GPIO_SPI_MISO, .num_chipselect = 3, }; static struct platform_device raumfeld_spi_device = { .name = "spi_gpio", .id = 0, .dev = { .platform_data = &raumfeld_spi_platform_data, } }; static struct lis3lv02d_platform_data lis3_pdata = { .click_flags = LIS3_CLICK_SINGLE_X | LIS3_CLICK_SINGLE_Y | LIS3_CLICK_SINGLE_Z, .irq_cfg = LIS3_IRQ1_CLICK | LIS3_IRQ2_CLICK, .wakeup_flags = LIS3_WAKEUP_X_LO | LIS3_WAKEUP_X_HI | LIS3_WAKEUP_Y_LO | LIS3_WAKEUP_Y_HI | LIS3_WAKEUP_Z_LO | LIS3_WAKEUP_Z_HI, .wakeup_thresh = 10, .click_thresh_x = 10, .click_thresh_y = 10, .click_thresh_z = 10, }; #define SPI_AK4104 \ { \ .modalias = "ak4104", \ .max_speed_hz = 10000, \ .bus_num = 0, \ .chip_select = 0, \ .controller_data = (void *) GPIO_SPDIF_CS, \ } #define SPI_LIS3 \ { \ .modalias = "lis3lv02d_spi", \ .max_speed_hz = 1000000, \ .bus_num = 0, \ .chip_select = 1, \ .controller_data = (void *) GPIO_ACCEL_CS, \ .platform_data = &lis3_pdata, \ .irq = gpio_to_irq(GPIO_ACCEL_IRQ), \ } #define SPI_DAC7512 \ { \ .modalias = "dac7512", \ .max_speed_hz = 1000000, \ .bus_num = 0, \ .chip_select = 2, \ .controller_data = (void *) GPIO_MCLK_DAC_CS, \ } static struct spi_board_info connector_spi_devices[] __initdata = { SPI_AK4104, SPI_DAC7512, }; static struct spi_board_info speaker_spi_devices[] __initdata = { SPI_DAC7512, }; static struct spi_board_info controller_spi_devices[] __initdata = { SPI_LIS3, }; /** * MMC for Marvell Libertas 8688 via SDIO */ static int raumfeld_mci_init(struct device *dev, irq_handler_t isr, void *data) { gpio_set_value(GPIO_W2W_RESET, 1); gpio_set_value(GPIO_W2W_PDN, 1); return 0; } static void raumfeld_mci_exit(struct device *dev, void *data) { gpio_set_value(GPIO_W2W_RESET, 0); gpio_set_value(GPIO_W2W_PDN, 0); } static struct pxamci_platform_data raumfeld_mci_platform_data = { .init = raumfeld_mci_init, .exit = raumfeld_mci_exit, .detect_delay_ms = 200, .gpio_card_detect = -1, .gpio_card_ro = -1, .gpio_power = -1, }; /* * External power / charge logic */ static int power_supply_init(struct device *dev) { return 0; } static void power_supply_exit(struct device *dev) { } static int raumfeld_is_ac_online(void) { return !gpio_get_value(GPIO_CHARGE_DC_OK); } static int raumfeld_is_usb_online(void) { return 0; } static char *raumfeld_power_supplicants[] = { "ds2760-battery.0" }; static struct pda_power_pdata power_supply_info = { .init = power_supply_init, .is_ac_online = raumfeld_is_ac_online, .is_usb_online = raumfeld_is_usb_online, .exit = power_supply_exit, .supplied_to = raumfeld_power_supplicants, .num_supplicants = ARRAY_SIZE(raumfeld_power_supplicants) }; static struct resource power_supply_resources[] = { { .name = "ac", .flags = IORESOURCE_IRQ | IORESOURCE_IRQ_HIGHEDGE | IORESOURCE_IRQ_LOWEDGE, .start = GPIO_CHARGE_DC_OK, .end = GPIO_CHARGE_DC_OK, }, }; static irqreturn_t charge_done_irq(int irq, void *dev_id) { struct power_supply *psy; psy = power_supply_get_by_name("ds2760-battery.0"); if (psy) power_supply_set_battery_charged(psy); return IRQ_HANDLED; } static struct platform_device raumfeld_power_supply = { .name = "pda-power", .id = -1, .dev = { .platform_data = &power_supply_info, }, .resource = power_supply_resources, .num_resources = ARRAY_SIZE(power_supply_resources), }; static void __init raumfeld_power_init(void) { int ret; /* Set PEN2 high to enable maximum charge current */ ret = gpio_request(GPIO_CHRG_PEN2, "CHRG_PEN2"); if (ret < 0) pr_warning("Unable to request GPIO_CHRG_PEN2\n"); else gpio_direction_output(GPIO_CHRG_PEN2, 1); ret = gpio_request(GPIO_CHARGE_DC_OK, "CABLE_DC_OK"); if (ret < 0) pr_warning("Unable to request GPIO_CHARGE_DC_OK\n"); ret = gpio_request(GPIO_CHARGE_USB_SUSP, "CHARGE_USB_SUSP"); if (ret < 0) pr_warning("Unable to request GPIO_CHARGE_USB_SUSP\n"); else gpio_direction_output(GPIO_CHARGE_USB_SUSP, 0); power_supply_resources[0].start = gpio_to_irq(GPIO_CHARGE_DC_OK); power_supply_resources[0].end = gpio_to_irq(GPIO_CHARGE_DC_OK); ret = request_irq(gpio_to_irq(GPIO_CHARGE_DONE), &charge_done_irq, IORESOURCE_IRQ_LOWEDGE, "charge_done", NULL); if (ret < 0) printk(KERN_ERR "%s: unable to register irq %d\n", __func__, GPIO_CHARGE_DONE); else platform_device_register(&raumfeld_power_supply); } /* Fixed regulator for AUDIO_VA, 0-0048 maps to the cs4270 codec device */ static struct regulator_consumer_supply audio_va_consumer_supply = REGULATOR_SUPPLY("va", "0-0048"); struct regulator_init_data audio_va_initdata = { .consumer_supplies = &audio_va_consumer_supply, .num_consumer_supplies = 1, .constraints = { .valid_ops_mask = REGULATOR_CHANGE_STATUS, }, }; static struct fixed_voltage_config audio_va_config = { .supply_name = "audio_va", .microvolts = 5000000, .gpio = GPIO_AUDIO_VA_ENABLE, .enable_high = 1, .enabled_at_boot = 0, .init_data = &audio_va_initdata, }; static struct platform_device audio_va_device = { .name = "reg-fixed-voltage", .id = 0, .dev = { .platform_data = &audio_va_config, }, }; /* Dummy supplies for Codec's VD/VLC */ static struct regulator_consumer_supply audio_dummy_supplies[] = { REGULATOR_SUPPLY("vd", "0-0048"), REGULATOR_SUPPLY("vlc", "0-0048"), }; struct regulator_init_data audio_dummy_initdata = { .consumer_supplies = audio_dummy_supplies, .num_consumer_supplies = ARRAY_SIZE(audio_dummy_supplies), .constraints = { .valid_ops_mask = REGULATOR_CHANGE_STATUS, }, }; static struct fixed_voltage_config audio_dummy_config = { .supply_name = "audio_vd", .microvolts = 3300000, .gpio = -1, .init_data = &audio_dummy_initdata, }; static struct platform_device audio_supply_dummy_device = { .name = "reg-fixed-voltage", .id = 1, .dev = { .platform_data = &audio_dummy_config, }, }; static struct platform_device *audio_regulator_devices[] = { &audio_va_device, &audio_supply_dummy_device, }; /** * Regulator support via MAX8660 */ static struct regulator_consumer_supply vcc_mmc_supply = REGULATOR_SUPPLY("vmmc", "pxa2xx-mci.0"); static struct regulator_init_data vcc_mmc_init_data = { .constraints = { .min_uV = 3300000, .max_uV = 3300000, .valid_modes_mask = REGULATOR_MODE_NORMAL, .valid_ops_mask = REGULATOR_CHANGE_STATUS | REGULATOR_CHANGE_VOLTAGE | REGULATOR_CHANGE_MODE, }, .consumer_supplies = &vcc_mmc_supply, .num_consumer_supplies = 1, }; struct max8660_subdev_data max8660_v6_subdev_data = { .id = MAX8660_V6, .name = "vmmc", .platform_data = &vcc_mmc_init_data, }; static struct max8660_platform_data max8660_pdata = { .subdevs = &max8660_v6_subdev_data, .num_subdevs = 1, }; /** * I2C devices */ static struct i2c_board_info raumfeld_pwri2c_board_info = { .type = "max8660", .addr = 0x34, .platform_data = &max8660_pdata, }; static struct i2c_board_info raumfeld_connector_i2c_board_info __initdata = { .type = "cs4270", .addr = 0x48, }; static struct eeti_ts_platform_data eeti_ts_pdata = { .irq_active_high = 1, }; static struct i2c_board_info raumfeld_controller_i2c_board_info __initdata = { .type = "eeti_ts", .addr = 0x0a, .irq = gpio_to_irq(GPIO_TOUCH_IRQ), .platform_data = &eeti_ts_pdata, }; static struct platform_device *raumfeld_common_devices[] = { &raumfeld_gpio_keys_device, &raumfeld_led_device, &raumfeld_spi_device, }; static void __init raumfeld_audio_init(void) { int ret; ret = gpio_request(GPIO_CODEC_RESET, "cs4270 reset"); if (ret < 0) pr_warning("unable to request GPIO_CODEC_RESET\n"); else gpio_direction_output(GPIO_CODEC_RESET, 1); ret = gpio_request(GPIO_SPDIF_RESET, "ak4104 s/pdif reset"); if (ret < 0) pr_warning("unable to request GPIO_SPDIF_RESET\n"); else gpio_direction_output(GPIO_SPDIF_RESET, 1); ret = gpio_request(GPIO_MCLK_RESET, "MCLK reset"); if (ret < 0) pr_warning("unable to request GPIO_MCLK_RESET\n"); else gpio_direction_output(GPIO_MCLK_RESET, 1); platform_add_devices(ARRAY_AND_SIZE(audio_regulator_devices)); } static void __init raumfeld_common_init(void) { int ret; /* The on/off button polarity has changed after revision 1 */ if ((system_rev & 0xff) > 1) { int i; for (i = 0; i < ARRAY_SIZE(gpio_keys_button); i++) if (!strcmp(gpio_keys_button[i].desc, "on_off button")) gpio_keys_button[i].active_low = 1; } enable_irq_wake(IRQ_WAKEUP0); pxa3xx_set_nand_info(&raumfeld_nand_info); pxa3xx_set_i2c_power_info(NULL); pxa_set_ohci_info(&raumfeld_ohci_info); pxa_set_mci_info(&raumfeld_mci_platform_data); pxa_set_i2c_info(NULL); pxa_set_ffuart_info(NULL); ret = gpio_request(GPIO_W2W_RESET, "Wi2Wi reset"); if (ret < 0) pr_warning("Unable to request GPIO_W2W_RESET\n"); else gpio_direction_output(GPIO_W2W_RESET, 0); ret = gpio_request(GPIO_W2W_PDN, "Wi2Wi powerup"); if (ret < 0) pr_warning("Unable to request GPIO_W2W_PDN\n"); else gpio_direction_output(GPIO_W2W_PDN, 0); /* this can be used to switch off the device */ ret = gpio_request(GPIO_SHUTDOWN_SUPPLY, "supply shutdown"); if (ret < 0) pr_warning("Unable to request GPIO_SHUTDOWN_SUPPLY\n"); else gpio_direction_output(GPIO_SHUTDOWN_SUPPLY, 0); platform_add_devices(ARRAY_AND_SIZE(raumfeld_common_devices)); i2c_register_board_info(1, &raumfeld_pwri2c_board_info, 1); } static void __init raumfeld_controller_init(void) { int ret; pxa3xx_mfp_config(ARRAY_AND_SIZE(raumfeld_controller_pin_config)); platform_device_register(&rotary_encoder_device); spi_register_board_info(ARRAY_AND_SIZE(controller_spi_devices)); i2c_register_board_info(0, &raumfeld_controller_i2c_board_info, 1); ret = gpio_request(GPIO_SHUTDOWN_BATT, "battery shutdown"); if (ret < 0) pr_warning("Unable to request GPIO_SHUTDOWN_BATT\n"); else gpio_direction_output(GPIO_SHUTDOWN_BATT, 0); raumfeld_common_init(); raumfeld_power_init(); raumfeld_lcd_init(); raumfeld_w1_init(); } static void __init raumfeld_connector_init(void) { pxa3xx_mfp_config(ARRAY_AND_SIZE(raumfeld_connector_pin_config)); spi_register_board_info(ARRAY_AND_SIZE(connector_spi_devices)); i2c_register_board_info(0, &raumfeld_connector_i2c_board_info, 1); platform_device_register(&smc91x_device); raumfeld_audio_init(); raumfeld_common_init(); } static void __init raumfeld_speaker_init(void) { pxa3xx_mfp_config(ARRAY_AND_SIZE(raumfeld_speaker_pin_config)); spi_register_board_info(ARRAY_AND_SIZE(speaker_spi_devices)); i2c_register_board_info(0, &raumfeld_connector_i2c_board_info, 1); platform_device_register(&smc91x_device); platform_device_register(&rotary_encoder_device); raumfeld_audio_init(); raumfeld_common_init(); } /* physical memory regions */ #define RAUMFELD_SDRAM_BASE 0xa0000000 /* SDRAM region */ #ifdef CONFIG_MACH_RAUMFELD_RC MACHINE_START(RAUMFELD_RC, "Raumfeld Controller") .phys_io = 0x40000000, .io_pg_offst = (io_p2v(0x40000000) >> 18) & 0xfffc, .boot_params = RAUMFELD_SDRAM_BASE + 0x100, .init_machine = raumfeld_controller_init, .map_io = pxa_map_io, .init_irq = pxa3xx_init_irq, .timer = &pxa_timer, MACHINE_END #endif #ifdef CONFIG_MACH_RAUMFELD_CONNECTOR MACHINE_START(RAUMFELD_CONNECTOR, "Raumfeld Connector") .phys_io = 0x40000000, .io_pg_offst = (io_p2v(0x40000000) >> 18) & 0xfffc, .boot_params = RAUMFELD_SDRAM_BASE + 0x100, .init_machine = raumfeld_connector_init, .map_io = pxa_map_io, .init_irq = pxa3xx_init_irq, .timer = &pxa_timer, MACHINE_END #endif #ifdef CONFIG_MACH_RAUMFELD_SPEAKER MACHINE_START(RAUMFELD_SPEAKER, "Raumfeld Speaker") .phys_io = 0x40000000, .io_pg_offst = (io_p2v(0x40000000) >> 18) & 0xfffc, .boot_params = RAUMFELD_SDRAM_BASE + 0x100, .init_machine = raumfeld_speaker_init, .map_io = pxa_map_io, .init_irq = pxa3xx_init_irq, .timer = &pxa_timer, MACHINE_END #endif
gpl-3.0
stranostrano/android_kernel_oppo_msm8974
arch/arm/mach-at91/board-pcontrol-g20.c
4823
5679
/* * Copyright (C) 2010 Christian Glindkamp <christian.glindkamp@taskit.de> * taskit GmbH * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* * copied and adjusted from board-stamp9g20.c * by Peter Gsellmann <pgsellmann@portner-elektronik.at> */ #include <linux/mm.h> #include <linux/platform_device.h> #include <linux/gpio.h> #include <linux/w1-gpio.h> #include <asm/mach-types.h> #include <asm/mach/arch.h> #include <mach/board.h> #include <mach/at91sam9_smc.h> #include <mach/stamp9g20.h> #include "sam9_smc.h" #include "generic.h" static void __init pcontrol_g20_init_early(void) { stamp9g20_init_early(); /* USART0 on ttyS1. (Rx, Tx, CTS, RTS) piggyback A2 */ at91_register_uart(AT91SAM9260_ID_US0, 1, ATMEL_UART_CTS | ATMEL_UART_RTS); /* USART1 on ttyS2. (Rx, Tx, CTS, RTS) isolated RS485 X5 */ at91_register_uart(AT91SAM9260_ID_US1, 2, ATMEL_UART_CTS | ATMEL_UART_RTS); /* USART2 on ttyS3. (Rx, Tx) 9bit-Bus Multidrop-mode X4 */ at91_register_uart(AT91SAM9260_ID_US4, 3, 0); } static struct sam9_smc_config __initdata pcontrol_smc_config[2] = { { .ncs_read_setup = 16, .nrd_setup = 18, .ncs_write_setup = 16, .nwe_setup = 18, .ncs_read_pulse = 63, .nrd_pulse = 55, .ncs_write_pulse = 63, .nwe_pulse = 55, .read_cycle = 127, .write_cycle = 127, .mode = AT91_SMC_READMODE | AT91_SMC_WRITEMODE | AT91_SMC_EXNWMODE_DISABLE | AT91_SMC_BAT_SELECT | AT91_SMC_DBW_8 | AT91_SMC_PS_4 | AT91_SMC_TDFMODE, .tdf_cycles = 3, }, { .ncs_read_setup = 0, .nrd_setup = 0, .ncs_write_setup = 0, .nwe_setup = 1, .ncs_read_pulse = 8, .nrd_pulse = 8, .ncs_write_pulse = 5, .nwe_pulse = 4, .read_cycle = 8, .write_cycle = 7, .mode = AT91_SMC_READMODE | AT91_SMC_WRITEMODE | AT91_SMC_EXNWMODE_DISABLE | AT91_SMC_BAT_SELECT | AT91_SMC_DBW_16 | AT91_SMC_PS_8 | AT91_SMC_TDFMODE, .tdf_cycles = 1, } }; static void __init add_device_pcontrol(void) { /* configure chip-select 4 (IO compatible to 8051 X4 ) */ sam9_smc_configure(0, 4, &pcontrol_smc_config[0]); /* configure chip-select 7 (FerroRAM 256KiBx16bit MR2A16A D4 ) */ sam9_smc_configure(0, 7, &pcontrol_smc_config[1]); } /* * USB Host port */ static struct at91_usbh_data __initdata usbh_data = { .ports = 2, .vbus_pin = {-EINVAL, -EINVAL}, .overcurrent_pin= {-EINVAL, -EINVAL}, }; /* * USB Device port */ static struct at91_udc_data __initdata pcontrol_g20_udc_data = { .vbus_pin = AT91_PIN_PA22, /* Detect +5V bus voltage */ .pullup_pin = AT91_PIN_PA4, /* K-state, active low */ }; /* * MACB Ethernet device */ static struct macb_platform_data __initdata macb_data = { .phy_irq_pin = AT91_PIN_PA28, .is_rmii = 1, }; /* * I2C devices: eeprom and phy/switch */ static struct i2c_board_info __initdata pcontrol_g20_i2c_devices[] = { { /* D7 address width=2, 8KiB */ I2C_BOARD_INFO("24c64", 0x50) }, { /* D8 address width=1, 1 byte has 32 bits! */ I2C_BOARD_INFO("lan9303", 0x0a) }, }; /* * LEDs */ static struct gpio_led pcontrol_g20_leds[] = { { .name = "LED1", /* red H5 */ .gpio = AT91_PIN_PB18, .active_low = 1, .default_trigger = "none", /* supervisor */ }, { .name = "LED2", /* yellow H7 */ .gpio = AT91_PIN_PB19, .active_low = 1, .default_trigger = "mmc0", /* SD-card activity */ }, { .name = "LED3", /* green H2 */ .gpio = AT91_PIN_PB20, .active_low = 1, .default_trigger = "heartbeat", /* blinky */ }, { .name = "LED4", /* red H3 */ .gpio = AT91_PIN_PC6, .active_low = 1, .default_trigger = "none", /* connection lost */ }, { .name = "LED5", /* yellow H6 */ .gpio = AT91_PIN_PC7, .active_low = 1, .default_trigger = "none", /* unsent data */ }, { .name = "LED6", /* green H1 */ .gpio = AT91_PIN_PC9, .active_low = 1, .default_trigger = "none", /* snafu */ } }; /* * SPI devices */ static struct spi_board_info pcontrol_g20_spi_devices[] = { { .modalias = "spidev", /* HMI port X4 */ .chip_select = 1, .max_speed_hz = 50 * 1000 * 1000, .bus_num = 0, }, { .modalias = "spidev", /* piggyback A2 */ .chip_select = 0, .max_speed_hz = 50 * 1000 * 1000, .bus_num = 1, }, }; static void __init pcontrol_g20_board_init(void) { stamp9g20_board_init(); at91_add_device_usbh(&usbh_data); at91_add_device_eth(&macb_data); at91_add_device_i2c(pcontrol_g20_i2c_devices, ARRAY_SIZE(pcontrol_g20_i2c_devices)); add_device_pcontrol(); at91_add_device_spi(pcontrol_g20_spi_devices, ARRAY_SIZE(pcontrol_g20_spi_devices)); at91_add_device_udc(&pcontrol_g20_udc_data); at91_gpio_leds(pcontrol_g20_leds, ARRAY_SIZE(pcontrol_g20_leds)); /* piggyback A2 */ at91_set_gpio_output(AT91_PIN_PB31, 1); } MACHINE_START(PCONTROL_G20, "PControl G20") /* Maintainer: pgsellmann@portner-elektronik.at */ .timer = &at91sam926x_timer, .map_io = at91_map_io, .init_early = pcontrol_g20_init_early, .init_irq = at91_init_irq_default, .init_machine = pcontrol_g20_board_init, MACHINE_END
gpl-3.0
JiaolongTong/ONOMPS_RTU
OpenSourceLibrary/linux-3.2.0-psp04.06.00.08.sdk/drivers/usb/core/message.c
217
60155
/* * message.c - synchronous message handling */ #include <linux/pci.h> /* for scatterlist macros */ #include <linux/usb.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/init.h> #include <linux/mm.h> #include <linux/timer.h> #include <linux/ctype.h> #include <linux/nls.h> #include <linux/device.h> #include <linux/scatterlist.h> #include <linux/usb/quirks.h> #include <linux/usb/hcd.h> /* for usbcore internals */ #include <asm/byteorder.h> #include "usb.h" static void cancel_async_set_config(struct usb_device *udev); struct api_context { struct completion done; int status; }; static void usb_api_blocking_completion(struct urb *urb) { struct api_context *ctx = urb->context; ctx->status = urb->status; complete(&ctx->done); } /* * Starts urb and waits for completion or timeout. Note that this call * is NOT interruptible. Many device driver i/o requests should be * interruptible and therefore these drivers should implement their * own interruptible routines. */ static int usb_start_wait_urb(struct urb *urb, int timeout, int *actual_length) { struct api_context ctx; unsigned long expire; int retval; init_completion(&ctx.done); urb->context = &ctx; urb->actual_length = 0; retval = usb_submit_urb(urb, GFP_NOIO); if (unlikely(retval)) goto out; expire = timeout ? msecs_to_jiffies(timeout) : MAX_SCHEDULE_TIMEOUT; if (!wait_for_completion_timeout(&ctx.done, expire)) { usb_kill_urb(urb); retval = (ctx.status == -ENOENT ? -ETIMEDOUT : ctx.status); dev_dbg(&urb->dev->dev, "%s timed out on ep%d%s len=%u/%u\n", current->comm, usb_endpoint_num(&urb->ep->desc), usb_urb_dir_in(urb) ? "in" : "out", urb->actual_length, urb->transfer_buffer_length); } else retval = ctx.status; out: if (actual_length) *actual_length = urb->actual_length; usb_free_urb(urb); return retval; } /*-------------------------------------------------------------------*/ /* returns status (negative) or length (positive) */ static int usb_internal_control_msg(struct usb_device *usb_dev, unsigned int pipe, struct usb_ctrlrequest *cmd, void *data, int len, int timeout) { struct urb *urb; int retv; int length; urb = usb_alloc_urb(0, GFP_NOIO); if (!urb) return -ENOMEM; usb_fill_control_urb(urb, usb_dev, pipe, (unsigned char *)cmd, data, len, usb_api_blocking_completion, NULL); retv = usb_start_wait_urb(urb, timeout, &length); if (retv < 0) return retv; else return length; } /** * usb_control_msg - Builds a control urb, sends it off and waits for completion * @dev: pointer to the usb device to send the message to * @pipe: endpoint "pipe" to send the message to * @request: USB message request value * @requesttype: USB message request type value * @value: USB message value * @index: USB message index value * @data: pointer to the data to send * @size: length in bytes of the data to send * @timeout: time in msecs to wait for the message to complete before timing * out (if 0 the wait is forever) * * Context: !in_interrupt () * * This function sends a simple control message to a specified endpoint and * waits for the message to complete, or timeout. * * If successful, it returns the number of bytes transferred, otherwise a * negative error number. * * Don't use this function from within an interrupt context, like a bottom half * handler. If you need an asynchronous message, or need to send a message * from within interrupt context, use usb_submit_urb(). * If a thread in your driver uses this call, make sure your disconnect() * method can wait for it to complete. Since you don't have a handle on the * URB used, you can't cancel the request. */ int usb_control_msg(struct usb_device *dev, unsigned int pipe, __u8 request, __u8 requesttype, __u16 value, __u16 index, void *data, __u16 size, int timeout) { struct usb_ctrlrequest *dr; int ret; dr = kmalloc(sizeof(struct usb_ctrlrequest), GFP_NOIO); if (!dr) return -ENOMEM; dr->bRequestType = requesttype; dr->bRequest = request; dr->wValue = cpu_to_le16(value); dr->wIndex = cpu_to_le16(index); dr->wLength = cpu_to_le16(size); /* dbg("usb_control_msg"); */ ret = usb_internal_control_msg(dev, pipe, dr, data, size, timeout); kfree(dr); return ret; } EXPORT_SYMBOL_GPL(usb_control_msg); /** * usb_interrupt_msg - Builds an interrupt urb, sends it off and waits for completion * @usb_dev: pointer to the usb device to send the message to * @pipe: endpoint "pipe" to send the message to * @data: pointer to the data to send * @len: length in bytes of the data to send * @actual_length: pointer to a location to put the actual length transferred * in bytes * @timeout: time in msecs to wait for the message to complete before * timing out (if 0 the wait is forever) * * Context: !in_interrupt () * * This function sends a simple interrupt message to a specified endpoint and * waits for the message to complete, or timeout. * * If successful, it returns 0, otherwise a negative error number. The number * of actual bytes transferred will be stored in the actual_length paramater. * * Don't use this function from within an interrupt context, like a bottom half * handler. If you need an asynchronous message, or need to send a message * from within interrupt context, use usb_submit_urb() If a thread in your * driver uses this call, make sure your disconnect() method can wait for it to * complete. Since you don't have a handle on the URB used, you can't cancel * the request. */ int usb_interrupt_msg(struct usb_device *usb_dev, unsigned int pipe, void *data, int len, int *actual_length, int timeout) { return usb_bulk_msg(usb_dev, pipe, data, len, actual_length, timeout); } EXPORT_SYMBOL_GPL(usb_interrupt_msg); /** * usb_bulk_msg - Builds a bulk urb, sends it off and waits for completion * @usb_dev: pointer to the usb device to send the message to * @pipe: endpoint "pipe" to send the message to * @data: pointer to the data to send * @len: length in bytes of the data to send * @actual_length: pointer to a location to put the actual length transferred * in bytes * @timeout: time in msecs to wait for the message to complete before * timing out (if 0 the wait is forever) * * Context: !in_interrupt () * * This function sends a simple bulk message to a specified endpoint * and waits for the message to complete, or timeout. * * If successful, it returns 0, otherwise a negative error number. The number * of actual bytes transferred will be stored in the actual_length paramater. * * Don't use this function from within an interrupt context, like a bottom half * handler. If you need an asynchronous message, or need to send a message * from within interrupt context, use usb_submit_urb() If a thread in your * driver uses this call, make sure your disconnect() method can wait for it to * complete. Since you don't have a handle on the URB used, you can't cancel * the request. * * Because there is no usb_interrupt_msg() and no USBDEVFS_INTERRUPT ioctl, * users are forced to abuse this routine by using it to submit URBs for * interrupt endpoints. We will take the liberty of creating an interrupt URB * (with the default interval) if the target is an interrupt endpoint. */ int usb_bulk_msg(struct usb_device *usb_dev, unsigned int pipe, void *data, int len, int *actual_length, int timeout) { struct urb *urb; struct usb_host_endpoint *ep; ep = usb_pipe_endpoint(usb_dev, pipe); if (!ep || len < 0) return -EINVAL; urb = usb_alloc_urb(0, GFP_KERNEL); if (!urb) return -ENOMEM; if ((ep->desc.bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) == USB_ENDPOINT_XFER_INT) { pipe = (pipe & ~(3 << 30)) | (PIPE_INTERRUPT << 30); usb_fill_int_urb(urb, usb_dev, pipe, data, len, usb_api_blocking_completion, NULL, ep->desc.bInterval); } else usb_fill_bulk_urb(urb, usb_dev, pipe, data, len, usb_api_blocking_completion, NULL); return usb_start_wait_urb(urb, timeout, actual_length); } EXPORT_SYMBOL_GPL(usb_bulk_msg); /*-------------------------------------------------------------------*/ static void sg_clean(struct usb_sg_request *io) { if (io->urbs) { while (io->entries--) usb_free_urb(io->urbs [io->entries]); kfree(io->urbs); io->urbs = NULL; } io->dev = NULL; } static void sg_complete(struct urb *urb) { struct usb_sg_request *io = urb->context; int status = urb->status; spin_lock(&io->lock); /* In 2.5 we require hcds' endpoint queues not to progress after fault * reports, until the completion callback (this!) returns. That lets * device driver code (like this routine) unlink queued urbs first, * if it needs to, since the HC won't work on them at all. So it's * not possible for page N+1 to overwrite page N, and so on. * * That's only for "hard" faults; "soft" faults (unlinks) sometimes * complete before the HCD can get requests away from hardware, * though never during cleanup after a hard fault. */ if (io->status && (io->status != -ECONNRESET || status != -ECONNRESET) && urb->actual_length) { dev_err(io->dev->bus->controller, "dev %s ep%d%s scatterlist error %d/%d\n", io->dev->devpath, usb_endpoint_num(&urb->ep->desc), usb_urb_dir_in(urb) ? "in" : "out", status, io->status); /* BUG (); */ } if (io->status == 0 && status && status != -ECONNRESET) { int i, found, retval; io->status = status; /* the previous urbs, and this one, completed already. * unlink pending urbs so they won't rx/tx bad data. * careful: unlink can sometimes be synchronous... */ spin_unlock(&io->lock); for (i = 0, found = 0; i < io->entries; i++) { if (!io->urbs [i] || !io->urbs [i]->dev) continue; if (found) { retval = usb_unlink_urb(io->urbs [i]); if (retval != -EINPROGRESS && retval != -ENODEV && retval != -EBUSY) dev_err(&io->dev->dev, "%s, unlink --> %d\n", __func__, retval); } else if (urb == io->urbs [i]) found = 1; } spin_lock(&io->lock); } urb->dev = NULL; /* on the last completion, signal usb_sg_wait() */ io->bytes += urb->actual_length; io->count--; if (!io->count) complete(&io->complete); spin_unlock(&io->lock); } /** * usb_sg_init - initializes scatterlist-based bulk/interrupt I/O request * @io: request block being initialized. until usb_sg_wait() returns, * treat this as a pointer to an opaque block of memory, * @dev: the usb device that will send or receive the data * @pipe: endpoint "pipe" used to transfer the data * @period: polling rate for interrupt endpoints, in frames or * (for high speed endpoints) microframes; ignored for bulk * @sg: scatterlist entries * @nents: how many entries in the scatterlist * @length: how many bytes to send from the scatterlist, or zero to * send every byte identified in the list. * @mem_flags: SLAB_* flags affecting memory allocations in this call * * Returns zero for success, else a negative errno value. This initializes a * scatter/gather request, allocating resources such as I/O mappings and urb * memory (except maybe memory used by USB controller drivers). * * The request must be issued using usb_sg_wait(), which waits for the I/O to * complete (or to be canceled) and then cleans up all resources allocated by * usb_sg_init(). * * The request may be canceled with usb_sg_cancel(), either before or after * usb_sg_wait() is called. */ int usb_sg_init(struct usb_sg_request *io, struct usb_device *dev, unsigned pipe, unsigned period, struct scatterlist *sg, int nents, size_t length, gfp_t mem_flags) { int i; int urb_flags; int use_sg; if (!io || !dev || !sg || usb_pipecontrol(pipe) || usb_pipeisoc(pipe) || nents <= 0) return -EINVAL; spin_lock_init(&io->lock); io->dev = dev; io->pipe = pipe; if (dev->bus->sg_tablesize > 0) { use_sg = true; io->entries = 1; } else { use_sg = false; io->entries = nents; } /* initialize all the urbs we'll use */ io->urbs = kmalloc(io->entries * sizeof *io->urbs, mem_flags); if (!io->urbs) goto nomem; urb_flags = URB_NO_INTERRUPT; if (usb_pipein(pipe)) urb_flags |= URB_SHORT_NOT_OK; for_each_sg(sg, sg, io->entries, i) { struct urb *urb; unsigned len; urb = usb_alloc_urb(0, mem_flags); if (!urb) { io->entries = i; goto nomem; } io->urbs[i] = urb; urb->dev = NULL; urb->pipe = pipe; urb->interval = period; urb->transfer_flags = urb_flags; urb->complete = sg_complete; urb->context = io; urb->sg = sg; if (use_sg) { /* There is no single transfer buffer */ urb->transfer_buffer = NULL; urb->num_sgs = nents; /* A length of zero means transfer the whole sg list */ len = length; if (len == 0) { struct scatterlist *sg2; int j; for_each_sg(sg, sg2, nents, j) len += sg2->length; } } else { /* * Some systems can't use DMA; they use PIO instead. * For their sakes, transfer_buffer is set whenever * possible. */ if (!PageHighMem(sg_page(sg))) urb->transfer_buffer = sg_virt(sg); else urb->transfer_buffer = NULL; len = sg->length; if (length) { len = min_t(size_t, len, length); length -= len; if (length == 0) io->entries = i + 1; } } urb->transfer_buffer_length = len; } io->urbs[--i]->transfer_flags &= ~URB_NO_INTERRUPT; /* transaction state */ io->count = io->entries; io->status = 0; io->bytes = 0; init_completion(&io->complete); return 0; nomem: sg_clean(io); return -ENOMEM; } EXPORT_SYMBOL_GPL(usb_sg_init); /** * usb_sg_wait - synchronously execute scatter/gather request * @io: request block handle, as initialized with usb_sg_init(). * some fields become accessible when this call returns. * Context: !in_interrupt () * * This function blocks until the specified I/O operation completes. It * leverages the grouping of the related I/O requests to get good transfer * rates, by queueing the requests. At higher speeds, such queuing can * significantly improve USB throughput. * * There are three kinds of completion for this function. * (1) success, where io->status is zero. The number of io->bytes * transferred is as requested. * (2) error, where io->status is a negative errno value. The number * of io->bytes transferred before the error is usually less * than requested, and can be nonzero. * (3) cancellation, a type of error with status -ECONNRESET that * is initiated by usb_sg_cancel(). * * When this function returns, all memory allocated through usb_sg_init() or * this call will have been freed. The request block parameter may still be * passed to usb_sg_cancel(), or it may be freed. It could also be * reinitialized and then reused. * * Data Transfer Rates: * * Bulk transfers are valid for full or high speed endpoints. * The best full speed data rate is 19 packets of 64 bytes each * per frame, or 1216 bytes per millisecond. * The best high speed data rate is 13 packets of 512 bytes each * per microframe, or 52 KBytes per millisecond. * * The reason to use interrupt transfers through this API would most likely * be to reserve high speed bandwidth, where up to 24 KBytes per millisecond * could be transferred. That capability is less useful for low or full * speed interrupt endpoints, which allow at most one packet per millisecond, * of at most 8 or 64 bytes (respectively). * * It is not necessary to call this function to reserve bandwidth for devices * under an xHCI host controller, as the bandwidth is reserved when the * configuration or interface alt setting is selected. */ void usb_sg_wait(struct usb_sg_request *io) { int i; int entries = io->entries; /* queue the urbs. */ spin_lock_irq(&io->lock); i = 0; while (i < entries && !io->status) { int retval; io->urbs[i]->dev = io->dev; retval = usb_submit_urb(io->urbs [i], GFP_ATOMIC); /* after we submit, let completions or cancelations fire; * we handshake using io->status. */ spin_unlock_irq(&io->lock); switch (retval) { /* maybe we retrying will recover */ case -ENXIO: /* hc didn't queue this one */ case -EAGAIN: case -ENOMEM: io->urbs[i]->dev = NULL; retval = 0; yield(); break; /* no error? continue immediately. * * NOTE: to work better with UHCI (4K I/O buffer may * need 3K of TDs) it may be good to limit how many * URBs are queued at once; N milliseconds? */ case 0: ++i; cpu_relax(); break; /* fail any uncompleted urbs */ default: io->urbs[i]->dev = NULL; io->urbs[i]->status = retval; dev_dbg(&io->dev->dev, "%s, submit --> %d\n", __func__, retval); usb_sg_cancel(io); } spin_lock_irq(&io->lock); if (retval && (io->status == 0 || io->status == -ECONNRESET)) io->status = retval; } io->count -= entries - i; if (io->count == 0) complete(&io->complete); spin_unlock_irq(&io->lock); /* OK, yes, this could be packaged as non-blocking. * So could the submit loop above ... but it's easier to * solve neither problem than to solve both! */ wait_for_completion(&io->complete); sg_clean(io); } EXPORT_SYMBOL_GPL(usb_sg_wait); /** * usb_sg_cancel - stop scatter/gather i/o issued by usb_sg_wait() * @io: request block, initialized with usb_sg_init() * * This stops a request after it has been started by usb_sg_wait(). * It can also prevents one initialized by usb_sg_init() from starting, * so that call just frees resources allocated to the request. */ void usb_sg_cancel(struct usb_sg_request *io) { unsigned long flags; spin_lock_irqsave(&io->lock, flags); /* shut everything down, if it didn't already */ if (!io->status) { int i; io->status = -ECONNRESET; spin_unlock(&io->lock); for (i = 0; i < io->entries; i++) { int retval; if (!io->urbs [i]->dev) continue; retval = usb_unlink_urb(io->urbs [i]); if (retval != -EINPROGRESS && retval != -EBUSY) dev_warn(&io->dev->dev, "%s, unlink --> %d\n", __func__, retval); } spin_lock(&io->lock); } spin_unlock_irqrestore(&io->lock, flags); } EXPORT_SYMBOL_GPL(usb_sg_cancel); /*-------------------------------------------------------------------*/ /** * usb_get_descriptor - issues a generic GET_DESCRIPTOR request * @dev: the device whose descriptor is being retrieved * @type: the descriptor type (USB_DT_*) * @index: the number of the descriptor * @buf: where to put the descriptor * @size: how big is "buf"? * Context: !in_interrupt () * * Gets a USB descriptor. Convenience functions exist to simplify * getting some types of descriptors. Use * usb_get_string() or usb_string() for USB_DT_STRING. * Device (USB_DT_DEVICE) and configuration descriptors (USB_DT_CONFIG) * are part of the device structure. * In addition to a number of USB-standard descriptors, some * devices also use class-specific or vendor-specific descriptors. * * This call is synchronous, and may not be used in an interrupt context. * * Returns the number of bytes received on success, or else the status code * returned by the underlying usb_control_msg() call. */ int usb_get_descriptor(struct usb_device *dev, unsigned char type, unsigned char index, void *buf, int size) { int i; int result; memset(buf, 0, size); /* Make sure we parse really received data */ for (i = 0; i < 3; ++i) { /* retry on length 0 or error; some devices are flakey */ result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0), USB_REQ_GET_DESCRIPTOR, USB_DIR_IN, (type << 8) + index, 0, buf, size, USB_CTRL_GET_TIMEOUT); if (result <= 0 && result != -ETIMEDOUT) continue; if (result > 1 && ((u8 *)buf)[1] != type) { result = -ENODATA; continue; } break; } return result; } EXPORT_SYMBOL_GPL(usb_get_descriptor); /** * usb_get_string - gets a string descriptor * @dev: the device whose string descriptor is being retrieved * @langid: code for language chosen (from string descriptor zero) * @index: the number of the descriptor * @buf: where to put the string * @size: how big is "buf"? * Context: !in_interrupt () * * Retrieves a string, encoded using UTF-16LE (Unicode, 16 bits per character, * in little-endian byte order). * The usb_string() function will often be a convenient way to turn * these strings into kernel-printable form. * * Strings may be referenced in device, configuration, interface, or other * descriptors, and could also be used in vendor-specific ways. * * This call is synchronous, and may not be used in an interrupt context. * * Returns the number of bytes received on success, or else the status code * returned by the underlying usb_control_msg() call. */ static int usb_get_string(struct usb_device *dev, unsigned short langid, unsigned char index, void *buf, int size) { int i; int result; for (i = 0; i < 3; ++i) { /* retry on length 0 or stall; some devices are flakey */ result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0), USB_REQ_GET_DESCRIPTOR, USB_DIR_IN, (USB_DT_STRING << 8) + index, langid, buf, size, USB_CTRL_GET_TIMEOUT); if (result == 0 || result == -EPIPE) continue; if (result > 1 && ((u8 *) buf)[1] != USB_DT_STRING) { result = -ENODATA; continue; } break; } return result; } static void usb_try_string_workarounds(unsigned char *buf, int *length) { int newlength, oldlength = *length; for (newlength = 2; newlength + 1 < oldlength; newlength += 2) if (!isprint(buf[newlength]) || buf[newlength + 1]) break; if (newlength > 2) { buf[0] = newlength; *length = newlength; } } static int usb_string_sub(struct usb_device *dev, unsigned int langid, unsigned int index, unsigned char *buf) { int rc; /* Try to read the string descriptor by asking for the maximum * possible number of bytes */ if (dev->quirks & USB_QUIRK_STRING_FETCH_255) rc = -EIO; else rc = usb_get_string(dev, langid, index, buf, 255); /* If that failed try to read the descriptor length, then * ask for just that many bytes */ if (rc < 2) { rc = usb_get_string(dev, langid, index, buf, 2); if (rc == 2) rc = usb_get_string(dev, langid, index, buf, buf[0]); } if (rc >= 2) { if (!buf[0] && !buf[1]) usb_try_string_workarounds(buf, &rc); /* There might be extra junk at the end of the descriptor */ if (buf[0] < rc) rc = buf[0]; rc = rc - (rc & 1); /* force a multiple of two */ } if (rc < 2) rc = (rc < 0 ? rc : -EINVAL); return rc; } static int usb_get_langid(struct usb_device *dev, unsigned char *tbuf) { int err; if (dev->have_langid) return 0; if (dev->string_langid < 0) return -EPIPE; err = usb_string_sub(dev, 0, 0, tbuf); /* If the string was reported but is malformed, default to english * (0x0409) */ if (err == -ENODATA || (err > 0 && err < 4)) { dev->string_langid = 0x0409; dev->have_langid = 1; dev_err(&dev->dev, "string descriptor 0 malformed (err = %d), " "defaulting to 0x%04x\n", err, dev->string_langid); return 0; } /* In case of all other errors, we assume the device is not able to * deal with strings at all. Set string_langid to -1 in order to * prevent any string to be retrieved from the device */ if (err < 0) { dev_err(&dev->dev, "string descriptor 0 read error: %d\n", err); dev->string_langid = -1; return -EPIPE; } /* always use the first langid listed */ dev->string_langid = tbuf[2] | (tbuf[3] << 8); dev->have_langid = 1; dev_dbg(&dev->dev, "default language 0x%04x\n", dev->string_langid); return 0; } /** * usb_string - returns UTF-8 version of a string descriptor * @dev: the device whose string descriptor is being retrieved * @index: the number of the descriptor * @buf: where to put the string * @size: how big is "buf"? * Context: !in_interrupt () * * This converts the UTF-16LE encoded strings returned by devices, from * usb_get_string_descriptor(), to null-terminated UTF-8 encoded ones * that are more usable in most kernel contexts. Note that this function * chooses strings in the first language supported by the device. * * This call is synchronous, and may not be used in an interrupt context. * * Returns length of the string (>= 0) or usb_control_msg status (< 0). */ int usb_string(struct usb_device *dev, int index, char *buf, size_t size) { unsigned char *tbuf; int err; if (dev->state == USB_STATE_SUSPENDED) return -EHOSTUNREACH; if (size <= 0 || !buf || !index) return -EINVAL; buf[0] = 0; tbuf = kmalloc(256, GFP_NOIO); if (!tbuf) return -ENOMEM; err = usb_get_langid(dev, tbuf); if (err < 0) goto errout; err = usb_string_sub(dev, dev->string_langid, index, tbuf); if (err < 0) goto errout; size--; /* leave room for trailing NULL char in output buffer */ err = utf16s_to_utf8s((wchar_t *) &tbuf[2], (err - 2) / 2, UTF16_LITTLE_ENDIAN, buf, size); buf[err] = 0; if (tbuf[1] != USB_DT_STRING) dev_dbg(&dev->dev, "wrong descriptor type %02x for string %d (\"%s\")\n", tbuf[1], index, buf); errout: kfree(tbuf); return err; } EXPORT_SYMBOL_GPL(usb_string); /* one UTF-8-encoded 16-bit character has at most three bytes */ #define MAX_USB_STRING_SIZE (127 * 3 + 1) /** * usb_cache_string - read a string descriptor and cache it for later use * @udev: the device whose string descriptor is being read * @index: the descriptor index * * Returns a pointer to a kmalloc'ed buffer containing the descriptor string, * or NULL if the index is 0 or the string could not be read. */ char *usb_cache_string(struct usb_device *udev, int index) { char *buf; char *smallbuf = NULL; int len; if (index <= 0) return NULL; buf = kmalloc(MAX_USB_STRING_SIZE, GFP_NOIO); if (buf) { len = usb_string(udev, index, buf, MAX_USB_STRING_SIZE); if (len > 0) { smallbuf = kmalloc(++len, GFP_NOIO); if (!smallbuf) return buf; memcpy(smallbuf, buf, len); } kfree(buf); } return smallbuf; } /* * usb_get_device_descriptor - (re)reads the device descriptor (usbcore) * @dev: the device whose device descriptor is being updated * @size: how much of the descriptor to read * Context: !in_interrupt () * * Updates the copy of the device descriptor stored in the device structure, * which dedicates space for this purpose. * * Not exported, only for use by the core. If drivers really want to read * the device descriptor directly, they can call usb_get_descriptor() with * type = USB_DT_DEVICE and index = 0. * * This call is synchronous, and may not be used in an interrupt context. * * Returns the number of bytes received on success, or else the status code * returned by the underlying usb_control_msg() call. */ int usb_get_device_descriptor(struct usb_device *dev, unsigned int size) { struct usb_device_descriptor *desc; int ret; if (size > sizeof(*desc)) return -EINVAL; desc = kmalloc(sizeof(*desc), GFP_NOIO); if (!desc) return -ENOMEM; ret = usb_get_descriptor(dev, USB_DT_DEVICE, 0, desc, size); if (ret >= 0) memcpy(&dev->descriptor, desc, size); kfree(desc); return ret; } /** * usb_get_status - issues a GET_STATUS call * @dev: the device whose status is being checked * @type: USB_RECIP_*; for device, interface, or endpoint * @target: zero (for device), else interface or endpoint number * @data: pointer to two bytes of bitmap data * Context: !in_interrupt () * * Returns device, interface, or endpoint status. Normally only of * interest to see if the device is self powered, or has enabled the * remote wakeup facility; or whether a bulk or interrupt endpoint * is halted ("stalled"). * * Bits in these status bitmaps are set using the SET_FEATURE request, * and cleared using the CLEAR_FEATURE request. The usb_clear_halt() * function should be used to clear halt ("stall") status. * * This call is synchronous, and may not be used in an interrupt context. * * Returns the number of bytes received on success, or else the status code * returned by the underlying usb_control_msg() call. */ int usb_get_status(struct usb_device *dev, int type, int target, void *data) { int ret; u16 *status = kmalloc(sizeof(*status), GFP_KERNEL); if (!status) return -ENOMEM; ret = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0), USB_REQ_GET_STATUS, USB_DIR_IN | type, 0, target, status, sizeof(*status), USB_CTRL_GET_TIMEOUT); *(u16 *)data = *status; kfree(status); return ret; } EXPORT_SYMBOL_GPL(usb_get_status); /** * usb_clear_halt - tells device to clear endpoint halt/stall condition * @dev: device whose endpoint is halted * @pipe: endpoint "pipe" being cleared * Context: !in_interrupt () * * This is used to clear halt conditions for bulk and interrupt endpoints, * as reported by URB completion status. Endpoints that are halted are * sometimes referred to as being "stalled". Such endpoints are unable * to transmit or receive data until the halt status is cleared. Any URBs * queued for such an endpoint should normally be unlinked by the driver * before clearing the halt condition, as described in sections 5.7.5 * and 5.8.5 of the USB 2.0 spec. * * Note that control and isochronous endpoints don't halt, although control * endpoints report "protocol stall" (for unsupported requests) using the * same status code used to report a true stall. * * This call is synchronous, and may not be used in an interrupt context. * * Returns zero on success, or else the status code returned by the * underlying usb_control_msg() call. */ int usb_clear_halt(struct usb_device *dev, int pipe) { int result; int endp = usb_pipeendpoint(pipe); if (usb_pipein(pipe)) endp |= USB_DIR_IN; /* we don't care if it wasn't halted first. in fact some devices * (like some ibmcam model 1 units) seem to expect hosts to make * this request for iso endpoints, which can't halt! */ result = usb_control_msg(dev, usb_sndctrlpipe(dev, 0), USB_REQ_CLEAR_FEATURE, USB_RECIP_ENDPOINT, USB_ENDPOINT_HALT, endp, NULL, 0, USB_CTRL_SET_TIMEOUT); /* don't un-halt or force to DATA0 except on success */ if (result < 0) return result; /* NOTE: seems like Microsoft and Apple don't bother verifying * the clear "took", so some devices could lock up if you check... * such as the Hagiwara FlashGate DUAL. So we won't bother. * * NOTE: make sure the logic here doesn't diverge much from * the copy in usb-storage, for as long as we need two copies. */ usb_reset_endpoint(dev, endp); return 0; } EXPORT_SYMBOL_GPL(usb_clear_halt); static int create_intf_ep_devs(struct usb_interface *intf) { struct usb_device *udev = interface_to_usbdev(intf); struct usb_host_interface *alt = intf->cur_altsetting; int i; if (intf->ep_devs_created || intf->unregistering) return 0; for (i = 0; i < alt->desc.bNumEndpoints; ++i) (void) usb_create_ep_devs(&intf->dev, &alt->endpoint[i], udev); intf->ep_devs_created = 1; return 0; } static void remove_intf_ep_devs(struct usb_interface *intf) { struct usb_host_interface *alt = intf->cur_altsetting; int i; if (!intf->ep_devs_created) return; for (i = 0; i < alt->desc.bNumEndpoints; ++i) usb_remove_ep_devs(&alt->endpoint[i]); intf->ep_devs_created = 0; } /** * usb_disable_endpoint -- Disable an endpoint by address * @dev: the device whose endpoint is being disabled * @epaddr: the endpoint's address. Endpoint number for output, * endpoint number + USB_DIR_IN for input * @reset_hardware: flag to erase any endpoint state stored in the * controller hardware * * Disables the endpoint for URB submission and nukes all pending URBs. * If @reset_hardware is set then also deallocates hcd/hardware state * for the endpoint. */ void usb_disable_endpoint(struct usb_device *dev, unsigned int epaddr, bool reset_hardware) { unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK; struct usb_host_endpoint *ep; if (!dev) return; if (usb_endpoint_out(epaddr)) { ep = dev->ep_out[epnum]; if (reset_hardware) dev->ep_out[epnum] = NULL; } else { ep = dev->ep_in[epnum]; if (reset_hardware) dev->ep_in[epnum] = NULL; } if (ep) { ep->enabled = 0; usb_hcd_flush_endpoint(dev, ep); if (reset_hardware) usb_hcd_disable_endpoint(dev, ep); } } /** * usb_reset_endpoint - Reset an endpoint's state. * @dev: the device whose endpoint is to be reset * @epaddr: the endpoint's address. Endpoint number for output, * endpoint number + USB_DIR_IN for input * * Resets any host-side endpoint state such as the toggle bit, * sequence number or current window. */ void usb_reset_endpoint(struct usb_device *dev, unsigned int epaddr) { unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK; struct usb_host_endpoint *ep; if (usb_endpoint_out(epaddr)) ep = dev->ep_out[epnum]; else ep = dev->ep_in[epnum]; if (ep) usb_hcd_reset_endpoint(dev, ep); } EXPORT_SYMBOL_GPL(usb_reset_endpoint); /** * usb_disable_interface -- Disable all endpoints for an interface * @dev: the device whose interface is being disabled * @intf: pointer to the interface descriptor * @reset_hardware: flag to erase any endpoint state stored in the * controller hardware * * Disables all the endpoints for the interface's current altsetting. */ void usb_disable_interface(struct usb_device *dev, struct usb_interface *intf, bool reset_hardware) { struct usb_host_interface *alt = intf->cur_altsetting; int i; for (i = 0; i < alt->desc.bNumEndpoints; ++i) { usb_disable_endpoint(dev, alt->endpoint[i].desc.bEndpointAddress, reset_hardware); } } /** * usb_disable_device - Disable all the endpoints for a USB device * @dev: the device whose endpoints are being disabled * @skip_ep0: 0 to disable endpoint 0, 1 to skip it. * * Disables all the device's endpoints, potentially including endpoint 0. * Deallocates hcd/hardware state for the endpoints (nuking all or most * pending urbs) and usbcore state for the interfaces, so that usbcore * must usb_set_configuration() before any interfaces could be used. * * Must be called with hcd->bandwidth_mutex held. */ void usb_disable_device(struct usb_device *dev, int skip_ep0) { int i; struct usb_hcd *hcd = bus_to_hcd(dev->bus); /* getting rid of interfaces will disconnect * any drivers bound to them (a key side effect) */ if (dev->actconfig) { /* * FIXME: In order to avoid self-deadlock involving the * bandwidth_mutex, we have to mark all the interfaces * before unregistering any of them. */ for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) dev->actconfig->interface[i]->unregistering = 1; for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) { struct usb_interface *interface; /* remove this interface if it has been registered */ interface = dev->actconfig->interface[i]; if (!device_is_registered(&interface->dev)) continue; dev_dbg(&dev->dev, "unregistering interface %s\n", dev_name(&interface->dev)); remove_intf_ep_devs(interface); device_del(&interface->dev); } /* Now that the interfaces are unbound, nobody should * try to access them. */ for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) { put_device(&dev->actconfig->interface[i]->dev); dev->actconfig->interface[i] = NULL; } dev->actconfig = NULL; if (dev->state == USB_STATE_CONFIGURED) usb_set_device_state(dev, USB_STATE_ADDRESS); } dev_dbg(&dev->dev, "%s nuking %s URBs\n", __func__, skip_ep0 ? "non-ep0" : "all"); if (hcd->driver->check_bandwidth) { /* First pass: Cancel URBs, leave endpoint pointers intact. */ for (i = skip_ep0; i < 16; ++i) { usb_disable_endpoint(dev, i, false); usb_disable_endpoint(dev, i + USB_DIR_IN, false); } /* Remove endpoints from the host controller internal state */ usb_hcd_alloc_bandwidth(dev, NULL, NULL, NULL); /* Second pass: remove endpoint pointers */ } for (i = skip_ep0; i < 16; ++i) { usb_disable_endpoint(dev, i, true); usb_disable_endpoint(dev, i + USB_DIR_IN, true); } } /** * usb_enable_endpoint - Enable an endpoint for USB communications * @dev: the device whose interface is being enabled * @ep: the endpoint * @reset_ep: flag to reset the endpoint state * * Resets the endpoint state if asked, and sets dev->ep_{in,out} pointers. * For control endpoints, both the input and output sides are handled. */ void usb_enable_endpoint(struct usb_device *dev, struct usb_host_endpoint *ep, bool reset_ep) { int epnum = usb_endpoint_num(&ep->desc); int is_out = usb_endpoint_dir_out(&ep->desc); int is_control = usb_endpoint_xfer_control(&ep->desc); if (reset_ep) usb_hcd_reset_endpoint(dev, ep); if (is_out || is_control) dev->ep_out[epnum] = ep; if (!is_out || is_control) dev->ep_in[epnum] = ep; ep->enabled = 1; } /** * usb_enable_interface - Enable all the endpoints for an interface * @dev: the device whose interface is being enabled * @intf: pointer to the interface descriptor * @reset_eps: flag to reset the endpoints' state * * Enables all the endpoints for the interface's current altsetting. */ void usb_enable_interface(struct usb_device *dev, struct usb_interface *intf, bool reset_eps) { struct usb_host_interface *alt = intf->cur_altsetting; int i; for (i = 0; i < alt->desc.bNumEndpoints; ++i) usb_enable_endpoint(dev, &alt->endpoint[i], reset_eps); } /** * usb_set_interface - Makes a particular alternate setting be current * @dev: the device whose interface is being updated * @interface: the interface being updated * @alternate: the setting being chosen. * Context: !in_interrupt () * * This is used to enable data transfers on interfaces that may not * be enabled by default. Not all devices support such configurability. * Only the driver bound to an interface may change its setting. * * Within any given configuration, each interface may have several * alternative settings. These are often used to control levels of * bandwidth consumption. For example, the default setting for a high * speed interrupt endpoint may not send more than 64 bytes per microframe, * while interrupt transfers of up to 3KBytes per microframe are legal. * Also, isochronous endpoints may never be part of an * interface's default setting. To access such bandwidth, alternate * interface settings must be made current. * * Note that in the Linux USB subsystem, bandwidth associated with * an endpoint in a given alternate setting is not reserved until an URB * is submitted that needs that bandwidth. Some other operating systems * allocate bandwidth early, when a configuration is chosen. * * This call is synchronous, and may not be used in an interrupt context. * Also, drivers must not change altsettings while urbs are scheduled for * endpoints in that interface; all such urbs must first be completed * (perhaps forced by unlinking). * * Returns zero on success, or else the status code returned by the * underlying usb_control_msg() call. */ int usb_set_interface(struct usb_device *dev, int interface, int alternate) { struct usb_interface *iface; struct usb_host_interface *alt; struct usb_hcd *hcd = bus_to_hcd(dev->bus); int ret; int manual = 0; unsigned int epaddr; unsigned int pipe; if (dev->state == USB_STATE_SUSPENDED) return -EHOSTUNREACH; iface = usb_ifnum_to_if(dev, interface); if (!iface) { dev_dbg(&dev->dev, "selecting invalid interface %d\n", interface); return -EINVAL; } if (iface->unregistering) return -ENODEV; alt = usb_altnum_to_altsetting(iface, alternate); if (!alt) { dev_warn(&dev->dev, "selecting invalid altsetting %d\n", alternate); return -EINVAL; } /* Make sure we have enough bandwidth for this alternate interface. * Remove the current alt setting and add the new alt setting. */ mutex_lock(hcd->bandwidth_mutex); ret = usb_hcd_alloc_bandwidth(dev, NULL, iface->cur_altsetting, alt); if (ret < 0) { dev_info(&dev->dev, "Not enough bandwidth for altsetting %d\n", alternate); mutex_unlock(hcd->bandwidth_mutex); return ret; } if (dev->quirks & USB_QUIRK_NO_SET_INTF) ret = -EPIPE; else ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0), USB_REQ_SET_INTERFACE, USB_RECIP_INTERFACE, alternate, interface, NULL, 0, 5000); /* 9.4.10 says devices don't need this and are free to STALL the * request if the interface only has one alternate setting. */ if (ret == -EPIPE && iface->num_altsetting == 1) { dev_dbg(&dev->dev, "manual set_interface for iface %d, alt %d\n", interface, alternate); manual = 1; } else if (ret < 0) { /* Re-instate the old alt setting */ usb_hcd_alloc_bandwidth(dev, NULL, alt, iface->cur_altsetting); mutex_unlock(hcd->bandwidth_mutex); return ret; } mutex_unlock(hcd->bandwidth_mutex); /* FIXME drivers shouldn't need to replicate/bugfix the logic here * when they implement async or easily-killable versions of this or * other "should-be-internal" functions (like clear_halt). * should hcd+usbcore postprocess control requests? */ /* prevent submissions using previous endpoint settings */ if (iface->cur_altsetting != alt) { remove_intf_ep_devs(iface); usb_remove_sysfs_intf_files(iface); } usb_disable_interface(dev, iface, true); iface->cur_altsetting = alt; /* If the interface only has one altsetting and the device didn't * accept the request, we attempt to carry out the equivalent action * by manually clearing the HALT feature for each endpoint in the * new altsetting. */ if (manual) { int i; for (i = 0; i < alt->desc.bNumEndpoints; i++) { epaddr = alt->endpoint[i].desc.bEndpointAddress; pipe = __create_pipe(dev, USB_ENDPOINT_NUMBER_MASK & epaddr) | (usb_endpoint_out(epaddr) ? USB_DIR_OUT : USB_DIR_IN); usb_clear_halt(dev, pipe); } } /* 9.1.1.5: reset toggles for all endpoints in the new altsetting * * Note: * Despite EP0 is always present in all interfaces/AS, the list of * endpoints from the descriptor does not contain EP0. Due to its * omnipresence one might expect EP0 being considered "affected" by * any SetInterface request and hence assume toggles need to be reset. * However, EP0 toggles are re-synced for every individual transfer * during the SETUP stage - hence EP0 toggles are "don't care" here. * (Likewise, EP0 never "halts" on well designed devices.) */ usb_enable_interface(dev, iface, true); if (device_is_registered(&iface->dev)) { usb_create_sysfs_intf_files(iface); create_intf_ep_devs(iface); } return 0; } EXPORT_SYMBOL_GPL(usb_set_interface); /** * usb_reset_configuration - lightweight device reset * @dev: the device whose configuration is being reset * * This issues a standard SET_CONFIGURATION request to the device using * the current configuration. The effect is to reset most USB-related * state in the device, including interface altsettings (reset to zero), * endpoint halts (cleared), and endpoint state (only for bulk and interrupt * endpoints). Other usbcore state is unchanged, including bindings of * usb device drivers to interfaces. * * Because this affects multiple interfaces, avoid using this with composite * (multi-interface) devices. Instead, the driver for each interface may * use usb_set_interface() on the interfaces it claims. Be careful though; * some devices don't support the SET_INTERFACE request, and others won't * reset all the interface state (notably endpoint state). Resetting the whole * configuration would affect other drivers' interfaces. * * The caller must own the device lock. * * Returns zero on success, else a negative error code. */ int usb_reset_configuration(struct usb_device *dev) { int i, retval; struct usb_host_config *config; struct usb_hcd *hcd = bus_to_hcd(dev->bus); if (dev->state == USB_STATE_SUSPENDED) return -EHOSTUNREACH; /* caller must have locked the device and must own * the usb bus readlock (so driver bindings are stable); * calls during probe() are fine */ for (i = 1; i < 16; ++i) { usb_disable_endpoint(dev, i, true); usb_disable_endpoint(dev, i + USB_DIR_IN, true); } config = dev->actconfig; retval = 0; mutex_lock(hcd->bandwidth_mutex); /* Make sure we have enough bandwidth for each alternate setting 0 */ for (i = 0; i < config->desc.bNumInterfaces; i++) { struct usb_interface *intf = config->interface[i]; struct usb_host_interface *alt; alt = usb_altnum_to_altsetting(intf, 0); if (!alt) alt = &intf->altsetting[0]; if (alt != intf->cur_altsetting) retval = usb_hcd_alloc_bandwidth(dev, NULL, intf->cur_altsetting, alt); if (retval < 0) break; } /* If not, reinstate the old alternate settings */ if (retval < 0) { reset_old_alts: for (i--; i >= 0; i--) { struct usb_interface *intf = config->interface[i]; struct usb_host_interface *alt; alt = usb_altnum_to_altsetting(intf, 0); if (!alt) alt = &intf->altsetting[0]; if (alt != intf->cur_altsetting) usb_hcd_alloc_bandwidth(dev, NULL, alt, intf->cur_altsetting); } mutex_unlock(hcd->bandwidth_mutex); return retval; } retval = usb_control_msg(dev, usb_sndctrlpipe(dev, 0), USB_REQ_SET_CONFIGURATION, 0, config->desc.bConfigurationValue, 0, NULL, 0, USB_CTRL_SET_TIMEOUT); if (retval < 0) goto reset_old_alts; mutex_unlock(hcd->bandwidth_mutex); /* re-init hc/hcd interface/endpoint state */ for (i = 0; i < config->desc.bNumInterfaces; i++) { struct usb_interface *intf = config->interface[i]; struct usb_host_interface *alt; alt = usb_altnum_to_altsetting(intf, 0); /* No altsetting 0? We'll assume the first altsetting. * We could use a GetInterface call, but if a device is * so non-compliant that it doesn't have altsetting 0 * then I wouldn't trust its reply anyway. */ if (!alt) alt = &intf->altsetting[0]; if (alt != intf->cur_altsetting) { remove_intf_ep_devs(intf); usb_remove_sysfs_intf_files(intf); } intf->cur_altsetting = alt; usb_enable_interface(dev, intf, true); if (device_is_registered(&intf->dev)) { usb_create_sysfs_intf_files(intf); create_intf_ep_devs(intf); } } return 0; } EXPORT_SYMBOL_GPL(usb_reset_configuration); static void usb_release_interface(struct device *dev) { struct usb_interface *intf = to_usb_interface(dev); struct usb_interface_cache *intfc = altsetting_to_usb_interface_cache(intf->altsetting); kref_put(&intfc->ref, usb_release_interface_cache); kfree(intf); } #ifdef CONFIG_HOTPLUG static int usb_if_uevent(struct device *dev, struct kobj_uevent_env *env) { struct usb_device *usb_dev; struct usb_interface *intf; struct usb_host_interface *alt; intf = to_usb_interface(dev); usb_dev = interface_to_usbdev(intf); alt = intf->cur_altsetting; if (add_uevent_var(env, "INTERFACE=%d/%d/%d", alt->desc.bInterfaceClass, alt->desc.bInterfaceSubClass, alt->desc.bInterfaceProtocol)) return -ENOMEM; if (add_uevent_var(env, "MODALIAS=usb:" "v%04Xp%04Xd%04Xdc%02Xdsc%02Xdp%02Xic%02Xisc%02Xip%02X", le16_to_cpu(usb_dev->descriptor.idVendor), le16_to_cpu(usb_dev->descriptor.idProduct), le16_to_cpu(usb_dev->descriptor.bcdDevice), usb_dev->descriptor.bDeviceClass, usb_dev->descriptor.bDeviceSubClass, usb_dev->descriptor.bDeviceProtocol, alt->desc.bInterfaceClass, alt->desc.bInterfaceSubClass, alt->desc.bInterfaceProtocol)) return -ENOMEM; return 0; } #else static int usb_if_uevent(struct device *dev, struct kobj_uevent_env *env) { return -ENODEV; } #endif /* CONFIG_HOTPLUG */ struct device_type usb_if_device_type = { .name = "usb_interface", .release = usb_release_interface, .uevent = usb_if_uevent, }; static struct usb_interface_assoc_descriptor *find_iad(struct usb_device *dev, struct usb_host_config *config, u8 inum) { struct usb_interface_assoc_descriptor *retval = NULL; struct usb_interface_assoc_descriptor *intf_assoc; int first_intf; int last_intf; int i; for (i = 0; (i < USB_MAXIADS && config->intf_assoc[i]); i++) { intf_assoc = config->intf_assoc[i]; if (intf_assoc->bInterfaceCount == 0) continue; first_intf = intf_assoc->bFirstInterface; last_intf = first_intf + (intf_assoc->bInterfaceCount - 1); if (inum >= first_intf && inum <= last_intf) { if (!retval) retval = intf_assoc; else dev_err(&dev->dev, "Interface #%d referenced" " by multiple IADs\n", inum); } } return retval; } /* * Internal function to queue a device reset * * This is initialized into the workstruct in 'struct * usb_device->reset_ws' that is launched by * message.c:usb_set_configuration() when initializing each 'struct * usb_interface'. * * It is safe to get the USB device without reference counts because * the life cycle of @iface is bound to the life cycle of @udev. Then, * this function will be ran only if @iface is alive (and before * freeing it any scheduled instances of it will have been cancelled). * * We need to set a flag (usb_dev->reset_running) because when we call * the reset, the interfaces might be unbound. The current interface * cannot try to remove the queued work as it would cause a deadlock * (you cannot remove your work from within your executing * workqueue). This flag lets it know, so that * usb_cancel_queued_reset() doesn't try to do it. * * See usb_queue_reset_device() for more details */ static void __usb_queue_reset_device(struct work_struct *ws) { int rc; struct usb_interface *iface = container_of(ws, struct usb_interface, reset_ws); struct usb_device *udev = interface_to_usbdev(iface); rc = usb_lock_device_for_reset(udev, iface); if (rc >= 0) { iface->reset_running = 1; usb_reset_device(udev); iface->reset_running = 0; usb_unlock_device(udev); } } /* * usb_set_configuration - Makes a particular device setting be current * @dev: the device whose configuration is being updated * @configuration: the configuration being chosen. * Context: !in_interrupt(), caller owns the device lock * * This is used to enable non-default device modes. Not all devices * use this kind of configurability; many devices only have one * configuration. * * @configuration is the value of the configuration to be installed. * According to the USB spec (e.g. section 9.1.1.5), configuration values * must be non-zero; a value of zero indicates that the device in * unconfigured. However some devices erroneously use 0 as one of their * configuration values. To help manage such devices, this routine will * accept @configuration = -1 as indicating the device should be put in * an unconfigured state. * * USB device configurations may affect Linux interoperability, * power consumption and the functionality available. For example, * the default configuration is limited to using 100mA of bus power, * so that when certain device functionality requires more power, * and the device is bus powered, that functionality should be in some * non-default device configuration. Other device modes may also be * reflected as configuration options, such as whether two ISDN * channels are available independently; and choosing between open * standard device protocols (like CDC) or proprietary ones. * * Note that a non-authorized device (dev->authorized == 0) will only * be put in unconfigured mode. * * Note that USB has an additional level of device configurability, * associated with interfaces. That configurability is accessed using * usb_set_interface(). * * This call is synchronous. The calling context must be able to sleep, * must own the device lock, and must not hold the driver model's USB * bus mutex; usb interface driver probe() methods cannot use this routine. * * Returns zero on success, or else the status code returned by the * underlying call that failed. On successful completion, each interface * in the original device configuration has been destroyed, and each one * in the new configuration has been probed by all relevant usb device * drivers currently known to the kernel. */ int usb_set_configuration(struct usb_device *dev, int configuration) { int i, ret; struct usb_host_config *cp = NULL; struct usb_interface **new_interfaces = NULL; struct usb_hcd *hcd = bus_to_hcd(dev->bus); int n, nintf; if (dev->authorized == 0 || configuration == -1) configuration = 0; else { for (i = 0; i < dev->descriptor.bNumConfigurations; i++) { if (dev->config[i].desc.bConfigurationValue == configuration) { cp = &dev->config[i]; break; } } } if ((!cp && configuration != 0)) return -EINVAL; /* The USB spec says configuration 0 means unconfigured. * But if a device includes a configuration numbered 0, * we will accept it as a correctly configured state. * Use -1 if you really want to unconfigure the device. */ if (cp && configuration == 0) dev_warn(&dev->dev, "config 0 descriptor??\n"); /* Allocate memory for new interfaces before doing anything else, * so that if we run out then nothing will have changed. */ n = nintf = 0; if (cp) { nintf = cp->desc.bNumInterfaces; new_interfaces = kmalloc(nintf * sizeof(*new_interfaces), GFP_NOIO); if (!new_interfaces) { dev_err(&dev->dev, "Out of memory\n"); return -ENOMEM; } for (; n < nintf; ++n) { new_interfaces[n] = kzalloc( sizeof(struct usb_interface), GFP_NOIO); if (!new_interfaces[n]) { dev_err(&dev->dev, "Out of memory\n"); ret = -ENOMEM; free_interfaces: while (--n >= 0) kfree(new_interfaces[n]); kfree(new_interfaces); return ret; } } i = dev->bus_mA - cp->desc.bMaxPower * 2; if (i < 0) dev_warn(&dev->dev, "new config #%d exceeds power " "limit by %dmA\n", configuration, -i); } /* Wake up the device so we can send it the Set-Config request */ ret = usb_autoresume_device(dev); if (ret) goto free_interfaces; /* if it's already configured, clear out old state first. * getting rid of old interfaces means unbinding their drivers. */ mutex_lock(hcd->bandwidth_mutex); if (dev->state != USB_STATE_ADDRESS) usb_disable_device(dev, 1); /* Skip ep0 */ /* Get rid of pending async Set-Config requests for this device */ cancel_async_set_config(dev); /* Make sure we have bandwidth (and available HCD resources) for this * configuration. Remove endpoints from the schedule if we're dropping * this configuration to set configuration 0. After this point, the * host controller will not allow submissions to dropped endpoints. If * this call fails, the device state is unchanged. */ ret = usb_hcd_alloc_bandwidth(dev, cp, NULL, NULL); if (ret < 0) { mutex_unlock(hcd->bandwidth_mutex); usb_autosuspend_device(dev); goto free_interfaces; } ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0), USB_REQ_SET_CONFIGURATION, 0, configuration, 0, NULL, 0, USB_CTRL_SET_TIMEOUT); if (ret < 0) { /* All the old state is gone, so what else can we do? * The device is probably useless now anyway. */ cp = NULL; } dev->actconfig = cp; if (!cp) { usb_set_device_state(dev, USB_STATE_ADDRESS); usb_hcd_alloc_bandwidth(dev, NULL, NULL, NULL); mutex_unlock(hcd->bandwidth_mutex); usb_autosuspend_device(dev); goto free_interfaces; } mutex_unlock(hcd->bandwidth_mutex); usb_set_device_state(dev, USB_STATE_CONFIGURED); /* Initialize the new interface structures and the * hc/hcd/usbcore interface/endpoint state. */ for (i = 0; i < nintf; ++i) { struct usb_interface_cache *intfc; struct usb_interface *intf; struct usb_host_interface *alt; cp->interface[i] = intf = new_interfaces[i]; intfc = cp->intf_cache[i]; intf->altsetting = intfc->altsetting; intf->num_altsetting = intfc->num_altsetting; intf->intf_assoc = find_iad(dev, cp, i); kref_get(&intfc->ref); alt = usb_altnum_to_altsetting(intf, 0); /* No altsetting 0? We'll assume the first altsetting. * We could use a GetInterface call, but if a device is * so non-compliant that it doesn't have altsetting 0 * then I wouldn't trust its reply anyway. */ if (!alt) alt = &intf->altsetting[0]; intf->cur_altsetting = alt; usb_enable_interface(dev, intf, true); intf->dev.parent = &dev->dev; intf->dev.driver = NULL; intf->dev.bus = &usb_bus_type; intf->dev.type = &usb_if_device_type; intf->dev.groups = usb_interface_groups; intf->dev.dma_mask = dev->dev.dma_mask; INIT_WORK(&intf->reset_ws, __usb_queue_reset_device); intf->minor = -1; device_initialize(&intf->dev); pm_runtime_no_callbacks(&intf->dev); dev_set_name(&intf->dev, "%d-%s:%d.%d", dev->bus->busnum, dev->devpath, configuration, alt->desc.bInterfaceNumber); } kfree(new_interfaces); if (cp->string == NULL && !(dev->quirks & USB_QUIRK_CONFIG_INTF_STRINGS)) cp->string = usb_cache_string(dev, cp->desc.iConfiguration); /* Now that all the interfaces are set up, register them * to trigger binding of drivers to interfaces. probe() * routines may install different altsettings and may * claim() any interfaces not yet bound. Many class drivers * need that: CDC, audio, video, etc. */ for (i = 0; i < nintf; ++i) { struct usb_interface *intf = cp->interface[i]; dev_dbg(&dev->dev, "adding %s (config #%d, interface %d)\n", dev_name(&intf->dev), configuration, intf->cur_altsetting->desc.bInterfaceNumber); device_enable_async_suspend(&intf->dev); ret = device_add(&intf->dev); if (ret != 0) { dev_err(&dev->dev, "device_add(%s) --> %d\n", dev_name(&intf->dev), ret); continue; } create_intf_ep_devs(intf); } usb_autosuspend_device(dev); return 0; } static LIST_HEAD(set_config_list); static DEFINE_SPINLOCK(set_config_lock); struct set_config_request { struct usb_device *udev; int config; struct work_struct work; struct list_head node; }; /* Worker routine for usb_driver_set_configuration() */ static void driver_set_config_work(struct work_struct *work) { struct set_config_request *req = container_of(work, struct set_config_request, work); struct usb_device *udev = req->udev; usb_lock_device(udev); spin_lock(&set_config_lock); list_del(&req->node); spin_unlock(&set_config_lock); if (req->config >= -1) /* Is req still valid? */ usb_set_configuration(udev, req->config); usb_unlock_device(udev); usb_put_dev(udev); kfree(req); } /* Cancel pending Set-Config requests for a device whose configuration * was just changed */ static void cancel_async_set_config(struct usb_device *udev) { struct set_config_request *req; spin_lock(&set_config_lock); list_for_each_entry(req, &set_config_list, node) { if (req->udev == udev) req->config = -999; /* Mark as cancelled */ } spin_unlock(&set_config_lock); } /** * usb_driver_set_configuration - Provide a way for drivers to change device configurations * @udev: the device whose configuration is being updated * @config: the configuration being chosen. * Context: In process context, must be able to sleep * * Device interface drivers are not allowed to change device configurations. * This is because changing configurations will destroy the interface the * driver is bound to and create new ones; it would be like a floppy-disk * driver telling the computer to replace the floppy-disk drive with a * tape drive! * * Still, in certain specialized circumstances the need may arise. This * routine gets around the normal restrictions by using a work thread to * submit the change-config request. * * Returns 0 if the request was successfully queued, error code otherwise. * The caller has no way to know whether the queued request will eventually * succeed. */ int usb_driver_set_configuration(struct usb_device *udev, int config) { struct set_config_request *req; req = kmalloc(sizeof(*req), GFP_KERNEL); if (!req) return -ENOMEM; req->udev = udev; req->config = config; INIT_WORK(&req->work, driver_set_config_work); spin_lock(&set_config_lock); list_add(&req->node, &set_config_list); spin_unlock(&set_config_lock); usb_get_dev(udev); schedule_work(&req->work); return 0; } EXPORT_SYMBOL_GPL(usb_driver_set_configuration);
gpl-3.0
invisiblek/kernel_lge_v700
arch/powerpc/platforms/powernv/opal-rtc.c
7132
2401
/* * PowerNV Real Time Clock. * * Copyright 2011 IBM Corp. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #include <linux/kernel.h> #include <linux/time.h> #include <linux/bcd.h> #include <linux/rtc.h> #include <linux/delay.h> #include <asm/opal.h> #include <asm/firmware.h> static void opal_to_tm(u32 y_m_d, u64 h_m_s_ms, struct rtc_time *tm) { tm->tm_year = ((bcd2bin(y_m_d >> 24) * 100) + bcd2bin((y_m_d >> 16) & 0xff)) - 1900; tm->tm_mon = bcd2bin((y_m_d >> 8) & 0xff) - 1; tm->tm_mday = bcd2bin(y_m_d & 0xff); tm->tm_hour = bcd2bin((h_m_s_ms >> 56) & 0xff); tm->tm_min = bcd2bin((h_m_s_ms >> 48) & 0xff); tm->tm_sec = bcd2bin((h_m_s_ms >> 40) & 0xff); GregorianDay(tm); } unsigned long __init opal_get_boot_time(void) { struct rtc_time tm; u32 y_m_d; u64 h_m_s_ms; long rc = OPAL_BUSY; while (rc == OPAL_BUSY || rc == OPAL_BUSY_EVENT) { rc = opal_rtc_read(&y_m_d, &h_m_s_ms); if (rc == OPAL_BUSY_EVENT) opal_poll_events(NULL); else mdelay(10); } if (rc != OPAL_SUCCESS) return 0; opal_to_tm(y_m_d, h_m_s_ms, &tm); return mktime(tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec); } void opal_get_rtc_time(struct rtc_time *tm) { long rc = OPAL_BUSY; u32 y_m_d; u64 h_m_s_ms; while (rc == OPAL_BUSY || rc == OPAL_BUSY_EVENT) { rc = opal_rtc_read(&y_m_d, &h_m_s_ms); if (rc == OPAL_BUSY_EVENT) opal_poll_events(NULL); else mdelay(10); } if (rc != OPAL_SUCCESS) return; opal_to_tm(y_m_d, h_m_s_ms, tm); } int opal_set_rtc_time(struct rtc_time *tm) { long rc = OPAL_BUSY; u32 y_m_d = 0; u64 h_m_s_ms = 0; y_m_d |= ((u32)bin2bcd((tm->tm_year + 1900) / 100)) << 24; y_m_d |= ((u32)bin2bcd((tm->tm_year + 1900) % 100)) << 16; y_m_d |= ((u32)bin2bcd((tm->tm_mon + 1))) << 8; y_m_d |= ((u32)bin2bcd(tm->tm_mday)); h_m_s_ms |= ((u64)bin2bcd(tm->tm_hour)) << 56; h_m_s_ms |= ((u64)bin2bcd(tm->tm_min)) << 48; h_m_s_ms |= ((u64)bin2bcd(tm->tm_sec)) << 40; while (rc == OPAL_BUSY || rc == OPAL_BUSY_EVENT) { rc = opal_rtc_write(y_m_d, h_m_s_ms); if (rc == OPAL_BUSY_EVENT) opal_poll_events(NULL); else mdelay(10); } return rc == OPAL_SUCCESS ? 0 : -EIO; }
gpl-3.0
slfl/HUAWEI89_WE_KK_610
kernel/drivers/usb/misc/sisusbvga/sisusb_init.c
11746
25368
/* * sisusb - usb kernel driver for SiS315(E) based USB2VGA dongles * * Display mode initializing code * * Copyright (C) 2001-2005 by Thomas Winischhofer, Vienna, Austria * * If distributed as part of the Linux kernel, this code is licensed under the * terms of the GPL v2. * * Otherwise, the following license terms apply: * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions * * are met: * * 1) Redistributions of source code must retain the above copyright * * notice, this list of conditions and the following disclaimer. * * 2) Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the following disclaimer in the * * documentation and/or other materials provided with the distribution. * * 3) The name of the author may not be used to endorse or promote products * * derived from this software without specific prior written permission. * * * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Author: Thomas Winischhofer <thomas@winischhofer.net> * */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/errno.h> #include <linux/poll.h> #include <linux/init.h> #include <linux/spinlock.h> #include "sisusb.h" #ifdef INCL_SISUSB_CON #include "sisusb_init.h" /*********************************************/ /* POINTER INITIALIZATION */ /*********************************************/ static void SiSUSB_InitPtr(struct SiS_Private *SiS_Pr) { SiS_Pr->SiS_ModeResInfo = SiSUSB_ModeResInfo; SiS_Pr->SiS_StandTable = SiSUSB_StandTable; SiS_Pr->SiS_SModeIDTable = SiSUSB_SModeIDTable; SiS_Pr->SiS_EModeIDTable = SiSUSB_EModeIDTable; SiS_Pr->SiS_RefIndex = SiSUSB_RefIndex; SiS_Pr->SiS_CRT1Table = SiSUSB_CRT1Table; SiS_Pr->SiS_VCLKData = SiSUSB_VCLKData; } /*********************************************/ /* HELPER: SetReg, GetReg */ /*********************************************/ static void SiS_SetReg(struct SiS_Private *SiS_Pr, unsigned long port, unsigned short index, unsigned short data) { sisusb_setidxreg(SiS_Pr->sisusb, port, index, data); } static void SiS_SetRegByte(struct SiS_Private *SiS_Pr, unsigned long port, unsigned short data) { sisusb_setreg(SiS_Pr->sisusb, port, data); } static unsigned char SiS_GetReg(struct SiS_Private *SiS_Pr, unsigned long port, unsigned short index) { u8 data; sisusb_getidxreg(SiS_Pr->sisusb, port, index, &data); return data; } static unsigned char SiS_GetRegByte(struct SiS_Private *SiS_Pr, unsigned long port) { u8 data; sisusb_getreg(SiS_Pr->sisusb, port, &data); return data; } static void SiS_SetRegANDOR(struct SiS_Private *SiS_Pr, unsigned long port, unsigned short index, unsigned short DataAND, unsigned short DataOR) { sisusb_setidxregandor(SiS_Pr->sisusb, port, index, DataAND, DataOR); } static void SiS_SetRegAND(struct SiS_Private *SiS_Pr, unsigned long port, unsigned short index, unsigned short DataAND) { sisusb_setidxregand(SiS_Pr->sisusb, port, index, DataAND); } static void SiS_SetRegOR(struct SiS_Private *SiS_Pr, unsigned long port, unsigned short index, unsigned short DataOR) { sisusb_setidxregor(SiS_Pr->sisusb, port, index, DataOR); } /*********************************************/ /* HELPER: DisplayOn, DisplayOff */ /*********************************************/ static void SiS_DisplayOn(struct SiS_Private *SiS_Pr) { SiS_SetRegAND(SiS_Pr, SiS_Pr->SiS_P3c4, 0x01, 0xDF); } /*********************************************/ /* HELPER: Init Port Addresses */ /*********************************************/ static void SiSUSBRegInit(struct SiS_Private *SiS_Pr, unsigned long BaseAddr) { SiS_Pr->SiS_P3c4 = BaseAddr + 0x14; SiS_Pr->SiS_P3d4 = BaseAddr + 0x24; SiS_Pr->SiS_P3c0 = BaseAddr + 0x10; SiS_Pr->SiS_P3ce = BaseAddr + 0x1e; SiS_Pr->SiS_P3c2 = BaseAddr + 0x12; SiS_Pr->SiS_P3ca = BaseAddr + 0x1a; SiS_Pr->SiS_P3c6 = BaseAddr + 0x16; SiS_Pr->SiS_P3c7 = BaseAddr + 0x17; SiS_Pr->SiS_P3c8 = BaseAddr + 0x18; SiS_Pr->SiS_P3c9 = BaseAddr + 0x19; SiS_Pr->SiS_P3cb = BaseAddr + 0x1b; SiS_Pr->SiS_P3cc = BaseAddr + 0x1c; SiS_Pr->SiS_P3cd = BaseAddr + 0x1d; SiS_Pr->SiS_P3da = BaseAddr + 0x2a; SiS_Pr->SiS_Part1Port = BaseAddr + SIS_CRT2_PORT_04; } /*********************************************/ /* HELPER: GetSysFlags */ /*********************************************/ static void SiS_GetSysFlags(struct SiS_Private *SiS_Pr) { SiS_Pr->SiS_MyCR63 = 0x63; } /*********************************************/ /* HELPER: Init PCI & Engines */ /*********************************************/ static void SiSInitPCIetc(struct SiS_Private *SiS_Pr) { SiS_SetReg(SiS_Pr, SiS_Pr->SiS_P3c4, 0x20, 0xa1); /* - Enable 2D (0x40) * - Enable 3D (0x02) * - Enable 3D vertex command fetch (0x10) * - Enable 3D command parser (0x08) * - Enable 3D G/L transformation engine (0x80) */ SiS_SetRegOR(SiS_Pr, SiS_Pr->SiS_P3c4, 0x1E, 0xDA); } /*********************************************/ /* HELPER: SET SEGMENT REGISTERS */ /*********************************************/ static void SiS_SetSegRegLower(struct SiS_Private *SiS_Pr, unsigned short value) { unsigned short temp; value &= 0x00ff; temp = SiS_GetRegByte(SiS_Pr, SiS_Pr->SiS_P3cb) & 0xf0; temp |= (value >> 4); SiS_SetRegByte(SiS_Pr, SiS_Pr->SiS_P3cb, temp); temp = SiS_GetRegByte(SiS_Pr, SiS_Pr->SiS_P3cd) & 0xf0; temp |= (value & 0x0f); SiS_SetRegByte(SiS_Pr, SiS_Pr->SiS_P3cd, temp); } static void SiS_SetSegRegUpper(struct SiS_Private *SiS_Pr, unsigned short value) { unsigned short temp; value &= 0x00ff; temp = SiS_GetRegByte(SiS_Pr, SiS_Pr->SiS_P3cb) & 0x0f; temp |= (value & 0xf0); SiS_SetRegByte(SiS_Pr, SiS_Pr->SiS_P3cb, temp); temp = SiS_GetRegByte(SiS_Pr, SiS_Pr->SiS_P3cd) & 0x0f; temp |= (value << 4); SiS_SetRegByte(SiS_Pr, SiS_Pr->SiS_P3cd, temp); } static void SiS_SetSegmentReg(struct SiS_Private *SiS_Pr, unsigned short value) { SiS_SetSegRegLower(SiS_Pr, value); SiS_SetSegRegUpper(SiS_Pr, value); } static void SiS_ResetSegmentReg(struct SiS_Private *SiS_Pr) { SiS_SetSegmentReg(SiS_Pr, 0); } static void SiS_SetSegmentRegOver(struct SiS_Private *SiS_Pr, unsigned short value) { unsigned short temp = value >> 8; temp &= 0x07; temp |= (temp << 4); SiS_SetReg(SiS_Pr, SiS_Pr->SiS_P3c4, 0x1d, temp); SiS_SetSegmentReg(SiS_Pr, value); } static void SiS_ResetSegmentRegOver(struct SiS_Private *SiS_Pr) { SiS_SetSegmentRegOver(SiS_Pr, 0); } static void SiS_ResetSegmentRegisters(struct SiS_Private *SiS_Pr) { SiS_ResetSegmentReg(SiS_Pr); SiS_ResetSegmentRegOver(SiS_Pr); } /*********************************************/ /* HELPER: SearchModeID */ /*********************************************/ static int SiS_SearchModeID(struct SiS_Private *SiS_Pr, unsigned short *ModeNo, unsigned short *ModeIdIndex) { if ((*ModeNo) <= 0x13) { if ((*ModeNo) != 0x03) return 0; (*ModeIdIndex) = 0; } else { for (*ModeIdIndex = 0;; (*ModeIdIndex)++) { if (SiS_Pr->SiS_EModeIDTable[*ModeIdIndex].Ext_ModeID == (*ModeNo)) break; if (SiS_Pr->SiS_EModeIDTable[*ModeIdIndex].Ext_ModeID == 0xFF) return 0; } } return 1; } /*********************************************/ /* HELPER: ENABLE CRT1 */ /*********************************************/ static void SiS_HandleCRT1(struct SiS_Private *SiS_Pr) { /* Enable CRT1 gating */ SiS_SetRegAND(SiS_Pr, SiS_Pr->SiS_P3d4, SiS_Pr->SiS_MyCR63, 0xbf); } /*********************************************/ /* HELPER: GetColorDepth */ /*********************************************/ static unsigned short SiS_GetColorDepth(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex) { static const unsigned short ColorDepth[6] = { 1, 2, 4, 4, 6, 8 }; unsigned short modeflag; short index; if (ModeNo <= 0x13) { modeflag = SiS_Pr->SiS_SModeIDTable[ModeIdIndex].St_ModeFlag; } else { modeflag = SiS_Pr->SiS_EModeIDTable[ModeIdIndex].Ext_ModeFlag; } index = (modeflag & ModeTypeMask) - ModeEGA; if (index < 0) index = 0; return ColorDepth[index]; } /*********************************************/ /* HELPER: GetOffset */ /*********************************************/ static unsigned short SiS_GetOffset(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex, unsigned short rrti) { unsigned short xres, temp, colordepth, infoflag; infoflag = SiS_Pr->SiS_RefIndex[rrti].Ext_InfoFlag; xres = SiS_Pr->SiS_RefIndex[rrti].XRes; colordepth = SiS_GetColorDepth(SiS_Pr, ModeNo, ModeIdIndex); temp = xres / 16; if (infoflag & InterlaceMode) temp <<= 1; temp *= colordepth; if (xres % 16) temp += (colordepth >> 1); return temp; } /*********************************************/ /* SEQ */ /*********************************************/ static void SiS_SetSeqRegs(struct SiS_Private *SiS_Pr, unsigned short StandTableIndex) { unsigned char SRdata; int i; SiS_SetReg(SiS_Pr, SiS_Pr->SiS_P3c4, 0x00, 0x03); SRdata = SiS_Pr->SiS_StandTable[StandTableIndex].SR[0] | 0x20; SiS_SetReg(SiS_Pr, SiS_Pr->SiS_P3c4, 0x01, SRdata); for (i = 2; i <= 4; i++) { SRdata = SiS_Pr->SiS_StandTable[StandTableIndex].SR[i - 1]; SiS_SetReg(SiS_Pr, SiS_Pr->SiS_P3c4, i, SRdata); } } /*********************************************/ /* MISC */ /*********************************************/ static void SiS_SetMiscRegs(struct SiS_Private *SiS_Pr, unsigned short StandTableIndex) { unsigned char Miscdata = SiS_Pr->SiS_StandTable[StandTableIndex].MISC; SiS_SetRegByte(SiS_Pr, SiS_Pr->SiS_P3c2, Miscdata); } /*********************************************/ /* CRTC */ /*********************************************/ static void SiS_SetCRTCRegs(struct SiS_Private *SiS_Pr, unsigned short StandTableIndex) { unsigned char CRTCdata; unsigned short i; SiS_SetRegAND(SiS_Pr, SiS_Pr->SiS_P3d4, 0x11, 0x7f); for (i = 0; i <= 0x18; i++) { CRTCdata = SiS_Pr->SiS_StandTable[StandTableIndex].CRTC[i]; SiS_SetReg(SiS_Pr, SiS_Pr->SiS_P3d4, i, CRTCdata); } } /*********************************************/ /* ATT */ /*********************************************/ static void SiS_SetATTRegs(struct SiS_Private *SiS_Pr, unsigned short StandTableIndex) { unsigned char ARdata; unsigned short i; for (i = 0; i <= 0x13; i++) { ARdata = SiS_Pr->SiS_StandTable[StandTableIndex].ATTR[i]; SiS_GetRegByte(SiS_Pr, SiS_Pr->SiS_P3da); SiS_SetRegByte(SiS_Pr, SiS_Pr->SiS_P3c0, i); SiS_SetRegByte(SiS_Pr, SiS_Pr->SiS_P3c0, ARdata); } SiS_GetRegByte(SiS_Pr, SiS_Pr->SiS_P3da); SiS_SetRegByte(SiS_Pr, SiS_Pr->SiS_P3c0, 0x14); SiS_SetRegByte(SiS_Pr, SiS_Pr->SiS_P3c0, 0x00); SiS_GetRegByte(SiS_Pr, SiS_Pr->SiS_P3da); SiS_SetRegByte(SiS_Pr, SiS_Pr->SiS_P3c0, 0x20); SiS_GetRegByte(SiS_Pr, SiS_Pr->SiS_P3da); } /*********************************************/ /* GRC */ /*********************************************/ static void SiS_SetGRCRegs(struct SiS_Private *SiS_Pr, unsigned short StandTableIndex) { unsigned char GRdata; unsigned short i; for (i = 0; i <= 0x08; i++) { GRdata = SiS_Pr->SiS_StandTable[StandTableIndex].GRC[i]; SiS_SetReg(SiS_Pr, SiS_Pr->SiS_P3ce, i, GRdata); } if (SiS_Pr->SiS_ModeType > ModeVGA) { /* 256 color disable */ SiS_SetRegAND(SiS_Pr, SiS_Pr->SiS_P3ce, 0x05, 0xBF); } } /*********************************************/ /* CLEAR EXTENDED REGISTERS */ /*********************************************/ static void SiS_ClearExt1Regs(struct SiS_Private *SiS_Pr, unsigned short ModeNo) { int i; for (i = 0x0A; i <= 0x0E; i++) { SiS_SetReg(SiS_Pr, SiS_Pr->SiS_P3c4, i, 0x00); } SiS_SetRegAND(SiS_Pr, SiS_Pr->SiS_P3c4, 0x37, 0xFE); } /*********************************************/ /* Get rate index */ /*********************************************/ static unsigned short SiS_GetRatePtr(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex) { unsigned short rrti, i, index, temp; if (ModeNo <= 0x13) return 0xFFFF; index = SiS_GetReg(SiS_Pr, SiS_Pr->SiS_P3d4, 0x33) & 0x0F; if (index > 0) index--; rrti = SiS_Pr->SiS_EModeIDTable[ModeIdIndex].REFindex; ModeNo = SiS_Pr->SiS_RefIndex[rrti].ModeID; i = 0; do { if (SiS_Pr->SiS_RefIndex[rrti + i].ModeID != ModeNo) break; temp = SiS_Pr->SiS_RefIndex[rrti + i].Ext_InfoFlag & ModeTypeMask; if (temp < SiS_Pr->SiS_ModeType) break; i++; index--; } while (index != 0xFFFF); i--; return (rrti + i); } /*********************************************/ /* SYNC */ /*********************************************/ static void SiS_SetCRT1Sync(struct SiS_Private *SiS_Pr, unsigned short rrti) { unsigned short sync = SiS_Pr->SiS_RefIndex[rrti].Ext_InfoFlag >> 8; sync &= 0xC0; sync |= 0x2f; SiS_SetRegByte(SiS_Pr, SiS_Pr->SiS_P3c2, sync); } /*********************************************/ /* CRTC/2 */ /*********************************************/ static void SiS_SetCRT1CRTC(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex, unsigned short rrti) { unsigned char index; unsigned short temp, i, j, modeflag; SiS_SetRegAND(SiS_Pr, SiS_Pr->SiS_P3d4, 0x11, 0x7f); modeflag = SiS_Pr->SiS_EModeIDTable[ModeIdIndex].Ext_ModeFlag; index = SiS_Pr->SiS_RefIndex[rrti].Ext_CRT1CRTC; for (i = 0, j = 0; i <= 7; i++, j++) { SiS_SetReg(SiS_Pr, SiS_Pr->SiS_P3d4, j, SiS_Pr->SiS_CRT1Table[index].CR[i]); } for (j = 0x10; i <= 10; i++, j++) { SiS_SetReg(SiS_Pr, SiS_Pr->SiS_P3d4, j, SiS_Pr->SiS_CRT1Table[index].CR[i]); } for (j = 0x15; i <= 12; i++, j++) { SiS_SetReg(SiS_Pr, SiS_Pr->SiS_P3d4, j, SiS_Pr->SiS_CRT1Table[index].CR[i]); } for (j = 0x0A; i <= 15; i++, j++) { SiS_SetReg(SiS_Pr, SiS_Pr->SiS_P3c4, j, SiS_Pr->SiS_CRT1Table[index].CR[i]); } temp = SiS_Pr->SiS_CRT1Table[index].CR[16] & 0xE0; SiS_SetReg(SiS_Pr, SiS_Pr->SiS_P3c4, 0x0E, temp); temp = ((SiS_Pr->SiS_CRT1Table[index].CR[16]) & 0x01) << 5; if (modeflag & DoubleScanMode) temp |= 0x80; SiS_SetRegANDOR(SiS_Pr, SiS_Pr->SiS_P3d4, 0x09, 0x5F, temp); if (SiS_Pr->SiS_ModeType > ModeVGA) SiS_SetReg(SiS_Pr, SiS_Pr->SiS_P3d4, 0x14, 0x4F); } /*********************************************/ /* OFFSET & PITCH */ /*********************************************/ /* (partly overruled by SetPitch() in XF86) */ /*********************************************/ static void SiS_SetCRT1Offset(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex, unsigned short rrti) { unsigned short du = SiS_GetOffset(SiS_Pr, ModeNo, ModeIdIndex, rrti); unsigned short infoflag = SiS_Pr->SiS_RefIndex[rrti].Ext_InfoFlag; unsigned short temp; temp = (du >> 8) & 0x0f; SiS_SetRegANDOR(SiS_Pr, SiS_Pr->SiS_P3c4, 0x0E, 0xF0, temp); SiS_SetReg(SiS_Pr, SiS_Pr->SiS_P3d4, 0x13, (du & 0xFF)); if (infoflag & InterlaceMode) du >>= 1; du <<= 5; temp = (du >> 8) & 0xff; if (du & 0xff) temp++; temp++; SiS_SetReg(SiS_Pr, SiS_Pr->SiS_P3c4, 0x10, temp); } /*********************************************/ /* VCLK */ /*********************************************/ static void SiS_SetCRT1VCLK(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short rrti) { unsigned short index = SiS_Pr->SiS_RefIndex[rrti].Ext_CRTVCLK; unsigned short clka = SiS_Pr->SiS_VCLKData[index].SR2B; unsigned short clkb = SiS_Pr->SiS_VCLKData[index].SR2C; SiS_SetRegAND(SiS_Pr, SiS_Pr->SiS_P3c4, 0x31, 0xCF); SiS_SetReg(SiS_Pr, SiS_Pr->SiS_P3c4, 0x2B, clka); SiS_SetReg(SiS_Pr, SiS_Pr->SiS_P3c4, 0x2C, clkb); SiS_SetReg(SiS_Pr, SiS_Pr->SiS_P3c4, 0x2D, 0x01); } /*********************************************/ /* FIFO */ /*********************************************/ static void SiS_SetCRT1FIFO_310(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short mi) { unsigned short modeflag = SiS_Pr->SiS_EModeIDTable[mi].Ext_ModeFlag; /* disable auto-threshold */ SiS_SetRegAND(SiS_Pr, SiS_Pr->SiS_P3c4, 0x3D, 0xFE); SiS_SetReg(SiS_Pr, SiS_Pr->SiS_P3c4, 0x08, 0xAE); SiS_SetRegAND(SiS_Pr, SiS_Pr->SiS_P3c4, 0x09, 0xF0); if (ModeNo <= 0x13) return; if ((!(modeflag & DoubleScanMode)) || (!(modeflag & HalfDCLK))) { SiS_SetReg(SiS_Pr, SiS_Pr->SiS_P3c4, 0x08, 0x34); SiS_SetRegOR(SiS_Pr, SiS_Pr->SiS_P3c4, 0x3D, 0x01); } } /*********************************************/ /* MODE REGISTERS */ /*********************************************/ static void SiS_SetVCLKState(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short rrti) { unsigned short data = 0, VCLK = 0, index = 0; if (ModeNo > 0x13) { index = SiS_Pr->SiS_RefIndex[rrti].Ext_CRTVCLK; VCLK = SiS_Pr->SiS_VCLKData[index].CLOCK; } if (VCLK >= 166) data |= 0x0c; SiS_SetRegANDOR(SiS_Pr, SiS_Pr->SiS_P3c4, 0x32, 0xf3, data); if (VCLK >= 166) SiS_SetRegAND(SiS_Pr, SiS_Pr->SiS_P3c4, 0x1f, 0xe7); /* DAC speed */ data = 0x03; if (VCLK >= 260) data = 0x00; else if (VCLK >= 160) data = 0x01; else if (VCLK >= 135) data = 0x02; SiS_SetRegANDOR(SiS_Pr, SiS_Pr->SiS_P3c4, 0x07, 0xF8, data); } static void SiS_SetCRT1ModeRegs(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex, unsigned short rrti) { unsigned short data, infoflag = 0, modeflag; if (ModeNo <= 0x13) modeflag = SiS_Pr->SiS_SModeIDTable[ModeIdIndex].St_ModeFlag; else { modeflag = SiS_Pr->SiS_EModeIDTable[ModeIdIndex].Ext_ModeFlag; infoflag = SiS_Pr->SiS_RefIndex[rrti].Ext_InfoFlag; } /* Disable DPMS */ SiS_SetRegAND(SiS_Pr, SiS_Pr->SiS_P3c4, 0x1F, 0x3F); data = 0; if (ModeNo > 0x13) { if (SiS_Pr->SiS_ModeType > ModeEGA) { data |= 0x02; data |= ((SiS_Pr->SiS_ModeType - ModeVGA) << 2); } if (infoflag & InterlaceMode) data |= 0x20; } SiS_SetRegANDOR(SiS_Pr, SiS_Pr->SiS_P3c4, 0x06, 0xC0, data); data = 0; if (infoflag & InterlaceMode) { /* data = (Hsync / 8) - ((Htotal / 8) / 2) + 3 */ unsigned short hrs = (SiS_GetReg(SiS_Pr, SiS_Pr->SiS_P3d4, 0x04) | ((SiS_GetReg(SiS_Pr, SiS_Pr->SiS_P3c4, 0x0b) & 0xc0) << 2)) - 3; unsigned short hto = (SiS_GetReg(SiS_Pr, SiS_Pr->SiS_P3d4, 0x00) | ((SiS_GetReg(SiS_Pr, SiS_Pr->SiS_P3c4, 0x0b) & 0x03) << 8)) + 5; data = hrs - (hto >> 1) + 3; } SiS_SetReg(SiS_Pr, SiS_Pr->SiS_P3d4, 0x19, (data & 0xFF)); SiS_SetRegANDOR(SiS_Pr, SiS_Pr->SiS_P3d4, 0x1a, 0xFC, (data >> 8)); if (modeflag & HalfDCLK) SiS_SetRegOR(SiS_Pr, SiS_Pr->SiS_P3c4, 0x01, 0x08); data = 0; if (modeflag & LineCompareOff) data = 0x08; SiS_SetRegANDOR(SiS_Pr, SiS_Pr->SiS_P3c4, 0x0F, 0xB7, data); if ((SiS_Pr->SiS_ModeType == ModeEGA) && (ModeNo > 0x13)) SiS_SetRegOR(SiS_Pr, SiS_Pr->SiS_P3c4, 0x0F, 0x40); SiS_SetRegAND(SiS_Pr, SiS_Pr->SiS_P3c4, 0x31, 0xfb); data = 0x60; if (SiS_Pr->SiS_ModeType != ModeText) { data ^= 0x60; if (SiS_Pr->SiS_ModeType != ModeEGA) data ^= 0xA0; } SiS_SetRegANDOR(SiS_Pr, SiS_Pr->SiS_P3c4, 0x21, 0x1F, data); SiS_SetVCLKState(SiS_Pr, ModeNo, rrti); if (SiS_GetReg(SiS_Pr, SiS_Pr->SiS_P3d4, 0x31) & 0x40) SiS_SetReg(SiS_Pr, SiS_Pr->SiS_P3d4, 0x52, 0x2c); else SiS_SetReg(SiS_Pr, SiS_Pr->SiS_P3d4, 0x52, 0x6c); } /*********************************************/ /* LOAD DAC */ /*********************************************/ static void SiS_WriteDAC(struct SiS_Private *SiS_Pr, unsigned long DACData, unsigned short shiftflag, unsigned short dl, unsigned short ah, unsigned short al, unsigned short dh) { unsigned short d1, d2, d3; switch (dl) { case 0: d1 = dh; d2 = ah; d3 = al; break; case 1: d1 = ah; d2 = al; d3 = dh; break; default: d1 = al; d2 = dh; d3 = ah; } SiS_SetRegByte(SiS_Pr, DACData, (d1 << shiftflag)); SiS_SetRegByte(SiS_Pr, DACData, (d2 << shiftflag)); SiS_SetRegByte(SiS_Pr, DACData, (d3 << shiftflag)); } static void SiS_LoadDAC(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short mi) { unsigned short data, data2, time, i, j, k, m, n, o; unsigned short si, di, bx, sf; unsigned long DACAddr, DACData; const unsigned char *table = NULL; if (ModeNo < 0x13) data = SiS_Pr->SiS_SModeIDTable[mi].St_ModeFlag; else data = SiS_Pr->SiS_EModeIDTable[mi].Ext_ModeFlag; data &= DACInfoFlag; j = time = 64; if (data == 0x00) table = SiS_MDA_DAC; else if (data == 0x08) table = SiS_CGA_DAC; else if (data == 0x10) table = SiS_EGA_DAC; else { j = 16; time = 256; table = SiS_VGA_DAC; } DACAddr = SiS_Pr->SiS_P3c8; DACData = SiS_Pr->SiS_P3c9; sf = 0; SiS_SetRegByte(SiS_Pr, SiS_Pr->SiS_P3c6, 0xFF); SiS_SetRegByte(SiS_Pr, DACAddr, 0x00); for (i = 0; i < j; i++) { data = table[i]; for (k = 0; k < 3; k++) { data2 = 0; if (data & 0x01) data2 += 0x2A; if (data & 0x02) data2 += 0x15; SiS_SetRegByte(SiS_Pr, DACData, (data2 << sf)); data >>= 2; } } if (time == 256) { for (i = 16; i < 32; i++) { data = table[i] << sf; for (k = 0; k < 3; k++) SiS_SetRegByte(SiS_Pr, DACData, data); } si = 32; for (m = 0; m < 9; m++) { di = si; bx = si + 4; for (n = 0; n < 3; n++) { for (o = 0; o < 5; o++) { SiS_WriteDAC(SiS_Pr, DACData, sf, n, table[di], table[bx], table[si]); si++; } si -= 2; for (o = 0; o < 3; o++) { SiS_WriteDAC(SiS_Pr, DACData, sf, n, table[di], table[si], table[bx]); si--; } } si += 5; } } } /*********************************************/ /* SET CRT1 REGISTER GROUP */ /*********************************************/ static void SiS_SetCRT1Group(struct SiS_Private *SiS_Pr, unsigned short ModeNo, unsigned short ModeIdIndex) { unsigned short StandTableIndex, rrti; SiS_Pr->SiS_CRT1Mode = ModeNo; if (ModeNo <= 0x13) StandTableIndex = 0; else StandTableIndex = 1; SiS_ResetSegmentRegisters(SiS_Pr); SiS_SetSeqRegs(SiS_Pr, StandTableIndex); SiS_SetMiscRegs(SiS_Pr, StandTableIndex); SiS_SetCRTCRegs(SiS_Pr, StandTableIndex); SiS_SetATTRegs(SiS_Pr, StandTableIndex); SiS_SetGRCRegs(SiS_Pr, StandTableIndex); SiS_ClearExt1Regs(SiS_Pr, ModeNo); rrti = SiS_GetRatePtr(SiS_Pr, ModeNo, ModeIdIndex); if (rrti != 0xFFFF) { SiS_SetCRT1Sync(SiS_Pr, rrti); SiS_SetCRT1CRTC(SiS_Pr, ModeNo, ModeIdIndex, rrti); SiS_SetCRT1Offset(SiS_Pr, ModeNo, ModeIdIndex, rrti); SiS_SetCRT1VCLK(SiS_Pr, ModeNo, rrti); } SiS_SetCRT1FIFO_310(SiS_Pr, ModeNo, ModeIdIndex); SiS_SetCRT1ModeRegs(SiS_Pr, ModeNo, ModeIdIndex, rrti); SiS_LoadDAC(SiS_Pr, ModeNo, ModeIdIndex); SiS_DisplayOn(SiS_Pr); } /*********************************************/ /* SiSSetMode() */ /*********************************************/ int SiSUSBSetMode(struct SiS_Private *SiS_Pr, unsigned short ModeNo) { unsigned short ModeIdIndex; unsigned long BaseAddr = SiS_Pr->IOAddress; SiSUSB_InitPtr(SiS_Pr); SiSUSBRegInit(SiS_Pr, BaseAddr); SiS_GetSysFlags(SiS_Pr); if (!(SiS_SearchModeID(SiS_Pr, &ModeNo, &ModeIdIndex))) return 0; SiS_SetReg(SiS_Pr, SiS_Pr->SiS_P3c4, 0x05, 0x86); SiSInitPCIetc(SiS_Pr); ModeNo &= 0x7f; SiS_Pr->SiS_ModeType = SiS_Pr->SiS_EModeIDTable[ModeIdIndex].Ext_ModeFlag & ModeTypeMask; SiS_Pr->SiS_SetFlag = LowModeTests; /* Set mode on CRT1 */ SiS_SetCRT1Group(SiS_Pr, ModeNo, ModeIdIndex); SiS_HandleCRT1(SiS_Pr); SiS_DisplayOn(SiS_Pr); SiS_SetRegByte(SiS_Pr, SiS_Pr->SiS_P3c6, 0xFF); /* Store mode number */ SiS_SetReg(SiS_Pr, SiS_Pr->SiS_P3d4, 0x34, ModeNo); return 1; } int SiSUSBSetVESAMode(struct SiS_Private *SiS_Pr, unsigned short VModeNo) { unsigned short ModeNo = 0; int i; SiSUSB_InitPtr(SiS_Pr); if (VModeNo == 0x03) { ModeNo = 0x03; } else { i = 0; do { if (SiS_Pr->SiS_EModeIDTable[i].Ext_VESAID == VModeNo) { ModeNo = SiS_Pr->SiS_EModeIDTable[i].Ext_ModeID; break; } } while (SiS_Pr->SiS_EModeIDTable[i++].Ext_ModeID != 0xff); } if (!ModeNo) return 0; return SiSUSBSetMode(SiS_Pr, ModeNo); } #endif /* INCL_SISUSB_CON */
gpl-3.0
orsonwang/shadowsocks-android
src/main/jni/openssl/crypto/aes/aes_cbc.c
740
2885
/* crypto/aes/aes_cbc.c -*- mode:C; c-file-style: "eay" -*- */ /* ==================================================================== * Copyright (c) 1998-2002 The OpenSSL Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * openssl-core@openssl.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.openssl.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * ==================================================================== * */ #include <openssl/aes.h> #include <openssl/modes.h> void AES_cbc_encrypt(const unsigned char *in, unsigned char *out, size_t len, const AES_KEY *key, unsigned char *ivec, const int enc) { if (enc) CRYPTO_cbc128_encrypt(in,out,len,key,ivec,(block128_f)AES_encrypt); else CRYPTO_cbc128_decrypt(in,out,len,key,ivec,(block128_f)AES_decrypt); }
gpl-3.0
chuncky/nuc900kernel
linux-2.6.35.4/drivers/net/wireless/rt2x00/rt2x00pci.c
757
9108
/* Copyright (C) 2004 - 2009 Ivo van Doorn <IvDoorn@gmail.com> <http://rt2x00.serialmonkey.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /* Module: rt2x00pci Abstract: rt2x00 generic pci device routines. */ #include <linux/dma-mapping.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/pci.h> #include <linux/slab.h> #include "rt2x00.h" #include "rt2x00pci.h" /* * Register access. */ int rt2x00pci_regbusy_read(struct rt2x00_dev *rt2x00dev, const unsigned int offset, const struct rt2x00_field32 field, u32 *reg) { unsigned int i; if (!test_bit(DEVICE_STATE_PRESENT, &rt2x00dev->flags)) return 0; for (i = 0; i < REGISTER_BUSY_COUNT; i++) { rt2x00pci_register_read(rt2x00dev, offset, reg); if (!rt2x00_get_field32(*reg, field)) return 1; udelay(REGISTER_BUSY_DELAY); } ERROR(rt2x00dev, "Indirect register access failed: " "offset=0x%.08x, value=0x%.08x\n", offset, *reg); *reg = ~0; return 0; } EXPORT_SYMBOL_GPL(rt2x00pci_regbusy_read); /* * TX data handlers. */ int rt2x00pci_write_tx_data(struct queue_entry *entry, struct txentry_desc *txdesc) { struct rt2x00_dev *rt2x00dev = entry->queue->rt2x00dev; /* * This should not happen, we already checked the entry * was ours. When the hardware disagrees there has been * a queue corruption! */ if (unlikely(rt2x00dev->ops->lib->get_entry_state(entry))) { ERROR(rt2x00dev, "Corrupt queue %d, accessing entry which is not ours.\n" "Please file bug report to %s.\n", entry->queue->qid, DRV_PROJECT); return -EINVAL; } return 0; } EXPORT_SYMBOL_GPL(rt2x00pci_write_tx_data); /* * TX/RX data handlers. */ void rt2x00pci_rxdone(struct rt2x00_dev *rt2x00dev) { struct data_queue *queue = rt2x00dev->rx; struct queue_entry *entry; struct queue_entry_priv_pci *entry_priv; struct skb_frame_desc *skbdesc; while (1) { entry = rt2x00queue_get_entry(queue, Q_INDEX); entry_priv = entry->priv_data; if (rt2x00dev->ops->lib->get_entry_state(entry)) break; /* * Fill in desc fields of the skb descriptor */ skbdesc = get_skb_frame_desc(entry->skb); skbdesc->desc = entry_priv->desc; skbdesc->desc_len = entry->queue->desc_size; /* * Send the frame to rt2x00lib for further processing. */ rt2x00lib_rxdone(rt2x00dev, entry); } } EXPORT_SYMBOL_GPL(rt2x00pci_rxdone); /* * Device initialization handlers. */ static int rt2x00pci_alloc_queue_dma(struct rt2x00_dev *rt2x00dev, struct data_queue *queue) { struct queue_entry_priv_pci *entry_priv; void *addr; dma_addr_t dma; unsigned int i; /* * Allocate DMA memory for descriptor and buffer. */ addr = dma_alloc_coherent(rt2x00dev->dev, queue->limit * queue->desc_size, &dma, GFP_KERNEL | GFP_DMA); if (!addr) return -ENOMEM; memset(addr, 0, queue->limit * queue->desc_size); /* * Initialize all queue entries to contain valid addresses. */ for (i = 0; i < queue->limit; i++) { entry_priv = queue->entries[i].priv_data; entry_priv->desc = addr + i * queue->desc_size; entry_priv->desc_dma = dma + i * queue->desc_size; } return 0; } static void rt2x00pci_free_queue_dma(struct rt2x00_dev *rt2x00dev, struct data_queue *queue) { struct queue_entry_priv_pci *entry_priv = queue->entries[0].priv_data; if (entry_priv->desc) dma_free_coherent(rt2x00dev->dev, queue->limit * queue->desc_size, entry_priv->desc, entry_priv->desc_dma); entry_priv->desc = NULL; } int rt2x00pci_initialize(struct rt2x00_dev *rt2x00dev) { struct data_queue *queue; int status; /* * Allocate DMA */ queue_for_each(rt2x00dev, queue) { status = rt2x00pci_alloc_queue_dma(rt2x00dev, queue); if (status) goto exit; } /* * Register interrupt handler. */ status = request_irq(rt2x00dev->irq, rt2x00dev->ops->lib->irq_handler, IRQF_SHARED, rt2x00dev->name, rt2x00dev); if (status) { ERROR(rt2x00dev, "IRQ %d allocation failed (error %d).\n", rt2x00dev->irq, status); goto exit; } return 0; exit: queue_for_each(rt2x00dev, queue) rt2x00pci_free_queue_dma(rt2x00dev, queue); return status; } EXPORT_SYMBOL_GPL(rt2x00pci_initialize); void rt2x00pci_uninitialize(struct rt2x00_dev *rt2x00dev) { struct data_queue *queue; /* * Free irq line. */ free_irq(rt2x00dev->irq, rt2x00dev); /* * Free DMA */ queue_for_each(rt2x00dev, queue) rt2x00pci_free_queue_dma(rt2x00dev, queue); } EXPORT_SYMBOL_GPL(rt2x00pci_uninitialize); /* * PCI driver handlers. */ static void rt2x00pci_free_reg(struct rt2x00_dev *rt2x00dev) { kfree(rt2x00dev->rf); rt2x00dev->rf = NULL; kfree(rt2x00dev->eeprom); rt2x00dev->eeprom = NULL; if (rt2x00dev->csr.base) { iounmap(rt2x00dev->csr.base); rt2x00dev->csr.base = NULL; } } static int rt2x00pci_alloc_reg(struct rt2x00_dev *rt2x00dev) { struct pci_dev *pci_dev = to_pci_dev(rt2x00dev->dev); rt2x00dev->csr.base = pci_ioremap_bar(pci_dev, 0); if (!rt2x00dev->csr.base) goto exit; rt2x00dev->eeprom = kzalloc(rt2x00dev->ops->eeprom_size, GFP_KERNEL); if (!rt2x00dev->eeprom) goto exit; rt2x00dev->rf = kzalloc(rt2x00dev->ops->rf_size, GFP_KERNEL); if (!rt2x00dev->rf) goto exit; return 0; exit: ERROR_PROBE("Failed to allocate registers.\n"); rt2x00pci_free_reg(rt2x00dev); return -ENOMEM; } int rt2x00pci_probe(struct pci_dev *pci_dev, const struct pci_device_id *id) { struct rt2x00_ops *ops = (struct rt2x00_ops *)id->driver_data; struct ieee80211_hw *hw; struct rt2x00_dev *rt2x00dev; int retval; retval = pci_request_regions(pci_dev, pci_name(pci_dev)); if (retval) { ERROR_PROBE("PCI request regions failed.\n"); return retval; } retval = pci_enable_device(pci_dev); if (retval) { ERROR_PROBE("Enable device failed.\n"); goto exit_release_regions; } pci_set_master(pci_dev); if (pci_set_mwi(pci_dev)) ERROR_PROBE("MWI not available.\n"); if (dma_set_mask(&pci_dev->dev, DMA_BIT_MASK(32))) { ERROR_PROBE("PCI DMA not supported.\n"); retval = -EIO; goto exit_disable_device; } hw = ieee80211_alloc_hw(sizeof(struct rt2x00_dev), ops->hw); if (!hw) { ERROR_PROBE("Failed to allocate hardware.\n"); retval = -ENOMEM; goto exit_disable_device; } pci_set_drvdata(pci_dev, hw); rt2x00dev = hw->priv; rt2x00dev->dev = &pci_dev->dev; rt2x00dev->ops = ops; rt2x00dev->hw = hw; rt2x00dev->irq = pci_dev->irq; rt2x00dev->name = pci_name(pci_dev); rt2x00_set_chip_intf(rt2x00dev, RT2X00_CHIP_INTF_PCI); retval = rt2x00pci_alloc_reg(rt2x00dev); if (retval) goto exit_free_device; retval = rt2x00lib_probe_dev(rt2x00dev); if (retval) goto exit_free_reg; return 0; exit_free_reg: rt2x00pci_free_reg(rt2x00dev); exit_free_device: ieee80211_free_hw(hw); exit_disable_device: if (retval != -EBUSY) pci_disable_device(pci_dev); exit_release_regions: pci_release_regions(pci_dev); pci_set_drvdata(pci_dev, NULL); return retval; } EXPORT_SYMBOL_GPL(rt2x00pci_probe); void rt2x00pci_remove(struct pci_dev *pci_dev) { struct ieee80211_hw *hw = pci_get_drvdata(pci_dev); struct rt2x00_dev *rt2x00dev = hw->priv; /* * Free all allocated data. */ rt2x00lib_remove_dev(rt2x00dev); rt2x00pci_free_reg(rt2x00dev); ieee80211_free_hw(hw); /* * Free the PCI device data. */ pci_set_drvdata(pci_dev, NULL); pci_disable_device(pci_dev); pci_release_regions(pci_dev); } EXPORT_SYMBOL_GPL(rt2x00pci_remove); #ifdef CONFIG_PM int rt2x00pci_suspend(struct pci_dev *pci_dev, pm_message_t state) { struct ieee80211_hw *hw = pci_get_drvdata(pci_dev); struct rt2x00_dev *rt2x00dev = hw->priv; int retval; retval = rt2x00lib_suspend(rt2x00dev, state); if (retval) return retval; pci_save_state(pci_dev); pci_disable_device(pci_dev); return pci_set_power_state(pci_dev, pci_choose_state(pci_dev, state)); } EXPORT_SYMBOL_GPL(rt2x00pci_suspend); int rt2x00pci_resume(struct pci_dev *pci_dev) { struct ieee80211_hw *hw = pci_get_drvdata(pci_dev); struct rt2x00_dev *rt2x00dev = hw->priv; if (pci_set_power_state(pci_dev, PCI_D0) || pci_enable_device(pci_dev) || pci_restore_state(pci_dev)) { ERROR(rt2x00dev, "Failed to resume device.\n"); return -EIO; } return rt2x00lib_resume(rt2x00dev); } EXPORT_SYMBOL_GPL(rt2x00pci_resume); #endif /* CONFIG_PM */ /* * rt2x00pci module information. */ MODULE_AUTHOR(DRV_PROJECT); MODULE_VERSION(DRV_VERSION); MODULE_DESCRIPTION("rt2x00 pci library"); MODULE_LICENSE("GPL");
gpl-3.0
geminy/aidear
oss/linux/linux-4.7/drivers/misc/mic/bus/vop_bus.c
252
4989
/* * Intel MIC Platform Software Stack (MPSS) * * Copyright(c) 2016 Intel Corporation. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License, version 2, as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * The full GNU General Public License is included in this distribution in * the file called "COPYING". * * Intel Virtio Over PCIe (VOP) Bus driver. */ #include <linux/slab.h> #include <linux/module.h> #include <linux/idr.h> #include <linux/dma-mapping.h> #include "vop_bus.h" static ssize_t device_show(struct device *d, struct device_attribute *attr, char *buf) { struct vop_device *dev = dev_to_vop(d); return sprintf(buf, "0x%04x\n", dev->id.device); } static DEVICE_ATTR_RO(device); static ssize_t vendor_show(struct device *d, struct device_attribute *attr, char *buf) { struct vop_device *dev = dev_to_vop(d); return sprintf(buf, "0x%04x\n", dev->id.vendor); } static DEVICE_ATTR_RO(vendor); static ssize_t modalias_show(struct device *d, struct device_attribute *attr, char *buf) { struct vop_device *dev = dev_to_vop(d); return sprintf(buf, "vop:d%08Xv%08X\n", dev->id.device, dev->id.vendor); } static DEVICE_ATTR_RO(modalias); static struct attribute *vop_dev_attrs[] = { &dev_attr_device.attr, &dev_attr_vendor.attr, &dev_attr_modalias.attr, NULL, }; ATTRIBUTE_GROUPS(vop_dev); static inline int vop_id_match(const struct vop_device *dev, const struct vop_device_id *id) { if (id->device != dev->id.device && id->device != VOP_DEV_ANY_ID) return 0; return id->vendor == VOP_DEV_ANY_ID || id->vendor == dev->id.vendor; } /* * This looks through all the IDs a driver claims to support. If any of them * match, we return 1 and the kernel will call vop_dev_probe(). */ static int vop_dev_match(struct device *dv, struct device_driver *dr) { unsigned int i; struct vop_device *dev = dev_to_vop(dv); const struct vop_device_id *ids; ids = drv_to_vop(dr)->id_table; for (i = 0; ids[i].device; i++) if (vop_id_match(dev, &ids[i])) return 1; return 0; } static int vop_uevent(struct device *dv, struct kobj_uevent_env *env) { struct vop_device *dev = dev_to_vop(dv); return add_uevent_var(env, "MODALIAS=vop:d%08Xv%08X", dev->id.device, dev->id.vendor); } static int vop_dev_probe(struct device *d) { struct vop_device *dev = dev_to_vop(d); struct vop_driver *drv = drv_to_vop(dev->dev.driver); return drv->probe(dev); } static int vop_dev_remove(struct device *d) { struct vop_device *dev = dev_to_vop(d); struct vop_driver *drv = drv_to_vop(dev->dev.driver); drv->remove(dev); return 0; } static struct bus_type vop_bus = { .name = "vop_bus", .match = vop_dev_match, .dev_groups = vop_dev_groups, .uevent = vop_uevent, .probe = vop_dev_probe, .remove = vop_dev_remove, }; int vop_register_driver(struct vop_driver *driver) { driver->driver.bus = &vop_bus; return driver_register(&driver->driver); } EXPORT_SYMBOL_GPL(vop_register_driver); void vop_unregister_driver(struct vop_driver *driver) { driver_unregister(&driver->driver); } EXPORT_SYMBOL_GPL(vop_unregister_driver); static void vop_release_dev(struct device *d) { put_device(d); } struct vop_device * vop_register_device(struct device *pdev, int id, const struct dma_map_ops *dma_ops, struct vop_hw_ops *hw_ops, u8 dnode, struct mic_mw *aper, struct dma_chan *chan) { int ret; struct vop_device *vdev; vdev = kzalloc(sizeof(*vdev), GFP_KERNEL); if (!vdev) return ERR_PTR(-ENOMEM); vdev->dev.parent = pdev; vdev->id.device = id; vdev->id.vendor = VOP_DEV_ANY_ID; vdev->dev.archdata.dma_ops = (struct dma_map_ops *)dma_ops; vdev->dev.dma_mask = &vdev->dev.coherent_dma_mask; dma_set_mask(&vdev->dev, DMA_BIT_MASK(64)); vdev->dev.release = vop_release_dev; vdev->hw_ops = hw_ops; vdev->dev.bus = &vop_bus; vdev->dnode = dnode; vdev->aper = aper; vdev->dma_ch = chan; vdev->index = dnode - 1; dev_set_name(&vdev->dev, "vop-dev%u", vdev->index); /* * device_register() causes the bus infrastructure to look for a * matching driver. */ ret = device_register(&vdev->dev); if (ret) goto free_vdev; return vdev; free_vdev: kfree(vdev); return ERR_PTR(ret); } EXPORT_SYMBOL_GPL(vop_register_device); void vop_unregister_device(struct vop_device *dev) { device_unregister(&dev->dev); } EXPORT_SYMBOL_GPL(vop_unregister_device); static int __init vop_init(void) { return bus_register(&vop_bus); } static void __exit vop_exit(void) { bus_unregister(&vop_bus); } core_initcall(vop_init); module_exit(vop_exit); MODULE_AUTHOR("Intel Corporation"); MODULE_DESCRIPTION("Intel(R) VOP Bus driver"); MODULE_LICENSE("GPL v2");
gpl-3.0
k0nane/R915_kernel_GB
Kernel/fs/smbfs/getopt.c
2047
1655
/* * getopt.c */ #include <linux/kernel.h> #include <linux/string.h> #include <linux/net.h> #include "getopt.h" /** * smb_getopt - option parser * @caller: name of the caller, for error messages * @options: the options string * @opts: an array of &struct option entries controlling parser operations * @optopt: output; will contain the current option * @optarg: output; will contain the value (if one exists) * @flag: output; may be NULL; should point to a long for or'ing flags * @value: output; may be NULL; will be overwritten with the integer value * of the current argument. * * Helper to parse options on the format used by mount ("a=b,c=d,e,f"). * Returns opts->val if a matching entry in the 'opts' array is found, * 0 when no more tokens are found, -1 if an error is encountered. */ int smb_getopt(char *caller, char **options, struct option *opts, char **optopt, char **optarg, unsigned long *flag, unsigned long *value) { char *token; char *val; int i; do { if ((token = strsep(options, ",")) == NULL) return 0; } while (*token == '\0'); *optopt = token; *optarg = NULL; if ((val = strchr (token, '=')) != NULL) { *val++ = 0; if (value) *value = simple_strtoul(val, NULL, 0); *optarg = val; } for (i = 0; opts[i].name != NULL; i++) { if (!strcmp(opts[i].name, token)) { if (!opts[i].flag && (!val || !*val)) { printk("%s: the %s option requires an argument\n", caller, token); return -1; } if (flag && opts[i].flag) *flag |= opts[i].flag; return opts[i].val; } } printk("%s: Unrecognized mount option %s\n", caller, token); return -1; }
gpl-3.0
tmhorne/celtx
toolkit/components/remote/nsPhRemoteService.cpp
1
5341
/* * The contents of this file are subject to the Mozilla Public * License Version 1.1 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or * implied. See the License for the specific language governing * rights and limitations under the License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is Christopher Blizzard. * Portions created by Christopher Blizzard are Copyright (C) * Christopher Blizzard. All Rights Reserved. * * Contributor(s): * Adrian Mardare <amardare@qnx.com> * Max Feil <mfeil@qnx.com> */ #include <stdlib.h> #include <nsIWidget.h> #include <nsCOMPtr.h> #include "nsIGenericFactory.h" #include "nsPhRemoteService.h" #include "nsIServiceManager.h" #include "nsCRT.h" #ifdef MOZ_XUL_APP #include "nsICommandLineRunner.h" #include "nsXULAppAPI.h" #else #include "nsISuiteRemoteService.h" #endif #include <Pt.h> NS_IMPL_QUERY_INTERFACE2(nsPhRemoteService, nsIRemoteService, nsIObserver) NS_IMETHODIMP_(nsrefcnt) nsPhRemoteService::AddRef() { return 1; } NS_IMETHODIMP_(nsrefcnt) nsPhRemoteService::Release() { return 1; } NS_IMETHODIMP nsPhRemoteService::Startup(const char* aAppName, const char* aProfileName) { NS_ASSERTION(aAppName, "Don't pass a null appname!"); if (mIsInitialized) return NS_ERROR_ALREADY_INITIALIZED; mIsInitialized = PR_TRUE; mAppName = aAppName; ToLowerCase(mAppName); HandleCommandsFor(nsnull, nsnull); return NS_OK; } NS_IMETHODIMP nsPhRemoteService::RegisterWindow(nsIDOMWindow* aWindow) { return NS_OK; } NS_IMETHODIMP nsPhRemoteService::Shutdown() { if (!mIsInitialized) return NS_ERROR_NOT_INITIALIZED; mIsInitialized = PR_FALSE; return NS_OK; } NS_IMETHODIMP nsPhRemoteService::Observe(nsISupports* aSubject, const char *aTopic, const PRUnichar *aData) { // This can be xpcom-shutdown or quit-application, but it's the same either // way. Shutdown(); return NS_OK; } #define MOZ_REMOTE_MSG_TYPE 100 static void const * RemoteMsgHandler( PtConnectionServer_t *connection, void *user_data, unsigned long type, void const *msg, unsigned len, unsigned *reply_len ) { nsresult rv; if( type != MOZ_REMOTE_MSG_TYPE ) return NULL; /* we are given strings and we reply with strings */ char *response = NULL; // parse the command nsCOMPtr<nsICommandLineRunner> cmdline (do_CreateInstance("@mozilla.org/toolkit/command-line;1", &rv)); if (!NS_FAILED(rv)) { // 1) Make sure that it looks remotely valid with parens // 2) Treat ping() immediately and specially nsCAutoString command((char *)msg); PRInt32 p1, p2; p1 = command.FindChar('('); p2 = command.FindChar(')'); if (p1 != kNotFound && p2 != kNotFound && p1 != 0 && p2 >= p1) { command.Truncate(p1); command.Trim(" ", PR_TRUE, PR_TRUE); ToLowerCase(command); //printf("Processing xremote command: %s\n", command.get()); if (!command.EqualsLiteral("ping")) { char* argv[3] = {"dummyappname", "-remote", (char *)msg}; rv = cmdline->Init(3, argv, nsnull, nsICommandLine::STATE_REMOTE_EXPLICIT); if (!NS_FAILED(rv)) { rv = cmdline->Run(); if (NS_ERROR_ABORT == rv) response = "500 command not parseable"; if (NS_FAILED(rv)) response = "509 internal error"; } else response = "509 internal error"; } } else response = "500 command not parseable"; } else response = "509 internal error"; PtConnectionReply( connection, response ? strlen(response) : 0, response ); return ( void * ) 1; /* return any non NULL value to indicate we handled the message */ } static void client_connect( PtConnector_t *cntr, PtConnectionServer_t *csrvr, void *data ) { static PtConnectionMsgHandler_t handlers[] = { { 0, RemoteMsgHandler } }; PtConnectionAddMsgHandlers( csrvr, handlers, sizeof(handlers)/sizeof(handlers[0]) ); } void nsPhRemoteService::HandleCommandsFor( nsIWidget *aWidget, nsIWeakReference* aWindow ) { static PRBool ConnectorCreated = PR_FALSE; ///* ATENTIE */ printf( "aProgram=%s aProfile=%s aWidget=%p\n", aProgram?aProgram:"NULL", aProfile?aProfile:"NULL", aWidget ); if( !ConnectorCreated ) { char RemoteServerName[128]; sprintf( RemoteServerName, "%s_RemoteServer", (char *) mAppName.get() ); /* create a connector for the remote control */ PtConnectorCreate( RemoteServerName, client_connect, NULL ); ConnectorCreated = PR_TRUE; } return; } // {C0773E90-5799-4eff-AD03-3EBCD85624AC} #define NS_REMOTESERVICE_CID \ { 0xc0773e90, 0x5799, 0x4eff, { 0xad, 0x3, 0x3e, 0xbc, 0xd8, 0x56, 0x24, 0xac } } NS_GENERIC_FACTORY_CONSTRUCTOR(nsPhRemoteService) static const nsModuleComponentInfo components[] = { { "Remote Service", NS_REMOTESERVICE_CID, "@mozilla.org/toolkit/remote-service;1", nsPhRemoteServiceConstructor } }; NS_IMPL_NSGETMODULE(RemoteServiceModule, components)
mpl-2.0
bryantabaird/cs6660
Include/eigen/bench/spbench/spbenchsolver.cpp
259
3302
#include <bench/spbench/spbenchsolver.h> void bench_printhelp() { cout<< " \nbenchsolver : performs a benchmark of all the solvers available in Eigen \n\n"; cout<< " MATRIX FOLDER : \n"; cout<< " The matrices for the benchmark should be collected in a folder specified with an environment variable EIGEN_MATRIXDIR \n"; cout<< " The matrices are stored using the matrix market coordinate format \n"; cout<< " The matrix and associated right-hand side (rhs) files are named respectively \n"; cout<< " as MatrixName.mtx and MatrixName_b.mtx. If the rhs does not exist, a random one is generated. \n"; cout<< " If a matrix is SPD, the matrix should be named as MatrixName_SPD.mtx \n"; cout<< " If a true solution exists, it should be named as MatrixName_x.mtx; \n" ; cout<< " it will be used to compute the norm of the error relative to the computed solutions\n\n"; cout<< " OPTIONS : \n"; cout<< " -h or --help \n print this help and return\n\n"; cout<< " -d matrixdir \n Use matrixdir as the matrix folder instead of the one specified in the environment variable EIGEN_MATRIXDIR\n\n"; cout<< " -o outputfile.xml \n Output the statistics to a xml file \n\n"; cout<< " --eps <RelErr> Sets the relative tolerance for iterative solvers (default 1e-08) \n\n"; cout<< " --maxits <MaxIts> Sets the maximum number of iterations (default 1000) \n\n"; } int main(int argc, char ** args) { bool help = ( get_options(argc, args, "-h") || get_options(argc, args, "--help") ); if(help) { bench_printhelp(); return 0; } // Get the location of the test matrices string matrix_dir; if (!get_options(argc, args, "-d", &matrix_dir)) { if(getenv("EIGEN_MATRIXDIR") == NULL){ std::cerr << "Please, specify the location of the matrices with -d mat_folder or the environment variable EIGEN_MATRIXDIR \n"; std::cerr << " Run with --help to see the list of all the available options \n"; return -1; } matrix_dir = getenv("EIGEN_MATRIXDIR"); } std::ofstream statbuf; string statFile ; // Get the file to write the statistics bool statFileExists = get_options(argc, args, "-o", &statFile); if(statFileExists) { statbuf.open(statFile.c_str(), std::ios::out); if(statbuf.good()){ statFileExists = true; printStatheader(statbuf); statbuf.close(); } else std::cerr << "Unable to open the provided file for writting... \n"; } // Get the maximum number of iterations and the tolerance int maxiters = 1000; double tol = 1e-08; string inval; if (get_options(argc, args, "--eps", &inval)) tol = atof(inval.c_str()); if(get_options(argc, args, "--maxits", &inval)) maxiters = atoi(inval.c_str()); string current_dir; // Test the real-arithmetics matrices Browse_Matrices<double>(matrix_dir, statFileExists, statFile,maxiters, tol); // Test the complex-arithmetics matrices Browse_Matrices<std::complex<double> >(matrix_dir, statFileExists, statFile, maxiters, tol); if(statFileExists) { statbuf.open(statFile.c_str(), std::ios::app); statbuf << "</BENCH> \n"; cout << "\n Output written in " << statFile << " ...\n"; statbuf.close(); } return 0; }
mpl-2.0
evarty/Microcontroller
ARM/SAMD20XPlainedPRO/ASFFiles/drivers/trng/unit_test/unit_test.c
1
8389
/** * \file * * \brief SAM True Random Number Generator (TRNG) Unit test * * Copyright (C) 2014-2015 Atmel Corporation. All rights reserved. * * \asf_license_start * * \page License * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name of Atmel may not be used to endorse or promote products derived * from this software without specific prior written permission. * * 4. This software may only be redistributed and used in connection with an * Atmel microcontroller product. * * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * \asf_license_stop * */ /** * \mainpage SAM TRNG Unit Test * See \ref appdoc_main "here" for project documentation. * \copydetails appdoc_preface * * * \page appdoc_preface Overview * This unit test carries out tests for the TRNG driver. * It consists of test cases for the following functionalities: * - Test for TRNG polling mode read. * - Test for TRNG callback mode read. */ /** * \page appdoc_main SAM TRNG Unit Test * * Overview: * - \ref appdoc_sam0_trng_unit_test_intro * - \ref appdoc_sam0_trng_unit_test_setup * - \ref appdoc_sam0_trng_unit_test_usage * - \ref appdoc_sam0_trng_unit_test_compinfo * - \ref appdoc_sam0_trng_unit_test_contactinfo * * \section appdoc_sam0_trng_unit_test_intro Introduction * \copydetails appdoc_preface * * The following kit is required for carrying out the test: * - SAM L21 Xplained Pro board * - SAM L22 Xplained Pro board * * \section appdoc_sam0_trng_unit_test_setup Setup * There is no special requirement. * * To run the test: * - Connect the SAM Xplained Pro board to the computer using a * micro USB cable. * - Open the virtual COM port in a terminal application. * \note The USB composite firmware running on the Embedded Debugger (EDBG) * will enumerate as debugger, virtual COM port, and EDBG data * gateway. * - Build the project, program the target and run the application. * The terminal shows the results of the unit test. * * \section appdoc_sam0_trng_unit_test_usage Usage * - Polling mode read is tested. * - Callback mode read is tested. * * \section appdoc_sam0_trng_unit_test_compinfo Compilation Info * This software was written for the GNU GCC and IAR for ARM. * Other compilers may or may not work. * * \section appdoc_sam0_trng_unit_test_contactinfo Contact Information * For further information, visit * <a href="http://www.atmel.com">http://www.atmel.com</a>. */ /* * Support and FAQ: visit <a href="http://www.atmel.com/design-support/">Atmel Support</a> */ #include <asf.h> #include <stdio_serial.h> #include <string.h> #include "conf_test.h" /* Structure for UART module connected to EDBG (used for unit test output) */ struct usart_module cdc_uart_module; /* Structure for TRNG module */ struct trng_module trng_instance; /* Interrupt flag used during callback test */ volatile bool interrupt_flag = false; /** * \internal * \brief TRNG callback function * * Called by TRNG driver on interrupt detection. * * \param module Pointer to the TRNG module (not used) */ static void trng_complete_callback(struct trng_module *const module_inst) { UNUSED(module_inst); interrupt_flag = true; } /** * \brief Initialize the USART for unit test * * Initializes the SERCOM USART used for sending the unit test status to the * computer via the EDBG CDC gateway. */ static void cdc_uart_init(void) { struct usart_config usart_conf; /* Configure USART for unit test output */ usart_get_config_defaults(&usart_conf); usart_conf.mux_setting = CONF_STDIO_MUX_SETTING; usart_conf.pinmux_pad0 = CONF_STDIO_PINMUX_PAD0; usart_conf.pinmux_pad1 = CONF_STDIO_PINMUX_PAD1; usart_conf.pinmux_pad2 = CONF_STDIO_PINMUX_PAD2; usart_conf.pinmux_pad3 = CONF_STDIO_PINMUX_PAD3; usart_conf.baudrate = CONF_STDIO_BAUDRATE; stdio_serial_init(&cdc_uart_module, CONF_STDIO_USART, &usart_conf); usart_enable(&cdc_uart_module); } /** * \internal * \brief Test for TRNG polling mode read. * * This test reads three random data in polling mode and check the result. * * \param test Current test case */ static void run_trng_polling_read_test(const struct test_case *test) { uint32_t i; uint32_t timeout; uint32_t random_result[3]; /* Structure for TRNG configuration */ struct trng_config config; /* Initialize and enable the TRNG */ trng_get_config_defaults(&config); trng_init(&trng_instance, TRNG, &config); trng_enable(&trng_instance); /* Read random data */ for (i = 0; i < 3; i++) { /* A new 32-bits random data will be generated for every * 84 CLK_TRNG_APB clock cycles. */ timeout = 84; if (trng_read(&trng_instance, &random_result[i]) != STATUS_OK) { timeout--; if (timeout == 0) { /* Skip test if fail to read random data */ test_assert_true(test, false, "Fail to read random data in polling mode."); } } } /* Assume there is no probability to read same three * consecutive random number */ if ((random_result[0] == random_result[1]) && (random_result[0] == random_result[2])) { test_assert_true(test, false, "Get same random data in polling mode."); } } /** * \internal * \brief TRNG callback mode test function * * This test reads three random data in callback mode and check the result. * * \param test Current test case. */ static void run_trng_callback_read_test(const struct test_case *test) { uint32_t timeout = 84 * 3; uint32_t random_result[3]; /* Register and enable TRNG read callback */ trng_register_callback(&trng_instance, trng_complete_callback, TRNG_CALLBACK_READ_BUFFER); trng_enable_callback(&trng_instance, TRNG_CALLBACK_READ_BUFFER); /* Start TRNG read job */ trng_read_buffer_job(&trng_instance, random_result, 3); do { timeout--; if (interrupt_flag) { break; } } while (timeout > 0); test_assert_true(test, timeout, "Fail to read random data in callback mode."); /* Assume there is no probability to read same three * consecutive random number */ if ((random_result[0] == random_result[1]) && (random_result[0] == random_result[2])) { test_assert_true(test, false, "Get same random data in polling mode."); } /* Test done, disable read callback and TRNG instance */ trng_disable_callback(&trng_instance, TRNG_CALLBACK_READ_BUFFER); trng_disable(&trng_instance); } /** * \brief Run TRNG unit tests * * Initializes the system and serial output, then sets up the * TRNG unit test suite and runs it. */ int main(void) { system_init(); cdc_uart_init(); /* Define Test Cases */ DEFINE_TEST_CASE(trng_polling_read_test, NULL, run_trng_polling_read_test, NULL, "Testing TRNG polling read"); DEFINE_TEST_CASE(trng_callback_read_test, NULL, run_trng_callback_read_test, NULL, "Testing TRNG callback read"); /* Put test case addresses in an array */ DEFINE_TEST_ARRAY(trng_tests) = { &trng_polling_read_test, &trng_callback_read_test, }; /* Define the test suite */ DEFINE_TEST_SUITE(trng_test_suite, trng_tests, "SAM TRNG driver test suite"); /* Run all tests in the suite*/ test_suite_run(&trng_test_suite); while (true) { /* Intentionally left empty */ } }
agpl-3.0
EASEA/EASEAudioMonitor
AudioMonitor/server/src/FluidCompositor.cpp
1
3077
#include "FluidCompositor.hpp" void FluidCompositor::send(){ Compositor::send(); } FluidCompositor::~FluidCompositor(){} void FluidCompositor::send(osc::OutboundPacketStream oscMsg){ Compositor::send(oscMsg); } osc::OutboundPacketStream FluidCompositor::compose(EASEAClientData* cl){ char buffer[OUTPUT_BUFFER_SIZE]; osc::OutboundPacketStream p( buffer, OUTPUT_BUFFER_SIZE ); int freq = cl->getBestVector()->back(); freq=rescaling(freq); p << osc::BeginBundleImmediate << osc::BeginMessage( "/note" ) << cl->computeNote() << cl->getID() << osc::EndMessage << osc::EndBundle; return p; } void FluidCompositor::notify(EASEAClientData* cl){ Compositor::notify(cl); } FluidCompositor::FluidCompositor(std::string ip,int port,bool dbg):Compositor::Compositor(ip,port,dbg){ juce::StringArray deviceName; juce::MidiFile* midiToParse; juce::FileInputStream* midiInputStream; juce::MidiOutput* fluidsynth; juce::MidiMessageSequence::MidiEventHolder* curEvent; juce::MidiBuffer chord; const juce::MidiMessageSequence* curTrack; juce::File* midiFile; int nbTrack; int nbEvent; int num; int i; double curTimestamp; double refTime; deviceName=juce::MidiOutput::getDevices(); std::cout<<"Available MIDI devices:"<<std::endl; /* Print found device */ for (i = 0; i < deviceName.size(); i++) { std::cout<<i<<"\t"<<deviceName[i]<<std::endl; } fluidsynth=juce::MidiOutput::openDevice(1); fluidsynth->startBackgroundThread(); /* Open and Read midiFile */ midiFile=new File("/home/pallamidessi/Ligeti/Test_and_demo/midi/gym3_1.mid"); if(!midiFile->existsAsFile()){ perror("File does not exist"); return; } midiInputStream= new FileInputStream(*midiFile); midiToParse=new MidiFile(); if(!midiToParse->readFrom(*midiInputStream)){ perror("Can't read stream"); return; } /*TODO: multi-track (drifting !!!) playback */ /*Retrieve track(s) and info*/ midiToParse->convertTimestampTicksToSeconds(); curTrack=midiToParse->getTrack(1); nbEvent=curTrack->getNumEvents(); curTimestamp=curTrack->getStartTime(); /* Start time */ refTime=Time::getMillisecondCounter(); /* Loop on all events, add them on MidiBuffers if they're "chords" * and send the MidiBuffers with delay * */ for (i = 0; i < nbEvent;) { num=0; /* Check if events form a "Chord" */ while(curTrack->getEventTime(i)==curTimestamp){ chord.addEvent(curTrack->getEventPointer(i)->message,num); num++; i++; } fluidsynth->sendBlockOfMessages(chord,refTime+curTimestamp*1000,100000); if(debug){ std::cout<<"message block sent :"<< curTimestamp<<" with " <<chord.getNumEvents()<<" event(s) "<<std::endl; } chord.clear(); curTimestamp=curTrack->getEventTime(i); } } void FluidCompositor::aSending(EASEAClientData* cl){ Compositor::aSending(cl); } void FluidCompositor::aReception(EASEAClientData* cl){ Compositor::aReception(cl); }
agpl-3.0
pohly/funambol-cpp-client-api
test/client-test-main.cpp
1
7826
/* * Funambol is a mobile platform developed by Funambol, Inc. * Copyright (C) 2003 - 2007 Funambol, Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by * the Free Software Foundation with the addition of the following permission * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, see http://www.gnu.org/licenses or write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA. * * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License * version 3, these Appropriate Legal Notices must retain the display of the * "Powered by Funambol" logo. If the display of the logo is not reasonably * feasible for technical reasons, the Appropriate Legal Notices must display * the words "Powered by Funambol". */ /** @cond API */ /** @addtogroup ClientTest */ /** @{ */ #ifdef HAVE_CONFIG_H # include <config.h> #endif #include <string> #include <stdexcept> #include <cppunit/CompilerOutputter.h> #include <cppunit/ui/text/TestRunner.h> #include <cppunit/TestListener.h> #include <cppunit/TestResult.h> #include <cppunit/TestFailure.h> #include <cppunit/extensions/TestFactoryRegistry.h> #include <cppunit/extensions/HelperMacros.h> #include <stdlib.h> #include <stdio.h> #include "base/globalsdef.h" #include <base/Log.h> #include "push/CTPService.h" USE_NAMESPACE #ifdef ENABLE_INTEGRATION_TESTS #include "TestFileSource.h" #endif #ifdef HAVE_SIGNAL_H # include <signal.h> #endif using namespace std; void simplifyFilename(string &filename) { size_t pos = 0; while (true) { pos = filename.find(":", pos); if (pos == filename.npos ) { break; } filename.replace(pos, 1, "_"); } } class ClientOutputter : public CppUnit::CompilerOutputter { public: ClientOutputter(CppUnit::TestResultCollector *result, std::ostream &stream) : CompilerOutputter(result, stream) {} void write() { // ensure that output goes to console again LOG.setLogName("test.log"); CompilerOutputter::write(); } }; class ClientListener : public CppUnit::TestListener { public: ClientListener() : m_failed(false) { #ifdef HAVE_SIGNAL_H // install signal handler which turns an alarm signal into a runtime exception // to abort tests which run too long const char *alarm = getenv("CLIENT_TEST_ALARM"); m_alarmSeconds = alarm ? atoi(alarm) : -1; struct sigaction action; memset(&action, 0, sizeof(action)); action.sa_handler = alarmTriggered; action.sa_flags = SA_NODEFER; sigaction(SIGALRM, &action, NULL); #endif } void addAllowedFailures(string allowedFailures) { size_t start = 0, end; while ((end = allowedFailures.find(',', start)) != allowedFailures.npos) { size_t len = end - start; if (len) { m_allowedFailures.insert(allowedFailures.substr(start, len)); } start = end + 1; } if (allowedFailures.size() > start) { m_allowedFailures.insert(allowedFailures.substr(start)); } } void startTest (CppUnit::Test *test) { m_currentTest = test->getName(); LOG.setLogName("test.log"); cerr << m_currentTest; string logfile = m_currentTest + ".log"; simplifyFilename(logfile); remove(logfile.c_str()); LOG.setLogName(logfile.c_str()); m_testFailed = false; #ifdef HAVE_SIGNAL_H if (m_alarmSeconds > 0) { alarm(m_alarmSeconds); } #endif } void addFailure(const CppUnit::TestFailure &failure) { m_testFailed = true; } void endTest (CppUnit::Test *test) { #ifdef HAVE_SIGNAL_H if (m_alarmSeconds > 0) { alarm(0); } #endif LOG.setLogName("test.log"); if (m_testFailed) { if (m_allowedFailures.find(m_currentTest) == m_allowedFailures.end()) { cerr << " *** failed ***"; m_failed = true; } else { cerr << " *** failure ignored ***"; } } cerr << "\n"; } bool hasFailed() { return m_failed; } const string &getCurrentTest() const { return m_currentTest; } private: set<string> m_allowedFailures; bool m_failed, m_testFailed; string m_currentTest; int m_alarmSeconds; static void alarmTriggered(int signal) { CPPUNIT_ASSERT_MESSAGE("test timed out", false); } } syncListener; const string &getCurrentTest() { return syncListener.getCurrentTest(); } static void printTests(CppUnit::Test *test, int indention) { if (!test) { return; } std::string name = test->getName(); printf("%*s%s\n", indention * 3, "", name.c_str()); for (int i = 0; i < test->getChildTestCount(); i++) { printTests(test->getChildTestAt(i), indention+1); } } int main(int argc, char* argv[]) { #ifdef ENABLE_INTEGRATION_TESTS TestFileSource testFileSource("A"); testFileSource.registerTests(); #endif // Get the top level suite from the registry CppUnit::Test *suite = CppUnit::TestFactoryRegistry::getRegistry().makeTest(); if (argc >= 2 && (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help"))) { printf("usage: %s [test name]+\n\n" "Without arguments all available tests are run.\n" "Otherwise only the tests or group of tests listed are run.\n" "Here is the test hierarchy of this test program:\n", argv[0]); printTests(suite, 1); return 0; } // Adds the test to the list of test to run CppUnit::TextUi::TestRunner runner; runner.addTest( suite ); // Change the default outputter to a compiler error format outputter runner.setOutputter( new ClientOutputter( &runner.result(), std::cerr ) ); // track current test and failure state const char *allowedFailures = getenv("CLIENT_TEST_FAILURES"); if (allowedFailures) { syncListener.addAllowedFailures(allowedFailures); } runner.eventManager().addListener(&syncListener); try { // Run the tests. if (argc <= 1) { // all tests runner.run("", false, true, false); } else { // run selected tests individually for (int test = 1; test < argc; test++) { runner.run(argv[test], false, true, false); } } // Return error code 1 if the one of test failed. return syncListener.hasFailed() ? 1 : 0; } catch (invalid_argument e) { // Test path not resolved std::cerr << std::endl << "ERROR: " << e.what() << std::endl; return 1; } } /** @} */ /** @endcond */
agpl-3.0
kaltura/nginx-secure-token-module
iijpta/ngx_http_secure_token_iijpta.c
1
6080
#include <ngx_config.h> #include "ngx_http_secure_token_iijpta.h" #include "../ngx_http_secure_token_filter_module.h" #include "../ngx_http_secure_token_utils.h" #include <openssl/evp.h> // macros #define set_be32(p, dw) \ { \ ((u_char*)p)[0] = ((dw) >> 24) & 0xFF; \ ((u_char*)p)[1] = ((dw) >> 16) & 0xFF; \ ((u_char*)p)[2] = ((dw) >> 8) & 0xFF; \ ((u_char*)p)[3] = (dw)& 0xFF; \ } #define set_be64(p, qw) \ { \ set_be32(p, (qw) >> 32); \ set_be32(p + 4, (qw)); \ } // constants #define CRC32_SIZE 4 #define EXPIRY_SIZE 8 #define PATH_LIMIT 1024 #define COOKIE_ATTR_SIZE (sizeof("; Expires=Thu, 31-Dec-2019 23:59:59 GMT; Max-Age=") - 1 + NGX_TIME_T_LEN) // typedefs typedef struct { ngx_str_t key; ngx_str_t iv; ngx_http_complex_value_t *acl; ngx_secure_token_time_t end; } ngx_secure_token_iijpta_token_t; typedef struct { u_char crc[CRC32_SIZE]; u_char expiry[EXPIRY_SIZE]; } ngx_http_secure_token_iijpta_header_t; static ngx_conf_num_bounds_t ngx_http_secure_token_iijpta_key_bounds = { ngx_conf_check_str_len_bounds, 16, 16 }; static ngx_conf_num_bounds_t ngx_http_secure_token_iijpta_iv_bounds = { ngx_conf_check_str_len_bounds, 16, 16 }; // globals static ngx_command_t ngx_http_secure_token_iijpta_cmds[] = { { ngx_string("key"), NGX_CONF_TAKE1, ngx_http_secure_token_conf_set_hex_str_slot, 0, offsetof(ngx_secure_token_iijpta_token_t, key), &ngx_http_secure_token_iijpta_key_bounds }, { ngx_string("iv"), NGX_CONF_TAKE1, ngx_http_secure_token_conf_set_hex_str_slot, 0, offsetof(ngx_secure_token_iijpta_token_t, iv), &ngx_http_secure_token_iijpta_iv_bounds }, { ngx_string("acl"), NGX_CONF_TAKE1, ngx_http_set_complex_value_slot, 0, offsetof(ngx_secure_token_iijpta_token_t, acl), NULL }, { ngx_string("end"), NGX_CONF_TAKE1, ngx_http_secure_token_conf_set_time_slot, 0, offsetof(ngx_secure_token_iijpta_token_t, end), NULL }, }; static ngx_int_t ngx_http_secure_token_get_acl_iijpta(ngx_http_request_t *r, ngx_http_complex_value_t *acl_conf, ngx_str_t* acl) { // get the acl if (acl_conf != NULL) { if (ngx_http_complex_value(r, acl_conf, acl) != NGX_OK) { return NGX_ERROR; } } else { // the default is '/*' ngx_str_set(acl, "/*"); } return NGX_OK; } static ngx_int_t ngx_secure_token_iijpta_get_var( ngx_http_request_t *r, ngx_http_variable_value_t *v, uintptr_t data) { EVP_CIPHER_CTX *ctx = NULL; uint32_t crc; ngx_secure_token_iijpta_token_t* token = (void*)data; ngx_http_secure_token_iijpta_header_t hdr; ngx_http_secure_token_loc_conf_t *conf; size_t in_len; size_t size; u_char *p; u_char *out; int out_len; u_char *outp; uint64_t end; ngx_str_t acl; ngx_int_t rc; conf = ngx_http_get_module_loc_conf(r, ngx_http_secure_token_filter_module); rc = ngx_http_secure_token_get_acl_iijpta(r, token->acl, &acl); if (rc != NGX_OK) { return rc; } if (acl.len > PATH_LIMIT) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "ngx_secure_token_iijpta_get_var: acl is too long for the iijpta token"); return NGX_ERROR; } end = token->end.val; if (token->end.type == NGX_HTTP_SECURE_TOKEN_TIME_RELATIVE) { end += ngx_time(); } set_be64(hdr.expiry, end); ngx_crc32_init(crc); ngx_crc32_update(&crc, hdr.expiry, EXPIRY_SIZE); ngx_crc32_update(&crc, acl.data, acl.len); ngx_crc32_final(crc); set_be32(hdr.crc, crc); ctx = EVP_CIPHER_CTX_new(); if (ctx == NULL) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "ngx_secure_token_iijpta_get_var: EVP_CIPHER_CTX_new failed"); return NGX_ERROR; } if (!EVP_EncryptInit_ex(ctx, EVP_aes_128_cbc(), NULL, token->key.data, token->iv.data)) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "ngx_secure_token_iijpta_get_var: EVP_EncryptInit_ex failed"); goto error; } in_len = sizeof(ngx_http_secure_token_iijpta_header_t) + acl.len; // in_len rounded up to block + one block for padding out = ngx_pnalloc(r->pool, (in_len & ~0xf) + 0x10); if (out == NULL) { goto error; } outp = out; if (!EVP_EncryptUpdate(ctx, outp, &out_len, (void *)&hdr, sizeof(hdr))) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "ngx_secure_token_iijpta_get_var: EVP_EncryptUpdate failed (1)"); goto error; } outp += out_len; if (!EVP_EncryptUpdate(ctx, outp, &out_len, acl.data, acl.len)) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "ngx_secure_token_iijpta_get_var: EVP_EncryptUpdate failed (2)"); goto error; } outp += out_len; if (!EVP_EncryptFinal_ex(ctx, outp, &out_len)) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "ngx_secure_token_iijpta_get_var: EVP_EncryptFinal_ex failed"); goto error; } outp += out_len; out_len = outp - out; size = sizeof("pta=") + (out_len * 2); if (conf->avoid_cookies == 0) { size += COOKIE_ATTR_SIZE; } p = ngx_pnalloc(r->pool, size); if (p == NULL) { goto error; } v->data = p; p = ngx_copy(p, "pta=", sizeof("pta=") - 1); p = ngx_hex_dump(p, out, out_len); if (conf->avoid_cookies == 0) { p = ngx_copy(p, "; Expires=", sizeof("; Expires=") - 1); p = ngx_http_cookie_time(p, end); p = ngx_sprintf(p, "; Max-Age=%T", end - ngx_time()); } *p = '\0'; v->len = p - v->data; v->valid = 1; v->no_cacheable = 0; v->not_found = 0; EVP_CIPHER_CTX_free(ctx); return NGX_OK; error: EVP_CIPHER_CTX_free(ctx); return NGX_ERROR; } char * ngx_secure_token_iijpta_block(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) { ngx_secure_token_iijpta_token_t* token; char* rv; // init config token = ngx_pcalloc(cf->pool, sizeof(*token)); if (token == NULL) { return NGX_CONF_ERROR; } token->end.type = NGX_HTTP_SECURE_TOKEN_TIME_UNSET; // parse the block rv = ngx_http_secure_token_conf_block( cf, ngx_http_secure_token_iijpta_cmds, token, ngx_secure_token_iijpta_get_var); if (rv != NGX_CONF_OK) { return rv; } if (token->end.type == NGX_HTTP_SECURE_TOKEN_TIME_UNSET) { token->end.type = NGX_HTTP_SECURE_TOKEN_TIME_RELATIVE; token->end.val = 86400; } return NGX_CONF_OK; }
agpl-3.0
djludo/navitia
source/type/message.cpp
8
3947
/* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved. This file is part of Navitia, the software to build cool stuff with public transport. Hope you'll enjoy and contribute to this project, powered by Canal TP (www.canaltp.fr). Help us simplify mobility and open public transport: a non ending quest to the responsive locomotion way of traveling! LICENCE: This program is free software; you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Stay tuned using twitter @navitia IRC #navitia on freenode https://groups.google.com/d/forum/navitia www.navitia.io */ #include "type/message.h" #include "type/pt_data.h" #include "utils/logger.h" #include <boost/format.hpp> namespace pt = boost::posix_time; namespace bg = boost::gregorian; namespace navitia { namespace type { namespace new_disruption { bool Impact::is_valid(const boost::posix_time::ptime& publication_date, const boost::posix_time::time_period& active_period) const { if(publication_date.is_not_a_date_time() && active_period.is_null()){ return false; } // we check if we want to publish the impact if (! disruption->is_publishable(publication_date)) { return false; } //if we have a active_period, we check if the impact applies on this period if (active_period.is_null()) { return true; } for (const auto& period: application_periods) { if (! period.intersection(active_period).is_null()) { return true; } } return false; } bool Disruption::is_publishable(const boost::posix_time::ptime& current_time) const{ if(current_time.is_not_a_date_time()){ return false; } if (this->publication_period.contains(current_time)) { return true; } return false; } void Disruption::add_impact(const boost::shared_ptr<Impact>& impact){ impact->disruption = this; impacts.push_back(impact); } namespace { template<typename T> PtObj transform_pt_object(const std::string& uri, const std::unordered_map<std::string, T*>& map, const boost::shared_ptr<Impact>& impact) { if (auto o = find_or_default(uri, map)) { if (impact){ o->add_impact(impact); } return o; } else { LOG4CPLUS_INFO(log4cplus::Logger::getInstance("log"), "Impossible to find pt object " << uri); return UnknownPtObj(); } } } PtObj make_pt_obj(Type_e type, const std::string& uri, const PT_Data& pt_data, const boost::shared_ptr<Impact>& impact) { switch (type) { case Type_e::Network: return transform_pt_object(uri, pt_data.networks_map, impact); case Type_e::StopArea: return transform_pt_object(uri, pt_data.stop_areas_map, impact); case Type_e::Line: return transform_pt_object(uri, pt_data.lines_map, impact); case Type_e::Route: return transform_pt_object(uri, pt_data.routes_map, impact); default: return UnknownPtObj(); } } bool Impact::operator<(const Impact& other){ if(this->severity->priority != other.severity->priority){ return this->severity->priority < other.severity->priority; }if(this->created_at != other.created_at){ return this->created_at < other.created_at; }else{ return this->uri < other.uri; } } }}}//namespace
agpl-3.0
xyg165/testgit.github.io
u-boot-1.1.6/board/MAI/bios_emulator/scitech/src/x86emu/ops.c
46
306177
/**************************************************************************** * * Realmode X86 Emulator Library * * Copyright (C) 1996-1999 SciTech Software, Inc. * Copyright (C) David Mosberger-Tang * Copyright (C) 1999 Egbert Eich * * ======================================================================== * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and that * both that copyright notice and this permission notice appear in * supporting documentation, and that the name of the authors not be used * in advertising or publicity pertaining to distribution of the software * without specific, written prior permission. The authors makes no * representations about the suitability of this software for any purpose. * It is provided "as is" without express or implied warranty. * * THE AUTHORS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO * EVENT SHALL THE AUTHORS BE LIABLE FOR ANY SPECIAL, INDIRECT OR * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. * * ======================================================================== * * Language: ANSI C * Environment: Any * Developer: Kendall Bennett * * Description: This file includes subroutines to implement the decoding * and emulation of all the x86 processor instructions. * * There are approximately 250 subroutines in here, which correspond * to the 256 byte-"opcodes" found on the 8086. The table which * dispatches this is found in the files optab.[ch]. * * Each opcode proc has a comment preceeding it which gives it's table * address. Several opcodes are missing (undefined) in the table. * * Each proc includes information for decoding (DECODE_PRINTF and * DECODE_PRINTF2), debugging (TRACE_REGS, SINGLE_STEP), and misc * functions (START_OF_INSTR, END_OF_INSTR). * * Many of the procedures are *VERY* similar in coding. This has * allowed for a very large amount of code to be generated in a fairly * short amount of time (i.e. cut, paste, and modify). The result is * that much of the code below could have been folded into subroutines * for a large reduction in size of this file. The downside would be * that there would be a penalty in execution speed. The file could * also have been *MUCH* larger by inlining certain functions which * were called. This could have resulted even faster execution. The * prime directive I used to decide whether to inline the code or to * modularize it, was basically: 1) no unnecessary subroutine calls, * 2) no routines more than about 200 lines in size, and 3) modularize * any code that I might not get right the first time. The fetch_* * subroutines fall into the latter category. The The decode_* fall * into the second category. The coding of the "switch(mod){ .... }" * in many of the subroutines below falls into the first category. * Especially, the coding of {add,and,or,sub,...}_{byte,word} * subroutines are an especially glaring case of the third guideline. * Since so much of the code is cloned from other modules (compare * opcode #00 to opcode #01), making the basic operations subroutine * calls is especially important; otherwise mistakes in coding an * "add" would represent a nightmare in maintenance. * ****************************************************************************/ #include "x86emu/x86emui.h" /*----------------------------- Implementation ----------------------------*/ /**************************************************************************** PARAMETERS: op1 - Instruction op code REMARKS: Handles illegal opcodes. ****************************************************************************/ void x86emuOp_illegal_op( u8 op1) { START_OF_INSTR(); DECODE_PRINTF("ILLEGAL X86 OPCODE\n"); TRACE_REGS(); printk("%04x:%04x: %02X ILLEGAL X86 OPCODE!\n", M.x86.R_CS, M.x86.R_IP-1,op1); HALT_SYS(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x00 ****************************************************************************/ void x86emuOp_add_byte_RM_R(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; uint destoffset; u8 *destreg, *srcreg; u8 destval; START_OF_INSTR(); DECODE_PRINTF("ADD\t"); FETCH_DECODE_MODRM(mod, rh, rl); switch (mod) { case 0: destoffset = decode_rm00_address(rl); DECODE_PRINTF(","); destval = fetch_data_byte(destoffset); srcreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = add_byte(destval, *srcreg); store_data_byte(destoffset, destval); break; case 1: destoffset = decode_rm01_address(rl); DECODE_PRINTF(","); destval = fetch_data_byte(destoffset); srcreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = add_byte(destval, *srcreg); store_data_byte(destoffset, destval); break; case 2: destoffset = decode_rm10_address(rl); DECODE_PRINTF(","); destval = fetch_data_byte(destoffset); srcreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = add_byte(destval, *srcreg); store_data_byte(destoffset, destval); break; case 3: /* register to register */ destreg = DECODE_RM_BYTE_REGISTER(rl); DECODE_PRINTF(","); srcreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = add_byte(*destreg, *srcreg); break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x01 ****************************************************************************/ void x86emuOp_add_word_RM_R(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; uint destoffset; START_OF_INSTR(); DECODE_PRINTF("ADD\t"); FETCH_DECODE_MODRM(mod, rh, rl); switch (mod) { case 0: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; u32 *srcreg; destoffset = decode_rm00_address(rl); DECODE_PRINTF(","); destval = fetch_data_long(destoffset); srcreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = add_long(destval, *srcreg); store_data_long(destoffset, destval); } else { u16 destval; u16 *srcreg; destoffset = decode_rm00_address(rl); DECODE_PRINTF(","); destval = fetch_data_word(destoffset); srcreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = add_word(destval, *srcreg); store_data_word(destoffset, destval); } break; case 1: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; u32 *srcreg; destoffset = decode_rm01_address(rl); DECODE_PRINTF(","); destval = fetch_data_long(destoffset); srcreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = add_long(destval, *srcreg); store_data_long(destoffset, destval); } else { u16 destval; u16 *srcreg; destoffset = decode_rm01_address(rl); DECODE_PRINTF(","); destval = fetch_data_word(destoffset); srcreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = add_word(destval, *srcreg); store_data_word(destoffset, destval); } break; case 2: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; u32 *srcreg; destoffset = decode_rm10_address(rl); DECODE_PRINTF(","); destval = fetch_data_long(destoffset); srcreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = add_long(destval, *srcreg); store_data_long(destoffset, destval); } else { u16 destval; u16 *srcreg; destoffset = decode_rm10_address(rl); DECODE_PRINTF(","); destval = fetch_data_word(destoffset); srcreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = add_word(destval, *srcreg); store_data_word(destoffset, destval); } break; case 3: /* register to register */ if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg,*srcreg; destreg = DECODE_RM_LONG_REGISTER(rl); DECODE_PRINTF(","); srcreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = add_long(*destreg, *srcreg); } else { u16 *destreg,*srcreg; destreg = DECODE_RM_WORD_REGISTER(rl); DECODE_PRINTF(","); srcreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = add_word(*destreg, *srcreg); } break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x02 ****************************************************************************/ void x86emuOp_add_byte_R_RM(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; u8 *destreg, *srcreg; uint srcoffset; u8 srcval; START_OF_INSTR(); DECODE_PRINTF("ADD\t"); FETCH_DECODE_MODRM(mod, rh, rl); switch (mod) { case 0: destreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm00_address(rl); srcval = fetch_data_byte(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = add_byte(*destreg, srcval); break; case 1: destreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm01_address(rl); srcval = fetch_data_byte(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = add_byte(*destreg, srcval); break; case 2: destreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm10_address(rl); srcval = fetch_data_byte(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = add_byte(*destreg, srcval); break; case 3: /* register to register */ destreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF(","); srcreg = DECODE_RM_BYTE_REGISTER(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = add_byte(*destreg, *srcreg); break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x03 ****************************************************************************/ void x86emuOp_add_word_R_RM(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; uint srcoffset; START_OF_INSTR(); DECODE_PRINTF("ADD\t"); FETCH_DECODE_MODRM(mod, rh, rl); switch (mod) { case 0: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg; u32 srcval; destreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm00_address(rl); srcval = fetch_data_long(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = add_long(*destreg, srcval); } else { u16 *destreg; u16 srcval; destreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm00_address(rl); srcval = fetch_data_word(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = add_word(*destreg, srcval); } break; case 1: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg; u32 srcval; destreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm01_address(rl); srcval = fetch_data_long(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = add_long(*destreg, srcval); } else { u16 *destreg; u16 srcval; destreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm01_address(rl); srcval = fetch_data_word(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = add_word(*destreg, srcval); } break; case 2: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg; u32 srcval; destreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm10_address(rl); srcval = fetch_data_long(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = add_long(*destreg, srcval); } else { u16 *destreg; u16 srcval; destreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm10_address(rl); srcval = fetch_data_word(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = add_word(*destreg, srcval); } break; case 3: /* register to register */ if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg,*srcreg; destreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF(","); srcreg = DECODE_RM_LONG_REGISTER(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = add_long(*destreg, *srcreg); } else { u16 *destreg,*srcreg; destreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF(","); srcreg = DECODE_RM_WORD_REGISTER(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = add_word(*destreg, *srcreg); } break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x04 ****************************************************************************/ void x86emuOp_add_byte_AL_IMM(u8 X86EMU_UNUSED(op1)) { u8 srcval; START_OF_INSTR(); DECODE_PRINTF("ADD\tAL,"); srcval = fetch_byte_imm(); DECODE_PRINTF2("%x\n", srcval); TRACE_AND_STEP(); M.x86.R_AL = add_byte(M.x86.R_AL, srcval); DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x05 ****************************************************************************/ void x86emuOp_add_word_AX_IMM(u8 X86EMU_UNUSED(op1)) { u32 srcval; START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("ADD\tEAX,"); srcval = fetch_long_imm(); } else { DECODE_PRINTF("ADD\tAX,"); srcval = fetch_word_imm(); } DECODE_PRINTF2("%x\n", srcval); TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { M.x86.R_EAX = add_long(M.x86.R_EAX, srcval); } else { M.x86.R_AX = add_word(M.x86.R_AX, (u16)srcval); } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x06 ****************************************************************************/ void x86emuOp_push_ES(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); DECODE_PRINTF("PUSH\tES\n"); TRACE_AND_STEP(); push_word(M.x86.R_ES); DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x07 ****************************************************************************/ void x86emuOp_pop_ES(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); DECODE_PRINTF("POP\tES\n"); TRACE_AND_STEP(); M.x86.R_ES = pop_word(); DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x08 ****************************************************************************/ void x86emuOp_or_byte_RM_R(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; u8 *destreg, *srcreg; uint destoffset; u8 destval; START_OF_INSTR(); DECODE_PRINTF("OR\t"); FETCH_DECODE_MODRM(mod, rh, rl); switch (mod) { case 0: destoffset = decode_rm00_address(rl); DECODE_PRINTF(","); destval = fetch_data_byte(destoffset); srcreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = or_byte(destval, *srcreg); store_data_byte(destoffset, destval); break; case 1: destoffset = decode_rm01_address(rl); DECODE_PRINTF(","); destval = fetch_data_byte(destoffset); srcreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = or_byte(destval, *srcreg); store_data_byte(destoffset, destval); break; case 2: destoffset = decode_rm10_address(rl); DECODE_PRINTF(","); destval = fetch_data_byte(destoffset); srcreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = or_byte(destval, *srcreg); store_data_byte(destoffset, destval); break; case 3: /* register to register */ destreg = DECODE_RM_BYTE_REGISTER(rl); DECODE_PRINTF(","); srcreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = or_byte(*destreg, *srcreg); break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x09 ****************************************************************************/ void x86emuOp_or_word_RM_R(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; uint destoffset; START_OF_INSTR(); DECODE_PRINTF("OR\t"); FETCH_DECODE_MODRM(mod, rh, rl); switch (mod) { case 0: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; u32 *srcreg; destoffset = decode_rm00_address(rl); DECODE_PRINTF(","); destval = fetch_data_long(destoffset); srcreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = or_long(destval, *srcreg); store_data_long(destoffset, destval); } else { u16 destval; u16 *srcreg; destoffset = decode_rm00_address(rl); DECODE_PRINTF(","); destval = fetch_data_word(destoffset); srcreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = or_word(destval, *srcreg); store_data_word(destoffset, destval); } break; case 1: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; u32 *srcreg; destoffset = decode_rm01_address(rl); DECODE_PRINTF(","); destval = fetch_data_long(destoffset); srcreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = or_long(destval, *srcreg); store_data_long(destoffset, destval); } else { u16 destval; u16 *srcreg; destoffset = decode_rm01_address(rl); DECODE_PRINTF(","); destval = fetch_data_word(destoffset); srcreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = or_word(destval, *srcreg); store_data_word(destoffset, destval); } break; case 2: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; u32 *srcreg; destoffset = decode_rm10_address(rl); DECODE_PRINTF(","); destval = fetch_data_long(destoffset); srcreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = or_long(destval, *srcreg); store_data_long(destoffset, destval); } else { u16 destval; u16 *srcreg; destoffset = decode_rm10_address(rl); DECODE_PRINTF(","); destval = fetch_data_word(destoffset); srcreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = or_word(destval, *srcreg); store_data_word(destoffset, destval); } break; case 3: /* register to register */ if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg,*srcreg; destreg = DECODE_RM_LONG_REGISTER(rl); DECODE_PRINTF(","); srcreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = or_long(*destreg, *srcreg); } else { u16 *destreg,*srcreg; destreg = DECODE_RM_WORD_REGISTER(rl); DECODE_PRINTF(","); srcreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = or_word(*destreg, *srcreg); } break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x0a ****************************************************************************/ void x86emuOp_or_byte_R_RM(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; u8 *destreg, *srcreg; uint srcoffset; u8 srcval; START_OF_INSTR(); DECODE_PRINTF("OR\t"); FETCH_DECODE_MODRM(mod, rh, rl); switch (mod) { case 0: destreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm00_address(rl); srcval = fetch_data_byte(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = or_byte(*destreg, srcval); break; case 1: destreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm01_address(rl); srcval = fetch_data_byte(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = or_byte(*destreg, srcval); break; case 2: destreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm10_address(rl); srcval = fetch_data_byte(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = or_byte(*destreg, srcval); break; case 3: /* register to register */ destreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF(","); srcreg = DECODE_RM_BYTE_REGISTER(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = or_byte(*destreg, *srcreg); break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x0b ****************************************************************************/ void x86emuOp_or_word_R_RM(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; uint srcoffset; START_OF_INSTR(); DECODE_PRINTF("OR\t"); FETCH_DECODE_MODRM(mod, rh, rl); switch (mod) { case 0: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg; u32 srcval; destreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm00_address(rl); srcval = fetch_data_long(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = or_long(*destreg, srcval); } else { u16 *destreg; u16 srcval; destreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm00_address(rl); srcval = fetch_data_word(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = or_word(*destreg, srcval); } break; case 1: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg; u32 srcval; destreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm01_address(rl); srcval = fetch_data_long(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = or_long(*destreg, srcval); } else { u16 *destreg; u16 srcval; destreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm01_address(rl); srcval = fetch_data_word(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = or_word(*destreg, srcval); } break; case 2: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg; u32 srcval; destreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm10_address(rl); srcval = fetch_data_long(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = or_long(*destreg, srcval); } else { u16 *destreg; u16 srcval; destreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm10_address(rl); srcval = fetch_data_word(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = or_word(*destreg, srcval); } break; case 3: /* register to register */ if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg,*srcreg; destreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF(","); srcreg = DECODE_RM_LONG_REGISTER(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = or_long(*destreg, *srcreg); } else { u16 *destreg,*srcreg; destreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF(","); srcreg = DECODE_RM_WORD_REGISTER(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = or_word(*destreg, *srcreg); } break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x0c ****************************************************************************/ void x86emuOp_or_byte_AL_IMM(u8 X86EMU_UNUSED(op1)) { u8 srcval; START_OF_INSTR(); DECODE_PRINTF("OR\tAL,"); srcval = fetch_byte_imm(); DECODE_PRINTF2("%x\n", srcval); TRACE_AND_STEP(); M.x86.R_AL = or_byte(M.x86.R_AL, srcval); DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x0d ****************************************************************************/ void x86emuOp_or_word_AX_IMM(u8 X86EMU_UNUSED(op1)) { u32 srcval; START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("OR\tEAX,"); srcval = fetch_long_imm(); } else { DECODE_PRINTF("OR\tAX,"); srcval = fetch_word_imm(); } DECODE_PRINTF2("%x\n", srcval); TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { M.x86.R_EAX = or_long(M.x86.R_EAX, srcval); } else { M.x86.R_AX = or_word(M.x86.R_AX, (u16)srcval); } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x0e ****************************************************************************/ void x86emuOp_push_CS(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); DECODE_PRINTF("PUSH\tCS\n"); TRACE_AND_STEP(); push_word(M.x86.R_CS); DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x0f. Escape for two-byte opcode (286 or better) ****************************************************************************/ void x86emuOp_two_byte(u8 X86EMU_UNUSED(op1)) { u8 op2 = (*sys_rdb)(((u32)M.x86.R_CS << 4) + (M.x86.R_IP++)); INC_DECODED_INST_LEN(1); (*x86emu_optab2[op2])(op2); } /**************************************************************************** REMARKS: Handles opcode 0x10 ****************************************************************************/ void x86emuOp_adc_byte_RM_R(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; u8 *destreg, *srcreg; uint destoffset; u8 destval; START_OF_INSTR(); DECODE_PRINTF("ADC\t"); FETCH_DECODE_MODRM(mod, rh, rl); switch (mod) { case 0: destoffset = decode_rm00_address(rl); DECODE_PRINTF(","); destval = fetch_data_byte(destoffset); srcreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = adc_byte(destval, *srcreg); store_data_byte(destoffset, destval); break; case 1: destoffset = decode_rm01_address(rl); DECODE_PRINTF(","); destval = fetch_data_byte(destoffset); srcreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = adc_byte(destval, *srcreg); store_data_byte(destoffset, destval); break; case 2: destoffset = decode_rm10_address(rl); DECODE_PRINTF(","); destval = fetch_data_byte(destoffset); srcreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = adc_byte(destval, *srcreg); store_data_byte(destoffset, destval); break; case 3: /* register to register */ destreg = DECODE_RM_BYTE_REGISTER(rl); DECODE_PRINTF(","); srcreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = adc_byte(*destreg, *srcreg); break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x11 ****************************************************************************/ void x86emuOp_adc_word_RM_R(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; uint destoffset; START_OF_INSTR(); DECODE_PRINTF("ADC\t"); FETCH_DECODE_MODRM(mod, rh, rl); switch (mod) { case 0: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; u32 *srcreg; destoffset = decode_rm00_address(rl); DECODE_PRINTF(","); destval = fetch_data_long(destoffset); srcreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = adc_long(destval, *srcreg); store_data_long(destoffset, destval); } else { u16 destval; u16 *srcreg; destoffset = decode_rm00_address(rl); DECODE_PRINTF(","); destval = fetch_data_word(destoffset); srcreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = adc_word(destval, *srcreg); store_data_word(destoffset, destval); } break; case 1: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; u32 *srcreg; destoffset = decode_rm01_address(rl); DECODE_PRINTF(","); destval = fetch_data_long(destoffset); srcreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = adc_long(destval, *srcreg); store_data_long(destoffset, destval); } else { u16 destval; u16 *srcreg; destoffset = decode_rm01_address(rl); DECODE_PRINTF(","); destval = fetch_data_word(destoffset); srcreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = adc_word(destval, *srcreg); store_data_word(destoffset, destval); } break; case 2: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; u32 *srcreg; destoffset = decode_rm10_address(rl); DECODE_PRINTF(","); destval = fetch_data_long(destoffset); srcreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = adc_long(destval, *srcreg); store_data_long(destoffset, destval); } else { u16 destval; u16 *srcreg; destoffset = decode_rm10_address(rl); DECODE_PRINTF(","); destval = fetch_data_word(destoffset); srcreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = adc_word(destval, *srcreg); store_data_word(destoffset, destval); } break; case 3: /* register to register */ if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg,*srcreg; destreg = DECODE_RM_LONG_REGISTER(rl); DECODE_PRINTF(","); srcreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = adc_long(*destreg, *srcreg); } else { u16 *destreg,*srcreg; destreg = DECODE_RM_WORD_REGISTER(rl); DECODE_PRINTF(","); srcreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = adc_word(*destreg, *srcreg); } break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x12 ****************************************************************************/ void x86emuOp_adc_byte_R_RM(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; u8 *destreg, *srcreg; uint srcoffset; u8 srcval; START_OF_INSTR(); DECODE_PRINTF("ADC\t"); FETCH_DECODE_MODRM(mod, rh, rl); switch (mod) { case 0: destreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm00_address(rl); srcval = fetch_data_byte(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = adc_byte(*destreg, srcval); break; case 1: destreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm01_address(rl); srcval = fetch_data_byte(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = adc_byte(*destreg, srcval); break; case 2: destreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm10_address(rl); srcval = fetch_data_byte(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = adc_byte(*destreg, srcval); break; case 3: /* register to register */ destreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF(","); srcreg = DECODE_RM_BYTE_REGISTER(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = adc_byte(*destreg, *srcreg); break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x13 ****************************************************************************/ void x86emuOp_adc_word_R_RM(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; uint srcoffset; START_OF_INSTR(); DECODE_PRINTF("ADC\t"); FETCH_DECODE_MODRM(mod, rh, rl); switch (mod) { case 0: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg; u32 srcval; destreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm00_address(rl); srcval = fetch_data_long(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = adc_long(*destreg, srcval); } else { u16 *destreg; u16 srcval; destreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm00_address(rl); srcval = fetch_data_word(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = adc_word(*destreg, srcval); } break; case 1: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg; u32 srcval; destreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm01_address(rl); srcval = fetch_data_long(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = adc_long(*destreg, srcval); } else { u16 *destreg; u16 srcval; destreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm01_address(rl); srcval = fetch_data_word(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = adc_word(*destreg, srcval); } break; case 2: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg; u32 srcval; destreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm10_address(rl); srcval = fetch_data_long(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = adc_long(*destreg, srcval); } else { u16 *destreg; u16 srcval; destreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm10_address(rl); srcval = fetch_data_word(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = adc_word(*destreg, srcval); } break; case 3: /* register to register */ if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg,*srcreg; destreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF(","); srcreg = DECODE_RM_LONG_REGISTER(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = adc_long(*destreg, *srcreg); } else { u16 *destreg,*srcreg; destreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF(","); srcreg = DECODE_RM_WORD_REGISTER(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = adc_word(*destreg, *srcreg); } break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x14 ****************************************************************************/ void x86emuOp_adc_byte_AL_IMM(u8 X86EMU_UNUSED(op1)) { u8 srcval; START_OF_INSTR(); DECODE_PRINTF("ADC\tAL,"); srcval = fetch_byte_imm(); DECODE_PRINTF2("%x\n", srcval); TRACE_AND_STEP(); M.x86.R_AL = adc_byte(M.x86.R_AL, srcval); DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x15 ****************************************************************************/ void x86emuOp_adc_word_AX_IMM(u8 X86EMU_UNUSED(op1)) { u32 srcval; START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("ADC\tEAX,"); srcval = fetch_long_imm(); } else { DECODE_PRINTF("ADC\tAX,"); srcval = fetch_word_imm(); } DECODE_PRINTF2("%x\n", srcval); TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { M.x86.R_EAX = adc_long(M.x86.R_EAX, srcval); } else { M.x86.R_AX = adc_word(M.x86.R_AX, (u16)srcval); } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x16 ****************************************************************************/ void x86emuOp_push_SS(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); DECODE_PRINTF("PUSH\tSS\n"); TRACE_AND_STEP(); push_word(M.x86.R_SS); DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x17 ****************************************************************************/ void x86emuOp_pop_SS(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); DECODE_PRINTF("POP\tSS\n"); TRACE_AND_STEP(); M.x86.R_SS = pop_word(); DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x18 ****************************************************************************/ void x86emuOp_sbb_byte_RM_R(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; u8 *destreg, *srcreg; uint destoffset; u8 destval; START_OF_INSTR(); DECODE_PRINTF("SBB\t"); FETCH_DECODE_MODRM(mod, rh, rl); switch (mod) { case 0: destoffset = decode_rm00_address(rl); DECODE_PRINTF(","); destval = fetch_data_byte(destoffset); srcreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = sbb_byte(destval, *srcreg); store_data_byte(destoffset, destval); break; case 1: destoffset = decode_rm01_address(rl); DECODE_PRINTF(","); destval = fetch_data_byte(destoffset); srcreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = sbb_byte(destval, *srcreg); store_data_byte(destoffset, destval); break; case 2: destoffset = decode_rm10_address(rl); DECODE_PRINTF(","); destval = fetch_data_byte(destoffset); srcreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = sbb_byte(destval, *srcreg); store_data_byte(destoffset, destval); break; case 3: /* register to register */ destreg = DECODE_RM_BYTE_REGISTER(rl); DECODE_PRINTF(","); srcreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = sbb_byte(*destreg, *srcreg); break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x19 ****************************************************************************/ void x86emuOp_sbb_word_RM_R(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; uint destoffset; START_OF_INSTR(); DECODE_PRINTF("SBB\t"); FETCH_DECODE_MODRM(mod, rh, rl); switch (mod) { case 0: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; u32 *srcreg; destoffset = decode_rm00_address(rl); DECODE_PRINTF(","); destval = fetch_data_long(destoffset); srcreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = sbb_long(destval, *srcreg); store_data_long(destoffset, destval); } else { u16 destval; u16 *srcreg; destoffset = decode_rm00_address(rl); DECODE_PRINTF(","); destval = fetch_data_word(destoffset); srcreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = sbb_word(destval, *srcreg); store_data_word(destoffset, destval); } break; case 1: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; u32 *srcreg; destoffset = decode_rm01_address(rl); DECODE_PRINTF(","); destval = fetch_data_long(destoffset); srcreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = sbb_long(destval, *srcreg); store_data_long(destoffset, destval); } else { u16 destval; u16 *srcreg; destoffset = decode_rm01_address(rl); DECODE_PRINTF(","); destval = fetch_data_word(destoffset); srcreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = sbb_word(destval, *srcreg); store_data_word(destoffset, destval); } break; case 2: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; u32 *srcreg; destoffset = decode_rm10_address(rl); DECODE_PRINTF(","); destval = fetch_data_long(destoffset); srcreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = sbb_long(destval, *srcreg); store_data_long(destoffset, destval); } else { u16 destval; u16 *srcreg; destoffset = decode_rm10_address(rl); DECODE_PRINTF(","); destval = fetch_data_word(destoffset); srcreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = sbb_word(destval, *srcreg); store_data_word(destoffset, destval); } break; case 3: /* register to register */ if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg,*srcreg; destreg = DECODE_RM_LONG_REGISTER(rl); DECODE_PRINTF(","); srcreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = sbb_long(*destreg, *srcreg); } else { u16 *destreg,*srcreg; destreg = DECODE_RM_WORD_REGISTER(rl); DECODE_PRINTF(","); srcreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = sbb_word(*destreg, *srcreg); } break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x1a ****************************************************************************/ void x86emuOp_sbb_byte_R_RM(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; u8 *destreg, *srcreg; uint srcoffset; u8 srcval; START_OF_INSTR(); DECODE_PRINTF("SBB\t"); FETCH_DECODE_MODRM(mod, rh, rl); switch (mod) { case 0: destreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm00_address(rl); srcval = fetch_data_byte(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = sbb_byte(*destreg, srcval); break; case 1: destreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm01_address(rl); srcval = fetch_data_byte(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = sbb_byte(*destreg, srcval); break; case 2: destreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm10_address(rl); srcval = fetch_data_byte(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = sbb_byte(*destreg, srcval); break; case 3: /* register to register */ destreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF(","); srcreg = DECODE_RM_BYTE_REGISTER(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = sbb_byte(*destreg, *srcreg); break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x1b ****************************************************************************/ void x86emuOp_sbb_word_R_RM(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; uint srcoffset; START_OF_INSTR(); DECODE_PRINTF("SBB\t"); FETCH_DECODE_MODRM(mod, rh, rl); switch (mod) { case 0: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg; u32 srcval; destreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm00_address(rl); srcval = fetch_data_long(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = sbb_long(*destreg, srcval); } else { u16 *destreg; u16 srcval; destreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm00_address(rl); srcval = fetch_data_word(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = sbb_word(*destreg, srcval); } break; case 1: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg; u32 srcval; destreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm01_address(rl); srcval = fetch_data_long(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = sbb_long(*destreg, srcval); } else { u16 *destreg; u16 srcval; destreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm01_address(rl); srcval = fetch_data_word(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = sbb_word(*destreg, srcval); } break; case 2: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg; u32 srcval; destreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm10_address(rl); srcval = fetch_data_long(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = sbb_long(*destreg, srcval); } else { u16 *destreg; u16 srcval; destreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm10_address(rl); srcval = fetch_data_word(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = sbb_word(*destreg, srcval); } break; case 3: /* register to register */ if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg,*srcreg; destreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF(","); srcreg = DECODE_RM_LONG_REGISTER(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = sbb_long(*destreg, *srcreg); } else { u16 *destreg,*srcreg; destreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF(","); srcreg = DECODE_RM_WORD_REGISTER(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = sbb_word(*destreg, *srcreg); } break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x1c ****************************************************************************/ void x86emuOp_sbb_byte_AL_IMM(u8 X86EMU_UNUSED(op1)) { u8 srcval; START_OF_INSTR(); DECODE_PRINTF("SBB\tAL,"); srcval = fetch_byte_imm(); DECODE_PRINTF2("%x\n", srcval); TRACE_AND_STEP(); M.x86.R_AL = sbb_byte(M.x86.R_AL, srcval); DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x1d ****************************************************************************/ void x86emuOp_sbb_word_AX_IMM(u8 X86EMU_UNUSED(op1)) { u32 srcval; START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("SBB\tEAX,"); srcval = fetch_long_imm(); } else { DECODE_PRINTF("SBB\tAX,"); srcval = fetch_word_imm(); } DECODE_PRINTF2("%x\n", srcval); TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { M.x86.R_EAX = sbb_long(M.x86.R_EAX, srcval); } else { M.x86.R_AX = sbb_word(M.x86.R_AX, (u16)srcval); } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x1e ****************************************************************************/ void x86emuOp_push_DS(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); DECODE_PRINTF("PUSH\tDS\n"); TRACE_AND_STEP(); push_word(M.x86.R_DS); DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x1f ****************************************************************************/ void x86emuOp_pop_DS(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); DECODE_PRINTF("POP\tDS\n"); TRACE_AND_STEP(); M.x86.R_DS = pop_word(); DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x20 ****************************************************************************/ void x86emuOp_and_byte_RM_R(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; u8 *destreg, *srcreg; uint destoffset; u8 destval; START_OF_INSTR(); DECODE_PRINTF("AND\t"); FETCH_DECODE_MODRM(mod, rh, rl); switch (mod) { case 0: destoffset = decode_rm00_address(rl); DECODE_PRINTF(","); destval = fetch_data_byte(destoffset); srcreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = and_byte(destval, *srcreg); store_data_byte(destoffset, destval); break; case 1: destoffset = decode_rm01_address(rl); DECODE_PRINTF(","); destval = fetch_data_byte(destoffset); srcreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = and_byte(destval, *srcreg); store_data_byte(destoffset, destval); break; case 2: destoffset = decode_rm10_address(rl); DECODE_PRINTF(","); destval = fetch_data_byte(destoffset); srcreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = and_byte(destval, *srcreg); store_data_byte(destoffset, destval); break; case 3: /* register to register */ destreg = DECODE_RM_BYTE_REGISTER(rl); DECODE_PRINTF(","); srcreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = and_byte(*destreg, *srcreg); break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x21 ****************************************************************************/ void x86emuOp_and_word_RM_R(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; uint destoffset; START_OF_INSTR(); DECODE_PRINTF("AND\t"); FETCH_DECODE_MODRM(mod, rh, rl); switch (mod) { case 0: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; u32 *srcreg; destoffset = decode_rm00_address(rl); DECODE_PRINTF(","); destval = fetch_data_long(destoffset); srcreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = and_long(destval, *srcreg); store_data_long(destoffset, destval); } else { u16 destval; u16 *srcreg; destoffset = decode_rm00_address(rl); DECODE_PRINTF(","); destval = fetch_data_word(destoffset); srcreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = and_word(destval, *srcreg); store_data_word(destoffset, destval); } break; case 1: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; u32 *srcreg; destoffset = decode_rm01_address(rl); DECODE_PRINTF(","); destval = fetch_data_long(destoffset); srcreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = and_long(destval, *srcreg); store_data_long(destoffset, destval); } else { u16 destval; u16 *srcreg; destoffset = decode_rm01_address(rl); DECODE_PRINTF(","); destval = fetch_data_word(destoffset); srcreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = and_word(destval, *srcreg); store_data_word(destoffset, destval); } break; case 2: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; u32 *srcreg; destoffset = decode_rm10_address(rl); DECODE_PRINTF(","); destval = fetch_data_long(destoffset); srcreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = and_long(destval, *srcreg); store_data_long(destoffset, destval); } else { u16 destval; u16 *srcreg; destoffset = decode_rm10_address(rl); DECODE_PRINTF(","); destval = fetch_data_word(destoffset); srcreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = and_word(destval, *srcreg); store_data_word(destoffset, destval); } break; case 3: /* register to register */ if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg,*srcreg; destreg = DECODE_RM_LONG_REGISTER(rl); DECODE_PRINTF(","); srcreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = and_long(*destreg, *srcreg); } else { u16 *destreg,*srcreg; destreg = DECODE_RM_WORD_REGISTER(rl); DECODE_PRINTF(","); srcreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = and_word(*destreg, *srcreg); } break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x22 ****************************************************************************/ void x86emuOp_and_byte_R_RM(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; u8 *destreg, *srcreg; uint srcoffset; u8 srcval; START_OF_INSTR(); DECODE_PRINTF("AND\t"); FETCH_DECODE_MODRM(mod, rh, rl); switch (mod) { case 0: destreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm00_address(rl); srcval = fetch_data_byte(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = and_byte(*destreg, srcval); break; case 1: destreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm01_address(rl); srcval = fetch_data_byte(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = and_byte(*destreg, srcval); break; case 2: destreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm10_address(rl); srcval = fetch_data_byte(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = and_byte(*destreg, srcval); break; case 3: /* register to register */ destreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF(","); srcreg = DECODE_RM_BYTE_REGISTER(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = and_byte(*destreg, *srcreg); break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x23 ****************************************************************************/ void x86emuOp_and_word_R_RM(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; uint srcoffset; START_OF_INSTR(); DECODE_PRINTF("AND\t"); FETCH_DECODE_MODRM(mod, rh, rl); switch (mod) { case 0: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg; u32 srcval; destreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm00_address(rl); srcval = fetch_data_long(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = and_long(*destreg, srcval); } else { u16 *destreg; u16 srcval; destreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm00_address(rl); srcval = fetch_data_word(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = and_word(*destreg, srcval); } break; case 1: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg; u32 srcval; destreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm01_address(rl); srcval = fetch_data_long(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = and_long(*destreg, srcval); break; } else { u16 *destreg; u16 srcval; destreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm01_address(rl); srcval = fetch_data_word(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = and_word(*destreg, srcval); break; } case 2: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg; u32 srcval; destreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm10_address(rl); srcval = fetch_data_long(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = and_long(*destreg, srcval); } else { u16 *destreg; u16 srcval; destreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm10_address(rl); srcval = fetch_data_word(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = and_word(*destreg, srcval); } break; case 3: /* register to register */ if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg,*srcreg; destreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF(","); srcreg = DECODE_RM_LONG_REGISTER(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = and_long(*destreg, *srcreg); } else { u16 *destreg,*srcreg; destreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF(","); srcreg = DECODE_RM_WORD_REGISTER(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = and_word(*destreg, *srcreg); } break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x24 ****************************************************************************/ void x86emuOp_and_byte_AL_IMM(u8 X86EMU_UNUSED(op1)) { u8 srcval; START_OF_INSTR(); DECODE_PRINTF("AND\tAL,"); srcval = fetch_byte_imm(); DECODE_PRINTF2("%x\n", srcval); TRACE_AND_STEP(); M.x86.R_AL = and_byte(M.x86.R_AL, srcval); DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x25 ****************************************************************************/ void x86emuOp_and_word_AX_IMM(u8 X86EMU_UNUSED(op1)) { u32 srcval; START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("AND\tEAX,"); srcval = fetch_long_imm(); } else { DECODE_PRINTF("AND\tAX,"); srcval = fetch_word_imm(); } DECODE_PRINTF2("%x\n", srcval); TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { M.x86.R_EAX = and_long(M.x86.R_EAX, srcval); } else { M.x86.R_AX = and_word(M.x86.R_AX, (u16)srcval); } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x26 ****************************************************************************/ void x86emuOp_segovr_ES(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); DECODE_PRINTF("ES:\n"); TRACE_AND_STEP(); M.x86.mode |= SYSMODE_SEGOVR_ES; /* * note the lack of DECODE_CLEAR_SEGOVR(r) since, here is one of 4 * opcode subroutines we do not want to do this. */ END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x27 ****************************************************************************/ void x86emuOp_daa(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); DECODE_PRINTF("DAA\n"); TRACE_AND_STEP(); M.x86.R_AL = daa_byte(M.x86.R_AL); DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x28 ****************************************************************************/ void x86emuOp_sub_byte_RM_R(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; u8 *destreg, *srcreg; uint destoffset; u8 destval; START_OF_INSTR(); DECODE_PRINTF("SUB\t"); FETCH_DECODE_MODRM(mod, rh, rl); switch (mod) { case 0: destoffset = decode_rm00_address(rl); DECODE_PRINTF(","); destval = fetch_data_byte(destoffset); srcreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = sub_byte(destval, *srcreg); store_data_byte(destoffset, destval); break; case 1: destoffset = decode_rm01_address(rl); DECODE_PRINTF(","); destval = fetch_data_byte(destoffset); srcreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = sub_byte(destval, *srcreg); store_data_byte(destoffset, destval); break; case 2: destoffset = decode_rm10_address(rl); DECODE_PRINTF(","); destval = fetch_data_byte(destoffset); srcreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = sub_byte(destval, *srcreg); store_data_byte(destoffset, destval); break; case 3: /* register to register */ destreg = DECODE_RM_BYTE_REGISTER(rl); DECODE_PRINTF(","); srcreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = sub_byte(*destreg, *srcreg); break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x29 ****************************************************************************/ void x86emuOp_sub_word_RM_R(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; uint destoffset; START_OF_INSTR(); DECODE_PRINTF("SUB\t"); FETCH_DECODE_MODRM(mod, rh, rl); switch (mod) { case 0: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; u32 *srcreg; destoffset = decode_rm00_address(rl); DECODE_PRINTF(","); destval = fetch_data_long(destoffset); srcreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = sub_long(destval, *srcreg); store_data_long(destoffset, destval); } else { u16 destval; u16 *srcreg; destoffset = decode_rm00_address(rl); DECODE_PRINTF(","); destval = fetch_data_word(destoffset); srcreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = sub_word(destval, *srcreg); store_data_word(destoffset, destval); } break; case 1: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; u32 *srcreg; destoffset = decode_rm01_address(rl); DECODE_PRINTF(","); destval = fetch_data_long(destoffset); srcreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = sub_long(destval, *srcreg); store_data_long(destoffset, destval); } else { u16 destval; u16 *srcreg; destoffset = decode_rm01_address(rl); DECODE_PRINTF(","); destval = fetch_data_word(destoffset); srcreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = sub_word(destval, *srcreg); store_data_word(destoffset, destval); } break; case 2: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; u32 *srcreg; destoffset = decode_rm10_address(rl); DECODE_PRINTF(","); destval = fetch_data_long(destoffset); srcreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = sub_long(destval, *srcreg); store_data_long(destoffset, destval); } else { u16 destval; u16 *srcreg; destoffset = decode_rm10_address(rl); DECODE_PRINTF(","); destval = fetch_data_word(destoffset); srcreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = sub_word(destval, *srcreg); store_data_word(destoffset, destval); } break; case 3: /* register to register */ if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg,*srcreg; destreg = DECODE_RM_LONG_REGISTER(rl); DECODE_PRINTF(","); srcreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = sub_long(*destreg, *srcreg); } else { u16 *destreg,*srcreg; destreg = DECODE_RM_WORD_REGISTER(rl); DECODE_PRINTF(","); srcreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = sub_word(*destreg, *srcreg); } break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x2a ****************************************************************************/ void x86emuOp_sub_byte_R_RM(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; u8 *destreg, *srcreg; uint srcoffset; u8 srcval; START_OF_INSTR(); DECODE_PRINTF("SUB\t"); FETCH_DECODE_MODRM(mod, rh, rl); switch (mod) { case 0: destreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm00_address(rl); srcval = fetch_data_byte(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = sub_byte(*destreg, srcval); break; case 1: destreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm01_address(rl); srcval = fetch_data_byte(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = sub_byte(*destreg, srcval); break; case 2: destreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm10_address(rl); srcval = fetch_data_byte(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = sub_byte(*destreg, srcval); break; case 3: /* register to register */ destreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF(","); srcreg = DECODE_RM_BYTE_REGISTER(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = sub_byte(*destreg, *srcreg); break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x2b ****************************************************************************/ void x86emuOp_sub_word_R_RM(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; uint srcoffset; START_OF_INSTR(); DECODE_PRINTF("SUB\t"); FETCH_DECODE_MODRM(mod, rh, rl); switch (mod) { case 0: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg; u32 srcval; destreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm00_address(rl); srcval = fetch_data_long(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = sub_long(*destreg, srcval); } else { u16 *destreg; u16 srcval; destreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm00_address(rl); srcval = fetch_data_word(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = sub_word(*destreg, srcval); } break; case 1: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg; u32 srcval; destreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm01_address(rl); srcval = fetch_data_long(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = sub_long(*destreg, srcval); } else { u16 *destreg; u16 srcval; destreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm01_address(rl); srcval = fetch_data_word(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = sub_word(*destreg, srcval); } break; case 2: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg; u32 srcval; destreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm10_address(rl); srcval = fetch_data_long(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = sub_long(*destreg, srcval); } else { u16 *destreg; u16 srcval; destreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm10_address(rl); srcval = fetch_data_word(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = sub_word(*destreg, srcval); } break; case 3: /* register to register */ if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg,*srcreg; destreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF(","); srcreg = DECODE_RM_LONG_REGISTER(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = sub_long(*destreg, *srcreg); } else { u16 *destreg,*srcreg; destreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF(","); srcreg = DECODE_RM_WORD_REGISTER(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = sub_word(*destreg, *srcreg); } break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x2c ****************************************************************************/ void x86emuOp_sub_byte_AL_IMM(u8 X86EMU_UNUSED(op1)) { u8 srcval; START_OF_INSTR(); DECODE_PRINTF("SUB\tAL,"); srcval = fetch_byte_imm(); DECODE_PRINTF2("%x\n", srcval); TRACE_AND_STEP(); M.x86.R_AL = sub_byte(M.x86.R_AL, srcval); DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x2d ****************************************************************************/ void x86emuOp_sub_word_AX_IMM(u8 X86EMU_UNUSED(op1)) { u32 srcval; START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("SUB\tEAX,"); srcval = fetch_long_imm(); } else { DECODE_PRINTF("SUB\tAX,"); srcval = fetch_word_imm(); } DECODE_PRINTF2("%x\n", srcval); TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { M.x86.R_EAX = sub_long(M.x86.R_EAX, srcval); } else { M.x86.R_AX = sub_word(M.x86.R_AX, (u16)srcval); } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x2e ****************************************************************************/ void x86emuOp_segovr_CS(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); DECODE_PRINTF("CS:\n"); TRACE_AND_STEP(); M.x86.mode |= SYSMODE_SEGOVR_CS; /* note no DECODE_CLEAR_SEGOVR here. */ END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x2f ****************************************************************************/ void x86emuOp_das(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); DECODE_PRINTF("DAS\n"); TRACE_AND_STEP(); M.x86.R_AL = das_byte(M.x86.R_AL); DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x30 ****************************************************************************/ void x86emuOp_xor_byte_RM_R(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; u8 *destreg, *srcreg; uint destoffset; u8 destval; START_OF_INSTR(); DECODE_PRINTF("XOR\t"); FETCH_DECODE_MODRM(mod, rh, rl); switch (mod) { case 0: destoffset = decode_rm00_address(rl); DECODE_PRINTF(","); destval = fetch_data_byte(destoffset); srcreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = xor_byte(destval, *srcreg); store_data_byte(destoffset, destval); break; case 1: destoffset = decode_rm01_address(rl); DECODE_PRINTF(","); destval = fetch_data_byte(destoffset); srcreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = xor_byte(destval, *srcreg); store_data_byte(destoffset, destval); break; case 2: destoffset = decode_rm10_address(rl); DECODE_PRINTF(","); destval = fetch_data_byte(destoffset); srcreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = xor_byte(destval, *srcreg); store_data_byte(destoffset, destval); break; case 3: /* register to register */ destreg = DECODE_RM_BYTE_REGISTER(rl); DECODE_PRINTF(","); srcreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = xor_byte(*destreg, *srcreg); break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x31 ****************************************************************************/ void x86emuOp_xor_word_RM_R(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; uint destoffset; START_OF_INSTR(); DECODE_PRINTF("XOR\t"); FETCH_DECODE_MODRM(mod, rh, rl); switch (mod) { case 0: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; u32 *srcreg; destoffset = decode_rm00_address(rl); DECODE_PRINTF(","); destval = fetch_data_long(destoffset); srcreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = xor_long(destval, *srcreg); store_data_long(destoffset, destval); } else { u16 destval; u16 *srcreg; destoffset = decode_rm00_address(rl); DECODE_PRINTF(","); destval = fetch_data_word(destoffset); srcreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = xor_word(destval, *srcreg); store_data_word(destoffset, destval); } break; case 1: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; u32 *srcreg; destoffset = decode_rm01_address(rl); DECODE_PRINTF(","); destval = fetch_data_long(destoffset); srcreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = xor_long(destval, *srcreg); store_data_long(destoffset, destval); } else { u16 destval; u16 *srcreg; destoffset = decode_rm01_address(rl); DECODE_PRINTF(","); destval = fetch_data_word(destoffset); srcreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = xor_word(destval, *srcreg); store_data_word(destoffset, destval); } break; case 2: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; u32 *srcreg; destoffset = decode_rm10_address(rl); DECODE_PRINTF(","); destval = fetch_data_long(destoffset); srcreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = xor_long(destval, *srcreg); store_data_long(destoffset, destval); } else { u16 destval; u16 *srcreg; destoffset = decode_rm10_address(rl); DECODE_PRINTF(","); destval = fetch_data_word(destoffset); srcreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = xor_word(destval, *srcreg); store_data_word(destoffset, destval); } break; case 3: /* register to register */ if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg,*srcreg; destreg = DECODE_RM_LONG_REGISTER(rl); DECODE_PRINTF(","); srcreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = xor_long(*destreg, *srcreg); } else { u16 *destreg,*srcreg; destreg = DECODE_RM_WORD_REGISTER(rl); DECODE_PRINTF(","); srcreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = xor_word(*destreg, *srcreg); } break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x32 ****************************************************************************/ void x86emuOp_xor_byte_R_RM(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; u8 *destreg, *srcreg; uint srcoffset; u8 srcval; START_OF_INSTR(); DECODE_PRINTF("XOR\t"); FETCH_DECODE_MODRM(mod, rh, rl); switch (mod) { case 0: destreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm00_address(rl); srcval = fetch_data_byte(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = xor_byte(*destreg, srcval); break; case 1: destreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm01_address(rl); srcval = fetch_data_byte(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = xor_byte(*destreg, srcval); break; case 2: destreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm10_address(rl); srcval = fetch_data_byte(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = xor_byte(*destreg, srcval); break; case 3: /* register to register */ destreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF(","); srcreg = DECODE_RM_BYTE_REGISTER(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = xor_byte(*destreg, *srcreg); break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x33 ****************************************************************************/ void x86emuOp_xor_word_R_RM(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; uint srcoffset; START_OF_INSTR(); DECODE_PRINTF("XOR\t"); FETCH_DECODE_MODRM(mod, rh, rl); switch (mod) { case 0: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg; u32 srcval; destreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm00_address(rl); srcval = fetch_data_long(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = xor_long(*destreg, srcval); } else { u16 *destreg; u16 srcval; destreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm00_address(rl); srcval = fetch_data_word(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = xor_word(*destreg, srcval); } break; case 1: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg; u32 srcval; destreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm01_address(rl); srcval = fetch_data_long(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = xor_long(*destreg, srcval); } else { u16 *destreg; u16 srcval; destreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm01_address(rl); srcval = fetch_data_word(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = xor_word(*destreg, srcval); } break; case 2: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg; u32 srcval; destreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm10_address(rl); srcval = fetch_data_long(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = xor_long(*destreg, srcval); } else { u16 *destreg; u16 srcval; destreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm10_address(rl); srcval = fetch_data_word(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = xor_word(*destreg, srcval); } break; case 3: /* register to register */ if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg,*srcreg; destreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF(","); srcreg = DECODE_RM_LONG_REGISTER(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = xor_long(*destreg, *srcreg); } else { u16 *destreg,*srcreg; destreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF(","); srcreg = DECODE_RM_WORD_REGISTER(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = xor_word(*destreg, *srcreg); } break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x34 ****************************************************************************/ void x86emuOp_xor_byte_AL_IMM(u8 X86EMU_UNUSED(op1)) { u8 srcval; START_OF_INSTR(); DECODE_PRINTF("XOR\tAL,"); srcval = fetch_byte_imm(); DECODE_PRINTF2("%x\n", srcval); TRACE_AND_STEP(); M.x86.R_AL = xor_byte(M.x86.R_AL, srcval); DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x35 ****************************************************************************/ void x86emuOp_xor_word_AX_IMM(u8 X86EMU_UNUSED(op1)) { u32 srcval; START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("XOR\tEAX,"); srcval = fetch_long_imm(); } else { DECODE_PRINTF("XOR\tAX,"); srcval = fetch_word_imm(); } DECODE_PRINTF2("%x\n", srcval); TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { M.x86.R_EAX = xor_long(M.x86.R_EAX, srcval); } else { M.x86.R_AX = xor_word(M.x86.R_AX, (u16)srcval); } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x36 ****************************************************************************/ void x86emuOp_segovr_SS(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); DECODE_PRINTF("SS:\n"); TRACE_AND_STEP(); M.x86.mode |= SYSMODE_SEGOVR_SS; /* no DECODE_CLEAR_SEGOVR ! */ END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x37 ****************************************************************************/ void x86emuOp_aaa(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); DECODE_PRINTF("AAA\n"); TRACE_AND_STEP(); M.x86.R_AX = aaa_word(M.x86.R_AX); DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x38 ****************************************************************************/ void x86emuOp_cmp_byte_RM_R(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; uint destoffset; u8 *destreg, *srcreg; u8 destval; START_OF_INSTR(); DECODE_PRINTF("CMP\t"); FETCH_DECODE_MODRM(mod, rh, rl); switch (mod) { case 0: destoffset = decode_rm00_address(rl); DECODE_PRINTF(","); destval = fetch_data_byte(destoffset); srcreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); cmp_byte(destval, *srcreg); break; case 1: destoffset = decode_rm01_address(rl); DECODE_PRINTF(","); destval = fetch_data_byte(destoffset); srcreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); cmp_byte(destval, *srcreg); break; case 2: destoffset = decode_rm10_address(rl); DECODE_PRINTF(","); destval = fetch_data_byte(destoffset); srcreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); cmp_byte(destval, *srcreg); break; case 3: /* register to register */ destreg = DECODE_RM_BYTE_REGISTER(rl); DECODE_PRINTF(","); srcreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); cmp_byte(*destreg, *srcreg); break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x39 ****************************************************************************/ void x86emuOp_cmp_word_RM_R(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; uint destoffset; START_OF_INSTR(); DECODE_PRINTF("CMP\t"); FETCH_DECODE_MODRM(mod, rh, rl); switch (mod) { case 0: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; u32 *srcreg; destoffset = decode_rm00_address(rl); DECODE_PRINTF(","); destval = fetch_data_long(destoffset); srcreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); cmp_long(destval, *srcreg); } else { u16 destval; u16 *srcreg; destoffset = decode_rm00_address(rl); DECODE_PRINTF(","); destval = fetch_data_word(destoffset); srcreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); cmp_word(destval, *srcreg); } break; case 1: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; u32 *srcreg; destoffset = decode_rm01_address(rl); DECODE_PRINTF(","); destval = fetch_data_long(destoffset); srcreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); cmp_long(destval, *srcreg); } else { u16 destval; u16 *srcreg; destoffset = decode_rm01_address(rl); DECODE_PRINTF(","); destval = fetch_data_word(destoffset); srcreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); cmp_word(destval, *srcreg); } break; case 2: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; u32 *srcreg; destoffset = decode_rm10_address(rl); DECODE_PRINTF(","); destval = fetch_data_long(destoffset); srcreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); cmp_long(destval, *srcreg); } else { u16 destval; u16 *srcreg; destoffset = decode_rm10_address(rl); DECODE_PRINTF(","); destval = fetch_data_word(destoffset); srcreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); cmp_word(destval, *srcreg); } break; case 3: /* register to register */ if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg,*srcreg; destreg = DECODE_RM_LONG_REGISTER(rl); DECODE_PRINTF(","); srcreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); cmp_long(*destreg, *srcreg); } else { u16 *destreg,*srcreg; destreg = DECODE_RM_WORD_REGISTER(rl); DECODE_PRINTF(","); srcreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); cmp_word(*destreg, *srcreg); } break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x3a ****************************************************************************/ void x86emuOp_cmp_byte_R_RM(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; u8 *destreg, *srcreg; uint srcoffset; u8 srcval; START_OF_INSTR(); DECODE_PRINTF("CMP\t"); FETCH_DECODE_MODRM(mod, rh, rl); switch (mod) { case 0: destreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm00_address(rl); srcval = fetch_data_byte(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); cmp_byte(*destreg, srcval); break; case 1: destreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm01_address(rl); srcval = fetch_data_byte(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); cmp_byte(*destreg, srcval); break; case 2: destreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm10_address(rl); srcval = fetch_data_byte(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); cmp_byte(*destreg, srcval); break; case 3: /* register to register */ destreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF(","); srcreg = DECODE_RM_BYTE_REGISTER(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); cmp_byte(*destreg, *srcreg); break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x3b ****************************************************************************/ void x86emuOp_cmp_word_R_RM(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; uint srcoffset; START_OF_INSTR(); DECODE_PRINTF("CMP\t"); FETCH_DECODE_MODRM(mod, rh, rl); switch (mod) { case 0: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg; u32 srcval; destreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm00_address(rl); srcval = fetch_data_long(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); cmp_long(*destreg, srcval); } else { u16 *destreg; u16 srcval; destreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm00_address(rl); srcval = fetch_data_word(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); cmp_word(*destreg, srcval); } break; case 1: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg; u32 srcval; destreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm01_address(rl); srcval = fetch_data_long(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); cmp_long(*destreg, srcval); } else { u16 *destreg; u16 srcval; destreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm01_address(rl); srcval = fetch_data_word(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); cmp_word(*destreg, srcval); } break; case 2: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg; u32 srcval; destreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm10_address(rl); srcval = fetch_data_long(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); cmp_long(*destreg, srcval); } else { u16 *destreg; u16 srcval; destreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm10_address(rl); srcval = fetch_data_word(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); cmp_word(*destreg, srcval); } break; case 3: /* register to register */ if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg,*srcreg; destreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF(","); srcreg = DECODE_RM_LONG_REGISTER(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); cmp_long(*destreg, *srcreg); } else { u16 *destreg,*srcreg; destreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF(","); srcreg = DECODE_RM_WORD_REGISTER(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); cmp_word(*destreg, *srcreg); } break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x3c ****************************************************************************/ void x86emuOp_cmp_byte_AL_IMM(u8 X86EMU_UNUSED(op1)) { u8 srcval; START_OF_INSTR(); DECODE_PRINTF("CMP\tAL,"); srcval = fetch_byte_imm(); DECODE_PRINTF2("%x\n", srcval); TRACE_AND_STEP(); cmp_byte(M.x86.R_AL, srcval); DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x3d ****************************************************************************/ void x86emuOp_cmp_word_AX_IMM(u8 X86EMU_UNUSED(op1)) { u32 srcval; START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("CMP\tEAX,"); srcval = fetch_long_imm(); } else { DECODE_PRINTF("CMP\tAX,"); srcval = fetch_word_imm(); } DECODE_PRINTF2("%x\n", srcval); TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { cmp_long(M.x86.R_EAX, srcval); } else { cmp_word(M.x86.R_AX, (u16)srcval); } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x3e ****************************************************************************/ void x86emuOp_segovr_DS(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); DECODE_PRINTF("DS:\n"); TRACE_AND_STEP(); M.x86.mode |= SYSMODE_SEGOVR_DS; /* NO DECODE_CLEAR_SEGOVR! */ END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x3f ****************************************************************************/ void x86emuOp_aas(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); DECODE_PRINTF("AAS\n"); TRACE_AND_STEP(); M.x86.R_AX = aas_word(M.x86.R_AX); DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x40 ****************************************************************************/ void x86emuOp_inc_AX(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("INC\tEAX\n"); } else { DECODE_PRINTF("INC\tAX\n"); } TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { M.x86.R_EAX = inc_long(M.x86.R_EAX); } else { M.x86.R_AX = inc_word(M.x86.R_AX); } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x41 ****************************************************************************/ void x86emuOp_inc_CX(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("INC\tECX\n"); } else { DECODE_PRINTF("INC\tCX\n"); } TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { M.x86.R_ECX = inc_long(M.x86.R_ECX); } else { M.x86.R_CX = inc_word(M.x86.R_CX); } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x42 ****************************************************************************/ void x86emuOp_inc_DX(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("INC\tEDX\n"); } else { DECODE_PRINTF("INC\tDX\n"); } TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { M.x86.R_EDX = inc_long(M.x86.R_EDX); } else { M.x86.R_DX = inc_word(M.x86.R_DX); } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x43 ****************************************************************************/ void x86emuOp_inc_BX(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("INC\tEBX\n"); } else { DECODE_PRINTF("INC\tBX\n"); } TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { M.x86.R_EBX = inc_long(M.x86.R_EBX); } else { M.x86.R_BX = inc_word(M.x86.R_BX); } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x44 ****************************************************************************/ void x86emuOp_inc_SP(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("INC\tESP\n"); } else { DECODE_PRINTF("INC\tSP\n"); } TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { M.x86.R_ESP = inc_long(M.x86.R_ESP); } else { M.x86.R_SP = inc_word(M.x86.R_SP); } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x45 ****************************************************************************/ void x86emuOp_inc_BP(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("INC\tEBP\n"); } else { DECODE_PRINTF("INC\tBP\n"); } TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { M.x86.R_EBP = inc_long(M.x86.R_EBP); } else { M.x86.R_BP = inc_word(M.x86.R_BP); } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x46 ****************************************************************************/ void x86emuOp_inc_SI(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("INC\tESI\n"); } else { DECODE_PRINTF("INC\tSI\n"); } TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { M.x86.R_ESI = inc_long(M.x86.R_ESI); } else { M.x86.R_SI = inc_word(M.x86.R_SI); } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x47 ****************************************************************************/ void x86emuOp_inc_DI(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("INC\tEDI\n"); } else { DECODE_PRINTF("INC\tDI\n"); } TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { M.x86.R_EDI = inc_long(M.x86.R_EDI); } else { M.x86.R_DI = inc_word(M.x86.R_DI); } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x48 ****************************************************************************/ void x86emuOp_dec_AX(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("DEC\tEAX\n"); } else { DECODE_PRINTF("DEC\tAX\n"); } TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { M.x86.R_EAX = dec_long(M.x86.R_EAX); } else { M.x86.R_AX = dec_word(M.x86.R_AX); } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x49 ****************************************************************************/ void x86emuOp_dec_CX(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("DEC\tECX\n"); } else { DECODE_PRINTF("DEC\tCX\n"); } TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { M.x86.R_ECX = dec_long(M.x86.R_ECX); } else { M.x86.R_CX = dec_word(M.x86.R_CX); } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x4a ****************************************************************************/ void x86emuOp_dec_DX(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("DEC\tEDX\n"); } else { DECODE_PRINTF("DEC\tDX\n"); } TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { M.x86.R_EDX = dec_long(M.x86.R_EDX); } else { M.x86.R_DX = dec_word(M.x86.R_DX); } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x4b ****************************************************************************/ void x86emuOp_dec_BX(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("DEC\tEBX\n"); } else { DECODE_PRINTF("DEC\tBX\n"); } TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { M.x86.R_EBX = dec_long(M.x86.R_EBX); } else { M.x86.R_BX = dec_word(M.x86.R_BX); } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x4c ****************************************************************************/ void x86emuOp_dec_SP(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("DEC\tESP\n"); } else { DECODE_PRINTF("DEC\tSP\n"); } TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { M.x86.R_ESP = dec_long(M.x86.R_ESP); } else { M.x86.R_SP = dec_word(M.x86.R_SP); } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x4d ****************************************************************************/ void x86emuOp_dec_BP(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("DEC\tEBP\n"); } else { DECODE_PRINTF("DEC\tBP\n"); } TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { M.x86.R_EBP = dec_long(M.x86.R_EBP); } else { M.x86.R_BP = dec_word(M.x86.R_BP); } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x4e ****************************************************************************/ void x86emuOp_dec_SI(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("DEC\tESI\n"); } else { DECODE_PRINTF("DEC\tSI\n"); } TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { M.x86.R_ESI = dec_long(M.x86.R_ESI); } else { M.x86.R_SI = dec_word(M.x86.R_SI); } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x4f ****************************************************************************/ void x86emuOp_dec_DI(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("DEC\tEDI\n"); } else { DECODE_PRINTF("DEC\tDI\n"); } TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { M.x86.R_EDI = dec_long(M.x86.R_EDI); } else { M.x86.R_DI = dec_word(M.x86.R_DI); } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x50 ****************************************************************************/ void x86emuOp_push_AX(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("PUSH\tEAX\n"); } else { DECODE_PRINTF("PUSH\tAX\n"); } TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { push_long(M.x86.R_EAX); } else { push_word(M.x86.R_AX); } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x51 ****************************************************************************/ void x86emuOp_push_CX(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("PUSH\tECX\n"); } else { DECODE_PRINTF("PUSH\tCX\n"); } TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { push_long(M.x86.R_ECX); } else { push_word(M.x86.R_CX); } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x52 ****************************************************************************/ void x86emuOp_push_DX(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("PUSH\tEDX\n"); } else { DECODE_PRINTF("PUSH\tDX\n"); } TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { push_long(M.x86.R_EDX); } else { push_word(M.x86.R_DX); } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x53 ****************************************************************************/ void x86emuOp_push_BX(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("PUSH\tEBX\n"); } else { DECODE_PRINTF("PUSH\tBX\n"); } TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { push_long(M.x86.R_EBX); } else { push_word(M.x86.R_BX); } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x54 ****************************************************************************/ void x86emuOp_push_SP(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("PUSH\tESP\n"); } else { DECODE_PRINTF("PUSH\tSP\n"); } TRACE_AND_STEP(); /* Always push (E)SP, since we are emulating an i386 and above * processor. This is necessary as some BIOS'es use this to check * what type of processor is in the system. */ if (M.x86.mode & SYSMODE_PREFIX_DATA) { push_long(M.x86.R_ESP); } else { push_word((u16)(M.x86.R_SP)); } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x55 ****************************************************************************/ void x86emuOp_push_BP(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("PUSH\tEBP\n"); } else { DECODE_PRINTF("PUSH\tBP\n"); } TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { push_long(M.x86.R_EBP); } else { push_word(M.x86.R_BP); } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x56 ****************************************************************************/ void x86emuOp_push_SI(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("PUSH\tESI\n"); } else { DECODE_PRINTF("PUSH\tSI\n"); } TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { push_long(M.x86.R_ESI); } else { push_word(M.x86.R_SI); } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x57 ****************************************************************************/ void x86emuOp_push_DI(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("PUSH\tEDI\n"); } else { DECODE_PRINTF("PUSH\tDI\n"); } TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { push_long(M.x86.R_EDI); } else { push_word(M.x86.R_DI); } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x58 ****************************************************************************/ void x86emuOp_pop_AX(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("POP\tEAX\n"); } else { DECODE_PRINTF("POP\tAX\n"); } TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { M.x86.R_EAX = pop_long(); } else { M.x86.R_AX = pop_word(); } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x59 ****************************************************************************/ void x86emuOp_pop_CX(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("POP\tECX\n"); } else { DECODE_PRINTF("POP\tCX\n"); } TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { M.x86.R_ECX = pop_long(); } else { M.x86.R_CX = pop_word(); } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x5a ****************************************************************************/ void x86emuOp_pop_DX(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("POP\tEDX\n"); } else { DECODE_PRINTF("POP\tDX\n"); } TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { M.x86.R_EDX = pop_long(); } else { M.x86.R_DX = pop_word(); } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x5b ****************************************************************************/ void x86emuOp_pop_BX(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("POP\tEBX\n"); } else { DECODE_PRINTF("POP\tBX\n"); } TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { M.x86.R_EBX = pop_long(); } else { M.x86.R_BX = pop_word(); } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x5c ****************************************************************************/ void x86emuOp_pop_SP(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("POP\tESP\n"); } else { DECODE_PRINTF("POP\tSP\n"); } TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { M.x86.R_ESP = pop_long(); } else { M.x86.R_SP = pop_word(); } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x5d ****************************************************************************/ void x86emuOp_pop_BP(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("POP\tEBP\n"); } else { DECODE_PRINTF("POP\tBP\n"); } TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { M.x86.R_EBP = pop_long(); } else { M.x86.R_BP = pop_word(); } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x5e ****************************************************************************/ void x86emuOp_pop_SI(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("POP\tESI\n"); } else { DECODE_PRINTF("POP\tSI\n"); } TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { M.x86.R_ESI = pop_long(); } else { M.x86.R_SI = pop_word(); } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x5f ****************************************************************************/ void x86emuOp_pop_DI(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("POP\tEDI\n"); } else { DECODE_PRINTF("POP\tDI\n"); } TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { M.x86.R_EDI = pop_long(); } else { M.x86.R_DI = pop_word(); } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x60 ****************************************************************************/ void x86emuOp_push_all(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("PUSHAD\n"); } else { DECODE_PRINTF("PUSHA\n"); } TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 old_sp = M.x86.R_ESP; push_long(M.x86.R_EAX); push_long(M.x86.R_ECX); push_long(M.x86.R_EDX); push_long(M.x86.R_EBX); push_long(old_sp); push_long(M.x86.R_EBP); push_long(M.x86.R_ESI); push_long(M.x86.R_EDI); } else { u16 old_sp = M.x86.R_SP; push_word(M.x86.R_AX); push_word(M.x86.R_CX); push_word(M.x86.R_DX); push_word(M.x86.R_BX); push_word(old_sp); push_word(M.x86.R_BP); push_word(M.x86.R_SI); push_word(M.x86.R_DI); } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x61 ****************************************************************************/ void x86emuOp_pop_all(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("POPAD\n"); } else { DECODE_PRINTF("POPA\n"); } TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { M.x86.R_EDI = pop_long(); M.x86.R_ESI = pop_long(); M.x86.R_EBP = pop_long(); M.x86.R_ESP += 4; /* skip ESP */ M.x86.R_EBX = pop_long(); M.x86.R_EDX = pop_long(); M.x86.R_ECX = pop_long(); M.x86.R_EAX = pop_long(); } else { M.x86.R_DI = pop_word(); M.x86.R_SI = pop_word(); M.x86.R_BP = pop_word(); M.x86.R_SP += 2; /* skip SP */ M.x86.R_BX = pop_word(); M.x86.R_DX = pop_word(); M.x86.R_CX = pop_word(); M.x86.R_AX = pop_word(); } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /*opcode 0x62 ILLEGAL OP, calls x86emuOp_illegal_op() */ /*opcode 0x63 ILLEGAL OP, calls x86emuOp_illegal_op() */ /**************************************************************************** REMARKS: Handles opcode 0x64 ****************************************************************************/ void x86emuOp_segovr_FS(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); DECODE_PRINTF("FS:\n"); TRACE_AND_STEP(); M.x86.mode |= SYSMODE_SEGOVR_FS; /* * note the lack of DECODE_CLEAR_SEGOVR(r) since, here is one of 4 * opcode subroutines we do not want to do this. */ END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x65 ****************************************************************************/ void x86emuOp_segovr_GS(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); DECODE_PRINTF("GS:\n"); TRACE_AND_STEP(); M.x86.mode |= SYSMODE_SEGOVR_GS; /* * note the lack of DECODE_CLEAR_SEGOVR(r) since, here is one of 4 * opcode subroutines we do not want to do this. */ END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x66 - prefix for 32-bit register ****************************************************************************/ void x86emuOp_prefix_data(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); DECODE_PRINTF("DATA:\n"); TRACE_AND_STEP(); M.x86.mode |= SYSMODE_PREFIX_DATA; /* note no DECODE_CLEAR_SEGOVR here. */ END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x67 - prefix for 32-bit address ****************************************************************************/ void x86emuOp_prefix_addr(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); DECODE_PRINTF("ADDR:\n"); TRACE_AND_STEP(); M.x86.mode |= SYSMODE_PREFIX_ADDR; /* note no DECODE_CLEAR_SEGOVR here. */ END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x68 ****************************************************************************/ void x86emuOp_push_word_IMM(u8 X86EMU_UNUSED(op1)) { u32 imm; START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { imm = fetch_long_imm(); } else { imm = fetch_word_imm(); } DECODE_PRINTF2("PUSH\t%x\n", imm); TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { push_long(imm); } else { push_word((u16)imm); } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x69 ****************************************************************************/ void x86emuOp_imul_word_IMM(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; uint srcoffset; START_OF_INSTR(); DECODE_PRINTF("IMUL\t"); FETCH_DECODE_MODRM(mod, rh, rl); switch (mod) { case 0: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg; u32 srcval; u32 res_lo,res_hi; s32 imm; destreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm00_address(rl); srcval = fetch_data_long(srcoffset); imm = fetch_long_imm(); DECODE_PRINTF2(",%d\n", (s32)imm); TRACE_AND_STEP(); imul_long_direct(&res_lo,&res_hi,(s32)srcval,(s32)imm); if (res_hi != 0) { SET_FLAG(F_CF); SET_FLAG(F_OF); } else { CLEAR_FLAG(F_CF); CLEAR_FLAG(F_OF); } *destreg = (u32)res_lo; } else { u16 *destreg; u16 srcval; u32 res; s16 imm; destreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm00_address(rl); srcval = fetch_data_word(srcoffset); imm = fetch_word_imm(); DECODE_PRINTF2(",%d\n", (s32)imm); TRACE_AND_STEP(); res = (s16)srcval * (s16)imm; if (res > 0xFFFF) { SET_FLAG(F_CF); SET_FLAG(F_OF); } else { CLEAR_FLAG(F_CF); CLEAR_FLAG(F_OF); } *destreg = (u16)res; } break; case 1: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg; u32 srcval; u32 res_lo,res_hi; s32 imm; destreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm01_address(rl); srcval = fetch_data_long(srcoffset); imm = fetch_long_imm(); DECODE_PRINTF2(",%d\n", (s32)imm); TRACE_AND_STEP(); imul_long_direct(&res_lo,&res_hi,(s32)srcval,(s32)imm); if (res_hi != 0) { SET_FLAG(F_CF); SET_FLAG(F_OF); } else { CLEAR_FLAG(F_CF); CLEAR_FLAG(F_OF); } *destreg = (u32)res_lo; } else { u16 *destreg; u16 srcval; u32 res; s16 imm; destreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm01_address(rl); srcval = fetch_data_word(srcoffset); imm = fetch_word_imm(); DECODE_PRINTF2(",%d\n", (s32)imm); TRACE_AND_STEP(); res = (s16)srcval * (s16)imm; if (res > 0xFFFF) { SET_FLAG(F_CF); SET_FLAG(F_OF); } else { CLEAR_FLAG(F_CF); CLEAR_FLAG(F_OF); } *destreg = (u16)res; } break; case 2: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg; u32 srcval; u32 res_lo,res_hi; s32 imm; destreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm10_address(rl); srcval = fetch_data_long(srcoffset); imm = fetch_long_imm(); DECODE_PRINTF2(",%d\n", (s32)imm); TRACE_AND_STEP(); imul_long_direct(&res_lo,&res_hi,(s32)srcval,(s32)imm); if (res_hi != 0) { SET_FLAG(F_CF); SET_FLAG(F_OF); } else { CLEAR_FLAG(F_CF); CLEAR_FLAG(F_OF); } *destreg = (u32)res_lo; } else { u16 *destreg; u16 srcval; u32 res; s16 imm; destreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm10_address(rl); srcval = fetch_data_word(srcoffset); imm = fetch_word_imm(); DECODE_PRINTF2(",%d\n", (s32)imm); TRACE_AND_STEP(); res = (s16)srcval * (s16)imm; if (res > 0xFFFF) { SET_FLAG(F_CF); SET_FLAG(F_OF); } else { CLEAR_FLAG(F_CF); CLEAR_FLAG(F_OF); } *destreg = (u16)res; } break; case 3: /* register to register */ if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg,*srcreg; u32 res_lo,res_hi; s32 imm; destreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF(","); srcreg = DECODE_RM_LONG_REGISTER(rl); imm = fetch_long_imm(); DECODE_PRINTF2(",%d\n", (s32)imm); TRACE_AND_STEP(); imul_long_direct(&res_lo,&res_hi,(s32)*srcreg,(s32)imm); if (res_hi != 0) { SET_FLAG(F_CF); SET_FLAG(F_OF); } else { CLEAR_FLAG(F_CF); CLEAR_FLAG(F_OF); } *destreg = (u32)res_lo; } else { u16 *destreg,*srcreg; u32 res; s16 imm; destreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF(","); srcreg = DECODE_RM_WORD_REGISTER(rl); imm = fetch_word_imm(); DECODE_PRINTF2(",%d\n", (s32)imm); res = (s16)*srcreg * (s16)imm; if (res > 0xFFFF) { SET_FLAG(F_CF); SET_FLAG(F_OF); } else { CLEAR_FLAG(F_CF); CLEAR_FLAG(F_OF); } *destreg = (u16)res; } break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x6a ****************************************************************************/ void x86emuOp_push_byte_IMM(u8 X86EMU_UNUSED(op1)) { s16 imm; START_OF_INSTR(); imm = (s8)fetch_byte_imm(); DECODE_PRINTF2("PUSH\t%d\n", imm); TRACE_AND_STEP(); push_word(imm); DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x6b ****************************************************************************/ void x86emuOp_imul_byte_IMM(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; uint srcoffset; s8 imm; START_OF_INSTR(); DECODE_PRINTF("IMUL\t"); FETCH_DECODE_MODRM(mod, rh, rl); switch (mod) { case 0: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg; u32 srcval; u32 res_lo,res_hi; destreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm00_address(rl); srcval = fetch_data_long(srcoffset); imm = fetch_byte_imm(); DECODE_PRINTF2(",%d\n", (s32)imm); TRACE_AND_STEP(); imul_long_direct(&res_lo,&res_hi,(s32)srcval,(s32)imm); if (res_hi != 0) { SET_FLAG(F_CF); SET_FLAG(F_OF); } else { CLEAR_FLAG(F_CF); CLEAR_FLAG(F_OF); } *destreg = (u32)res_lo; } else { u16 *destreg; u16 srcval; u32 res; destreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm00_address(rl); srcval = fetch_data_word(srcoffset); imm = fetch_byte_imm(); DECODE_PRINTF2(",%d\n", (s32)imm); TRACE_AND_STEP(); res = (s16)srcval * (s16)imm; if (res > 0xFFFF) { SET_FLAG(F_CF); SET_FLAG(F_OF); } else { CLEAR_FLAG(F_CF); CLEAR_FLAG(F_OF); } *destreg = (u16)res; } break; case 1: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg; u32 srcval; u32 res_lo,res_hi; destreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm01_address(rl); srcval = fetch_data_long(srcoffset); imm = fetch_byte_imm(); DECODE_PRINTF2(",%d\n", (s32)imm); TRACE_AND_STEP(); imul_long_direct(&res_lo,&res_hi,(s32)srcval,(s32)imm); if (res_hi != 0) { SET_FLAG(F_CF); SET_FLAG(F_OF); } else { CLEAR_FLAG(F_CF); CLEAR_FLAG(F_OF); } *destreg = (u32)res_lo; } else { u16 *destreg; u16 srcval; u32 res; destreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm01_address(rl); srcval = fetch_data_word(srcoffset); imm = fetch_byte_imm(); DECODE_PRINTF2(",%d\n", (s32)imm); TRACE_AND_STEP(); res = (s16)srcval * (s16)imm; if (res > 0xFFFF) { SET_FLAG(F_CF); SET_FLAG(F_OF); } else { CLEAR_FLAG(F_CF); CLEAR_FLAG(F_OF); } *destreg = (u16)res; } break; case 2: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg; u32 srcval; u32 res_lo,res_hi; destreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm10_address(rl); srcval = fetch_data_long(srcoffset); imm = fetch_byte_imm(); DECODE_PRINTF2(",%d\n", (s32)imm); TRACE_AND_STEP(); imul_long_direct(&res_lo,&res_hi,(s32)srcval,(s32)imm); if (res_hi != 0) { SET_FLAG(F_CF); SET_FLAG(F_OF); } else { CLEAR_FLAG(F_CF); CLEAR_FLAG(F_OF); } *destreg = (u32)res_lo; } else { u16 *destreg; u16 srcval; u32 res; destreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm10_address(rl); srcval = fetch_data_word(srcoffset); imm = fetch_byte_imm(); DECODE_PRINTF2(",%d\n", (s32)imm); TRACE_AND_STEP(); res = (s16)srcval * (s16)imm; if (res > 0xFFFF) { SET_FLAG(F_CF); SET_FLAG(F_OF); } else { CLEAR_FLAG(F_CF); CLEAR_FLAG(F_OF); } *destreg = (u16)res; } break; case 3: /* register to register */ if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg,*srcreg; u32 res_lo,res_hi; destreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF(","); srcreg = DECODE_RM_LONG_REGISTER(rl); imm = fetch_byte_imm(); DECODE_PRINTF2(",%d\n", (s32)imm); TRACE_AND_STEP(); imul_long_direct(&res_lo,&res_hi,(s32)*srcreg,(s32)imm); if (res_hi != 0) { SET_FLAG(F_CF); SET_FLAG(F_OF); } else { CLEAR_FLAG(F_CF); CLEAR_FLAG(F_OF); } *destreg = (u32)res_lo; } else { u16 *destreg,*srcreg; u32 res; destreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF(","); srcreg = DECODE_RM_WORD_REGISTER(rl); imm = fetch_byte_imm(); DECODE_PRINTF2(",%d\n", (s32)imm); res = (s16)*srcreg * (s16)imm; if (res > 0xFFFF) { SET_FLAG(F_CF); SET_FLAG(F_OF); } else { CLEAR_FLAG(F_CF); CLEAR_FLAG(F_OF); } *destreg = (u16)res; } break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x6c ****************************************************************************/ void x86emuOp_ins_byte(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); DECODE_PRINTF("INSB\n"); ins(1); TRACE_AND_STEP(); DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x6d ****************************************************************************/ void x86emuOp_ins_word(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("INSD\n"); ins(4); } else { DECODE_PRINTF("INSW\n"); ins(2); } TRACE_AND_STEP(); DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x6e ****************************************************************************/ void x86emuOp_outs_byte(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); DECODE_PRINTF("OUTSB\n"); outs(1); TRACE_AND_STEP(); DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x6f ****************************************************************************/ void x86emuOp_outs_word(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("OUTSD\n"); outs(4); } else { DECODE_PRINTF("OUTSW\n"); outs(2); } TRACE_AND_STEP(); DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x70 ****************************************************************************/ void x86emuOp_jump_near_O(u8 X86EMU_UNUSED(op1)) { s8 offset; u16 target; /* jump to byte offset if overflow flag is set */ START_OF_INSTR(); DECODE_PRINTF("JO\t"); offset = (s8)fetch_byte_imm(); target = (u16)(M.x86.R_IP + (s16)offset); DECODE_PRINTF2("%x\n", target); TRACE_AND_STEP(); if (ACCESS_FLAG(F_OF)) M.x86.R_IP = target; DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x71 ****************************************************************************/ void x86emuOp_jump_near_NO(u8 X86EMU_UNUSED(op1)) { s8 offset; u16 target; /* jump to byte offset if overflow is not set */ START_OF_INSTR(); DECODE_PRINTF("JNO\t"); offset = (s8)fetch_byte_imm(); target = (u16)(M.x86.R_IP + (s16)offset); DECODE_PRINTF2("%x\n", target); TRACE_AND_STEP(); if (!ACCESS_FLAG(F_OF)) M.x86.R_IP = target; DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x72 ****************************************************************************/ void x86emuOp_jump_near_B(u8 X86EMU_UNUSED(op1)) { s8 offset; u16 target; /* jump to byte offset if carry flag is set. */ START_OF_INSTR(); DECODE_PRINTF("JB\t"); offset = (s8)fetch_byte_imm(); target = (u16)(M.x86.R_IP + (s16)offset); DECODE_PRINTF2("%x\n", target); TRACE_AND_STEP(); if (ACCESS_FLAG(F_CF)) M.x86.R_IP = target; DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x73 ****************************************************************************/ void x86emuOp_jump_near_NB(u8 X86EMU_UNUSED(op1)) { s8 offset; u16 target; /* jump to byte offset if carry flag is clear. */ START_OF_INSTR(); DECODE_PRINTF("JNB\t"); offset = (s8)fetch_byte_imm(); target = (u16)(M.x86.R_IP + (s16)offset); DECODE_PRINTF2("%x\n", target); TRACE_AND_STEP(); if (!ACCESS_FLAG(F_CF)) M.x86.R_IP = target; DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x74 ****************************************************************************/ void x86emuOp_jump_near_Z(u8 X86EMU_UNUSED(op1)) { s8 offset; u16 target; /* jump to byte offset if zero flag is set. */ START_OF_INSTR(); DECODE_PRINTF("JZ\t"); offset = (s8)fetch_byte_imm(); target = (u16)(M.x86.R_IP + (s16)offset); DECODE_PRINTF2("%x\n", target); TRACE_AND_STEP(); if (ACCESS_FLAG(F_ZF)) M.x86.R_IP = target; DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x75 ****************************************************************************/ void x86emuOp_jump_near_NZ(u8 X86EMU_UNUSED(op1)) { s8 offset; u16 target; /* jump to byte offset if zero flag is clear. */ START_OF_INSTR(); DECODE_PRINTF("JNZ\t"); offset = (s8)fetch_byte_imm(); target = (u16)(M.x86.R_IP + (s16)offset); DECODE_PRINTF2("%x\n", target); TRACE_AND_STEP(); if (!ACCESS_FLAG(F_ZF)) M.x86.R_IP = target; DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x76 ****************************************************************************/ void x86emuOp_jump_near_BE(u8 X86EMU_UNUSED(op1)) { s8 offset; u16 target; /* jump to byte offset if carry flag is set or if the zero flag is set. */ START_OF_INSTR(); DECODE_PRINTF("JBE\t"); offset = (s8)fetch_byte_imm(); target = (u16)(M.x86.R_IP + (s16)offset); DECODE_PRINTF2("%x\n", target); TRACE_AND_STEP(); if (ACCESS_FLAG(F_CF) || ACCESS_FLAG(F_ZF)) M.x86.R_IP = target; DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x77 ****************************************************************************/ void x86emuOp_jump_near_NBE(u8 X86EMU_UNUSED(op1)) { s8 offset; u16 target; /* jump to byte offset if carry flag is clear and if the zero flag is clear */ START_OF_INSTR(); DECODE_PRINTF("JNBE\t"); offset = (s8)fetch_byte_imm(); target = (u16)(M.x86.R_IP + (s16)offset); DECODE_PRINTF2("%x\n", target); TRACE_AND_STEP(); if (!(ACCESS_FLAG(F_CF) || ACCESS_FLAG(F_ZF))) M.x86.R_IP = target; DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x78 ****************************************************************************/ void x86emuOp_jump_near_S(u8 X86EMU_UNUSED(op1)) { s8 offset; u16 target; /* jump to byte offset if sign flag is set */ START_OF_INSTR(); DECODE_PRINTF("JS\t"); offset = (s8)fetch_byte_imm(); target = (u16)(M.x86.R_IP + (s16)offset); DECODE_PRINTF2("%x\n", target); TRACE_AND_STEP(); if (ACCESS_FLAG(F_SF)) M.x86.R_IP = target; DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x79 ****************************************************************************/ void x86emuOp_jump_near_NS(u8 X86EMU_UNUSED(op1)) { s8 offset; u16 target; /* jump to byte offset if sign flag is clear */ START_OF_INSTR(); DECODE_PRINTF("JNS\t"); offset = (s8)fetch_byte_imm(); target = (u16)(M.x86.R_IP + (s16)offset); DECODE_PRINTF2("%x\n", target); TRACE_AND_STEP(); if (!ACCESS_FLAG(F_SF)) M.x86.R_IP = target; DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x7a ****************************************************************************/ void x86emuOp_jump_near_P(u8 X86EMU_UNUSED(op1)) { s8 offset; u16 target; /* jump to byte offset if parity flag is set (even parity) */ START_OF_INSTR(); DECODE_PRINTF("JP\t"); offset = (s8)fetch_byte_imm(); target = (u16)(M.x86.R_IP + (s16)offset); DECODE_PRINTF2("%x\n", target); TRACE_AND_STEP(); if (ACCESS_FLAG(F_PF)) M.x86.R_IP = target; DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x7b ****************************************************************************/ void x86emuOp_jump_near_NP(u8 X86EMU_UNUSED(op1)) { s8 offset; u16 target; /* jump to byte offset if parity flag is clear (odd parity) */ START_OF_INSTR(); DECODE_PRINTF("JNP\t"); offset = (s8)fetch_byte_imm(); target = (u16)(M.x86.R_IP + (s16)offset); DECODE_PRINTF2("%x\n", target); TRACE_AND_STEP(); if (!ACCESS_FLAG(F_PF)) M.x86.R_IP = target; DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x7c ****************************************************************************/ void x86emuOp_jump_near_L(u8 X86EMU_UNUSED(op1)) { s8 offset; u16 target; int sf, of; /* jump to byte offset if sign flag not equal to overflow flag. */ START_OF_INSTR(); DECODE_PRINTF("JL\t"); offset = (s8)fetch_byte_imm(); target = (u16)(M.x86.R_IP + (s16)offset); DECODE_PRINTF2("%x\n", target); TRACE_AND_STEP(); sf = ACCESS_FLAG(F_SF) != 0; of = ACCESS_FLAG(F_OF) != 0; if (sf ^ of) M.x86.R_IP = target; DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x7d ****************************************************************************/ void x86emuOp_jump_near_NL(u8 X86EMU_UNUSED(op1)) { s8 offset; u16 target; int sf, of; /* jump to byte offset if sign flag not equal to overflow flag. */ START_OF_INSTR(); DECODE_PRINTF("JNL\t"); offset = (s8)fetch_byte_imm(); target = (u16)(M.x86.R_IP + (s16)offset); DECODE_PRINTF2("%x\n", target); TRACE_AND_STEP(); sf = ACCESS_FLAG(F_SF) != 0; of = ACCESS_FLAG(F_OF) != 0; /* note: inverse of above, but using == instead of xor. */ if (sf == of) M.x86.R_IP = target; DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x7e ****************************************************************************/ void x86emuOp_jump_near_LE(u8 X86EMU_UNUSED(op1)) { s8 offset; u16 target; int sf, of; /* jump to byte offset if sign flag not equal to overflow flag or the zero flag is set */ START_OF_INSTR(); DECODE_PRINTF("JLE\t"); offset = (s8)fetch_byte_imm(); target = (u16)(M.x86.R_IP + (s16)offset); DECODE_PRINTF2("%x\n", target); TRACE_AND_STEP(); sf = ACCESS_FLAG(F_SF) != 0; of = ACCESS_FLAG(F_OF) != 0; if ((sf ^ of) || ACCESS_FLAG(F_ZF)) M.x86.R_IP = target; DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x7f ****************************************************************************/ void x86emuOp_jump_near_NLE(u8 X86EMU_UNUSED(op1)) { s8 offset; u16 target; int sf, of; /* jump to byte offset if sign flag equal to overflow flag. and the zero flag is clear */ START_OF_INSTR(); DECODE_PRINTF("JNLE\t"); offset = (s8)fetch_byte_imm(); target = (u16)(M.x86.R_IP + (s16)offset); DECODE_PRINTF2("%x\n", target); TRACE_AND_STEP(); sf = ACCESS_FLAG(F_SF) != 0; of = ACCESS_FLAG(F_OF) != 0; if ((sf == of) && !ACCESS_FLAG(F_ZF)) M.x86.R_IP = target; DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } static u8 (*opc80_byte_operation[])(u8 d, u8 s) = { add_byte, /* 00 */ or_byte, /* 01 */ adc_byte, /* 02 */ sbb_byte, /* 03 */ and_byte, /* 04 */ sub_byte, /* 05 */ xor_byte, /* 06 */ cmp_byte, /* 07 */ }; /**************************************************************************** REMARKS: Handles opcode 0x80 ****************************************************************************/ void x86emuOp_opc80_byte_RM_IMM(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; u8 *destreg; uint destoffset; u8 imm; u8 destval; /* * Weirdo special case instruction format. Part of the opcode * held below in "RH". Doubly nested case would result, except * that the decoded instruction */ START_OF_INSTR(); FETCH_DECODE_MODRM(mod, rh, rl); #ifdef DEBUG if (DEBUG_DECODE()) { /* XXX DECODE_PRINTF may be changed to something more general, so that it is important to leave the strings in the same format, even though the result is that the above test is done twice. */ switch (rh) { case 0: DECODE_PRINTF("ADD\t"); break; case 1: DECODE_PRINTF("OR\t"); break; case 2: DECODE_PRINTF("ADC\t"); break; case 3: DECODE_PRINTF("SBB\t"); break; case 4: DECODE_PRINTF("AND\t"); break; case 5: DECODE_PRINTF("SUB\t"); break; case 6: DECODE_PRINTF("XOR\t"); break; case 7: DECODE_PRINTF("CMP\t"); break; } } #endif /* know operation, decode the mod byte to find the addressing mode. */ switch (mod) { case 0: DECODE_PRINTF("BYTE PTR "); destoffset = decode_rm00_address(rl); DECODE_PRINTF(","); destval = fetch_data_byte(destoffset); imm = fetch_byte_imm(); DECODE_PRINTF2("%x\n", imm); TRACE_AND_STEP(); destval = (*opc80_byte_operation[rh]) (destval, imm); if (rh != 7) store_data_byte(destoffset, destval); break; case 1: DECODE_PRINTF("BYTE PTR "); destoffset = decode_rm01_address(rl); DECODE_PRINTF(","); destval = fetch_data_byte(destoffset); imm = fetch_byte_imm(); DECODE_PRINTF2("%x\n", imm); TRACE_AND_STEP(); destval = (*opc80_byte_operation[rh]) (destval, imm); if (rh != 7) store_data_byte(destoffset, destval); break; case 2: DECODE_PRINTF("BYTE PTR "); destoffset = decode_rm10_address(rl); DECODE_PRINTF(","); destval = fetch_data_byte(destoffset); imm = fetch_byte_imm(); DECODE_PRINTF2("%x\n", imm); TRACE_AND_STEP(); destval = (*opc80_byte_operation[rh]) (destval, imm); if (rh != 7) store_data_byte(destoffset, destval); break; case 3: /* register to register */ destreg = DECODE_RM_BYTE_REGISTER(rl); DECODE_PRINTF(","); imm = fetch_byte_imm(); DECODE_PRINTF2("%x\n", imm); TRACE_AND_STEP(); destval = (*opc80_byte_operation[rh]) (*destreg, imm); if (rh != 7) *destreg = destval; break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } static u16 (*opc81_word_operation[])(u16 d, u16 s) = { add_word, /*00 */ or_word, /*01 */ adc_word, /*02 */ sbb_word, /*03 */ and_word, /*04 */ sub_word, /*05 */ xor_word, /*06 */ cmp_word, /*07 */ }; static u32 (*opc81_long_operation[])(u32 d, u32 s) = { add_long, /*00 */ or_long, /*01 */ adc_long, /*02 */ sbb_long, /*03 */ and_long, /*04 */ sub_long, /*05 */ xor_long, /*06 */ cmp_long, /*07 */ }; /**************************************************************************** REMARKS: Handles opcode 0x81 ****************************************************************************/ void x86emuOp_opc81_word_RM_IMM(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; uint destoffset; /* * Weirdo special case instruction format. Part of the opcode * held below in "RH". Doubly nested case would result, except * that the decoded instruction */ START_OF_INSTR(); FETCH_DECODE_MODRM(mod, rh, rl); #ifdef DEBUG if (DEBUG_DECODE()) { /* XXX DECODE_PRINTF may be changed to something more general, so that it is important to leave the strings in the same format, even though the result is that the above test is done twice. */ switch (rh) { case 0: DECODE_PRINTF("ADD\t"); break; case 1: DECODE_PRINTF("OR\t"); break; case 2: DECODE_PRINTF("ADC\t"); break; case 3: DECODE_PRINTF("SBB\t"); break; case 4: DECODE_PRINTF("AND\t"); break; case 5: DECODE_PRINTF("SUB\t"); break; case 6: DECODE_PRINTF("XOR\t"); break; case 7: DECODE_PRINTF("CMP\t"); break; } } #endif /* * Know operation, decode the mod byte to find the addressing * mode. */ switch (mod) { case 0: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval,imm; DECODE_PRINTF("DWORD PTR "); destoffset = decode_rm00_address(rl); DECODE_PRINTF(","); destval = fetch_data_long(destoffset); imm = fetch_long_imm(); DECODE_PRINTF2("%x\n", imm); TRACE_AND_STEP(); destval = (*opc81_long_operation[rh]) (destval, imm); if (rh != 7) store_data_long(destoffset, destval); } else { u16 destval,imm; DECODE_PRINTF("WORD PTR "); destoffset = decode_rm00_address(rl); DECODE_PRINTF(","); destval = fetch_data_word(destoffset); imm = fetch_word_imm(); DECODE_PRINTF2("%x\n", imm); TRACE_AND_STEP(); destval = (*opc81_word_operation[rh]) (destval, imm); if (rh != 7) store_data_word(destoffset, destval); } break; case 1: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval,imm; DECODE_PRINTF("DWORD PTR "); destoffset = decode_rm01_address(rl); DECODE_PRINTF(","); destval = fetch_data_long(destoffset); imm = fetch_long_imm(); DECODE_PRINTF2("%x\n", imm); TRACE_AND_STEP(); destval = (*opc81_long_operation[rh]) (destval, imm); if (rh != 7) store_data_long(destoffset, destval); } else { u16 destval,imm; DECODE_PRINTF("WORD PTR "); destoffset = decode_rm01_address(rl); DECODE_PRINTF(","); destval = fetch_data_word(destoffset); imm = fetch_word_imm(); DECODE_PRINTF2("%x\n", imm); TRACE_AND_STEP(); destval = (*opc81_word_operation[rh]) (destval, imm); if (rh != 7) store_data_word(destoffset, destval); } break; case 2: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval,imm; DECODE_PRINTF("DWORD PTR "); destoffset = decode_rm10_address(rl); DECODE_PRINTF(","); destval = fetch_data_long(destoffset); imm = fetch_long_imm(); DECODE_PRINTF2("%x\n", imm); TRACE_AND_STEP(); destval = (*opc81_long_operation[rh]) (destval, imm); if (rh != 7) store_data_long(destoffset, destval); } else { u16 destval,imm; DECODE_PRINTF("WORD PTR "); destoffset = decode_rm10_address(rl); DECODE_PRINTF(","); destval = fetch_data_word(destoffset); imm = fetch_word_imm(); DECODE_PRINTF2("%x\n", imm); TRACE_AND_STEP(); destval = (*opc81_word_operation[rh]) (destval, imm); if (rh != 7) store_data_word(destoffset, destval); } break; case 3: /* register to register */ if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg; u32 destval,imm; destreg = DECODE_RM_LONG_REGISTER(rl); DECODE_PRINTF(","); imm = fetch_long_imm(); DECODE_PRINTF2("%x\n", imm); TRACE_AND_STEP(); destval = (*opc81_long_operation[rh]) (*destreg, imm); if (rh != 7) *destreg = destval; } else { u16 *destreg; u16 destval,imm; destreg = DECODE_RM_WORD_REGISTER(rl); DECODE_PRINTF(","); imm = fetch_word_imm(); DECODE_PRINTF2("%x\n", imm); TRACE_AND_STEP(); destval = (*opc81_word_operation[rh]) (*destreg, imm); if (rh != 7) *destreg = destval; } break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } static u8 (*opc82_byte_operation[])(u8 s, u8 d) = { add_byte, /*00 */ or_byte, /*01 */ /*YYY UNUSED ???? */ adc_byte, /*02 */ sbb_byte, /*03 */ and_byte, /*04 */ /*YYY UNUSED ???? */ sub_byte, /*05 */ xor_byte, /*06 */ /*YYY UNUSED ???? */ cmp_byte, /*07 */ }; /**************************************************************************** REMARKS: Handles opcode 0x82 ****************************************************************************/ void x86emuOp_opc82_byte_RM_IMM(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; u8 *destreg; uint destoffset; u8 imm; u8 destval; /* * Weirdo special case instruction format. Part of the opcode * held below in "RH". Doubly nested case would result, except * that the decoded instruction Similar to opcode 81, except that * the immediate byte is sign extended to a word length. */ START_OF_INSTR(); FETCH_DECODE_MODRM(mod, rh, rl); #ifdef DEBUG if (DEBUG_DECODE()) { /* XXX DECODE_PRINTF may be changed to something more general, so that it is important to leave the strings in the same format, even though the result is that the above test is done twice. */ switch (rh) { case 0: DECODE_PRINTF("ADD\t"); break; case 1: DECODE_PRINTF("OR\t"); break; case 2: DECODE_PRINTF("ADC\t"); break; case 3: DECODE_PRINTF("SBB\t"); break; case 4: DECODE_PRINTF("AND\t"); break; case 5: DECODE_PRINTF("SUB\t"); break; case 6: DECODE_PRINTF("XOR\t"); break; case 7: DECODE_PRINTF("CMP\t"); break; } } #endif /* know operation, decode the mod byte to find the addressing mode. */ switch (mod) { case 0: DECODE_PRINTF("BYTE PTR "); destoffset = decode_rm00_address(rl); destval = fetch_data_byte(destoffset); imm = fetch_byte_imm(); DECODE_PRINTF2(",%x\n", imm); TRACE_AND_STEP(); destval = (*opc82_byte_operation[rh]) (destval, imm); if (rh != 7) store_data_byte(destoffset, destval); break; case 1: DECODE_PRINTF("BYTE PTR "); destoffset = decode_rm01_address(rl); destval = fetch_data_byte(destoffset); imm = fetch_byte_imm(); DECODE_PRINTF2(",%x\n", imm); TRACE_AND_STEP(); destval = (*opc82_byte_operation[rh]) (destval, imm); if (rh != 7) store_data_byte(destoffset, destval); break; case 2: DECODE_PRINTF("BYTE PTR "); destoffset = decode_rm10_address(rl); destval = fetch_data_byte(destoffset); imm = fetch_byte_imm(); DECODE_PRINTF2(",%x\n", imm); TRACE_AND_STEP(); destval = (*opc82_byte_operation[rh]) (destval, imm); if (rh != 7) store_data_byte(destoffset, destval); break; case 3: /* register to register */ destreg = DECODE_RM_BYTE_REGISTER(rl); imm = fetch_byte_imm(); DECODE_PRINTF2(",%x\n", imm); TRACE_AND_STEP(); destval = (*opc82_byte_operation[rh]) (*destreg, imm); if (rh != 7) *destreg = destval; break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } static u16 (*opc83_word_operation[])(u16 s, u16 d) = { add_word, /*00 */ or_word, /*01 */ /*YYY UNUSED ???? */ adc_word, /*02 */ sbb_word, /*03 */ and_word, /*04 */ /*YYY UNUSED ???? */ sub_word, /*05 */ xor_word, /*06 */ /*YYY UNUSED ???? */ cmp_word, /*07 */ }; static u32 (*opc83_long_operation[])(u32 s, u32 d) = { add_long, /*00 */ or_long, /*01 */ /*YYY UNUSED ???? */ adc_long, /*02 */ sbb_long, /*03 */ and_long, /*04 */ /*YYY UNUSED ???? */ sub_long, /*05 */ xor_long, /*06 */ /*YYY UNUSED ???? */ cmp_long, /*07 */ }; /**************************************************************************** REMARKS: Handles opcode 0x83 ****************************************************************************/ void x86emuOp_opc83_word_RM_IMM(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; uint destoffset; /* * Weirdo special case instruction format. Part of the opcode * held below in "RH". Doubly nested case would result, except * that the decoded instruction Similar to opcode 81, except that * the immediate byte is sign extended to a word length. */ START_OF_INSTR(); FETCH_DECODE_MODRM(mod, rh, rl); #ifdef DEBUG if (DEBUG_DECODE()) { /* XXX DECODE_PRINTF may be changed to something more general, so that it is important to leave the strings in the same format, even though the result is that the above test is done twice. */ switch (rh) { case 0: DECODE_PRINTF("ADD\t"); break; case 1: DECODE_PRINTF("OR\t"); break; case 2: DECODE_PRINTF("ADC\t"); break; case 3: DECODE_PRINTF("SBB\t"); break; case 4: DECODE_PRINTF("AND\t"); break; case 5: DECODE_PRINTF("SUB\t"); break; case 6: DECODE_PRINTF("XOR\t"); break; case 7: DECODE_PRINTF("CMP\t"); break; } } #endif /* know operation, decode the mod byte to find the addressing mode. */ switch (mod) { case 0: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval,imm; DECODE_PRINTF("DWORD PTR "); destoffset = decode_rm00_address(rl); destval = fetch_data_long(destoffset); imm = (s8) fetch_byte_imm(); DECODE_PRINTF2(",%x\n", imm); TRACE_AND_STEP(); destval = (*opc83_long_operation[rh]) (destval, imm); if (rh != 7) store_data_long(destoffset, destval); } else { u16 destval,imm; DECODE_PRINTF("WORD PTR "); destoffset = decode_rm00_address(rl); destval = fetch_data_word(destoffset); imm = (s8) fetch_byte_imm(); DECODE_PRINTF2(",%x\n", imm); TRACE_AND_STEP(); destval = (*opc83_word_operation[rh]) (destval, imm); if (rh != 7) store_data_word(destoffset, destval); } break; case 1: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval,imm; DECODE_PRINTF("DWORD PTR "); destoffset = decode_rm01_address(rl); destval = fetch_data_long(destoffset); imm = (s8) fetch_byte_imm(); DECODE_PRINTF2(",%x\n", imm); TRACE_AND_STEP(); destval = (*opc83_long_operation[rh]) (destval, imm); if (rh != 7) store_data_long(destoffset, destval); } else { u16 destval,imm; DECODE_PRINTF("WORD PTR "); destoffset = decode_rm01_address(rl); destval = fetch_data_word(destoffset); imm = (s8) fetch_byte_imm(); DECODE_PRINTF2(",%x\n", imm); TRACE_AND_STEP(); destval = (*opc83_word_operation[rh]) (destval, imm); if (rh != 7) store_data_word(destoffset, destval); } break; case 2: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval,imm; DECODE_PRINTF("DWORD PTR "); destoffset = decode_rm10_address(rl); destval = fetch_data_long(destoffset); imm = (s8) fetch_byte_imm(); DECODE_PRINTF2(",%x\n", imm); TRACE_AND_STEP(); destval = (*opc83_long_operation[rh]) (destval, imm); if (rh != 7) store_data_long(destoffset, destval); } else { u16 destval,imm; DECODE_PRINTF("WORD PTR "); destoffset = decode_rm10_address(rl); destval = fetch_data_word(destoffset); imm = (s8) fetch_byte_imm(); DECODE_PRINTF2(",%x\n", imm); TRACE_AND_STEP(); destval = (*opc83_word_operation[rh]) (destval, imm); if (rh != 7) store_data_word(destoffset, destval); } break; case 3: /* register to register */ if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg; u32 destval,imm; destreg = DECODE_RM_LONG_REGISTER(rl); imm = (s8) fetch_byte_imm(); DECODE_PRINTF2(",%x\n", imm); TRACE_AND_STEP(); destval = (*opc83_long_operation[rh]) (*destreg, imm); if (rh != 7) *destreg = destval; } else { u16 *destreg; u16 destval,imm; destreg = DECODE_RM_WORD_REGISTER(rl); imm = (s8) fetch_byte_imm(); DECODE_PRINTF2(",%x\n", imm); TRACE_AND_STEP(); destval = (*opc83_word_operation[rh]) (*destreg, imm); if (rh != 7) *destreg = destval; } break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x84 ****************************************************************************/ void x86emuOp_test_byte_RM_R(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; u8 *destreg, *srcreg; uint destoffset; u8 destval; START_OF_INSTR(); DECODE_PRINTF("TEST\t"); FETCH_DECODE_MODRM(mod, rh, rl); switch (mod) { case 0: destoffset = decode_rm00_address(rl); DECODE_PRINTF(","); destval = fetch_data_byte(destoffset); srcreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); test_byte(destval, *srcreg); break; case 1: destoffset = decode_rm01_address(rl); DECODE_PRINTF(","); destval = fetch_data_byte(destoffset); srcreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); test_byte(destval, *srcreg); break; case 2: destoffset = decode_rm10_address(rl); DECODE_PRINTF(","); destval = fetch_data_byte(destoffset); srcreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); test_byte(destval, *srcreg); break; case 3: /* register to register */ destreg = DECODE_RM_BYTE_REGISTER(rl); DECODE_PRINTF(","); srcreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); test_byte(*destreg, *srcreg); break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x85 ****************************************************************************/ void x86emuOp_test_word_RM_R(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; uint destoffset; START_OF_INSTR(); DECODE_PRINTF("TEST\t"); FETCH_DECODE_MODRM(mod, rh, rl); switch (mod) { case 0: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; u32 *srcreg; destoffset = decode_rm00_address(rl); DECODE_PRINTF(","); destval = fetch_data_long(destoffset); srcreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); test_long(destval, *srcreg); } else { u16 destval; u16 *srcreg; destoffset = decode_rm00_address(rl); DECODE_PRINTF(","); destval = fetch_data_word(destoffset); srcreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); test_word(destval, *srcreg); } break; case 1: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; u32 *srcreg; destoffset = decode_rm01_address(rl); DECODE_PRINTF(","); destval = fetch_data_long(destoffset); srcreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); test_long(destval, *srcreg); } else { u16 destval; u16 *srcreg; destoffset = decode_rm01_address(rl); DECODE_PRINTF(","); destval = fetch_data_word(destoffset); srcreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); test_word(destval, *srcreg); } break; case 2: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; u32 *srcreg; destoffset = decode_rm10_address(rl); DECODE_PRINTF(","); destval = fetch_data_long(destoffset); srcreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); test_long(destval, *srcreg); } else { u16 destval; u16 *srcreg; destoffset = decode_rm10_address(rl); DECODE_PRINTF(","); destval = fetch_data_word(destoffset); srcreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); test_word(destval, *srcreg); } break; case 3: /* register to register */ if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg,*srcreg; destreg = DECODE_RM_LONG_REGISTER(rl); DECODE_PRINTF(","); srcreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); test_long(*destreg, *srcreg); } else { u16 *destreg,*srcreg; destreg = DECODE_RM_WORD_REGISTER(rl); DECODE_PRINTF(","); srcreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); test_word(*destreg, *srcreg); } break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x86 ****************************************************************************/ void x86emuOp_xchg_byte_RM_R(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; u8 *destreg, *srcreg; uint destoffset; u8 destval; u8 tmp; START_OF_INSTR(); DECODE_PRINTF("XCHG\t"); FETCH_DECODE_MODRM(mod, rh, rl); switch (mod) { case 0: destoffset = decode_rm00_address(rl); DECODE_PRINTF(","); destval = fetch_data_byte(destoffset); srcreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); tmp = *srcreg; *srcreg = destval; destval = tmp; store_data_byte(destoffset, destval); break; case 1: destoffset = decode_rm01_address(rl); DECODE_PRINTF(","); destval = fetch_data_byte(destoffset); srcreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); tmp = *srcreg; *srcreg = destval; destval = tmp; store_data_byte(destoffset, destval); break; case 2: destoffset = decode_rm10_address(rl); DECODE_PRINTF(","); destval = fetch_data_byte(destoffset); srcreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); tmp = *srcreg; *srcreg = destval; destval = tmp; store_data_byte(destoffset, destval); break; case 3: /* register to register */ destreg = DECODE_RM_BYTE_REGISTER(rl); DECODE_PRINTF(","); srcreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); tmp = *srcreg; *srcreg = *destreg; *destreg = tmp; break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x87 ****************************************************************************/ void x86emuOp_xchg_word_RM_R(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; uint destoffset; START_OF_INSTR(); DECODE_PRINTF("XCHG\t"); FETCH_DECODE_MODRM(mod, rh, rl); switch (mod) { case 0: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *srcreg; u32 destval,tmp; destoffset = decode_rm00_address(rl); DECODE_PRINTF(","); destval = fetch_data_long(destoffset); srcreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); tmp = *srcreg; *srcreg = destval; destval = tmp; store_data_long(destoffset, destval); } else { u16 *srcreg; u16 destval,tmp; destoffset = decode_rm00_address(rl); DECODE_PRINTF(","); destval = fetch_data_word(destoffset); srcreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); tmp = *srcreg; *srcreg = destval; destval = tmp; store_data_word(destoffset, destval); } break; case 1: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *srcreg; u32 destval,tmp; destoffset = decode_rm01_address(rl); DECODE_PRINTF(","); destval = fetch_data_long(destoffset); srcreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); tmp = *srcreg; *srcreg = destval; destval = tmp; store_data_long(destoffset, destval); } else { u16 *srcreg; u16 destval,tmp; destoffset = decode_rm01_address(rl); DECODE_PRINTF(","); destval = fetch_data_word(destoffset); srcreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); tmp = *srcreg; *srcreg = destval; destval = tmp; store_data_word(destoffset, destval); } break; case 2: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *srcreg; u32 destval,tmp; destoffset = decode_rm10_address(rl); DECODE_PRINTF(","); destval = fetch_data_long(destoffset); srcreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); tmp = *srcreg; *srcreg = destval; destval = tmp; store_data_long(destoffset, destval); } else { u16 *srcreg; u16 destval,tmp; destoffset = decode_rm10_address(rl); DECODE_PRINTF(","); destval = fetch_data_word(destoffset); srcreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); tmp = *srcreg; *srcreg = destval; destval = tmp; store_data_word(destoffset, destval); } break; case 3: /* register to register */ if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg,*srcreg; u32 tmp; destreg = DECODE_RM_LONG_REGISTER(rl); DECODE_PRINTF(","); srcreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); tmp = *srcreg; *srcreg = *destreg; *destreg = tmp; } else { u16 *destreg,*srcreg; u16 tmp; destreg = DECODE_RM_WORD_REGISTER(rl); DECODE_PRINTF(","); srcreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); tmp = *srcreg; *srcreg = *destreg; *destreg = tmp; } break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x88 ****************************************************************************/ void x86emuOp_mov_byte_RM_R(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; u8 *destreg, *srcreg; uint destoffset; START_OF_INSTR(); DECODE_PRINTF("MOV\t"); FETCH_DECODE_MODRM(mod, rh, rl); switch (mod) { case 0: destoffset = decode_rm00_address(rl); DECODE_PRINTF(","); srcreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); store_data_byte(destoffset, *srcreg); break; case 1: destoffset = decode_rm01_address(rl); DECODE_PRINTF(","); srcreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); store_data_byte(destoffset, *srcreg); break; case 2: destoffset = decode_rm10_address(rl); DECODE_PRINTF(","); srcreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); store_data_byte(destoffset, *srcreg); break; case 3: /* register to register */ destreg = DECODE_RM_BYTE_REGISTER(rl); DECODE_PRINTF(","); srcreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = *srcreg; break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x89 ****************************************************************************/ void x86emuOp_mov_word_RM_R(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; uint destoffset; START_OF_INSTR(); DECODE_PRINTF("MOV\t"); FETCH_DECODE_MODRM(mod, rh, rl); switch (mod) { case 0: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *srcreg; destoffset = decode_rm00_address(rl); DECODE_PRINTF(","); srcreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); store_data_long(destoffset, *srcreg); } else { u16 *srcreg; destoffset = decode_rm00_address(rl); DECODE_PRINTF(","); srcreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); store_data_word(destoffset, *srcreg); } break; case 1: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *srcreg; destoffset = decode_rm01_address(rl); DECODE_PRINTF(","); srcreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); store_data_long(destoffset, *srcreg); } else { u16 *srcreg; destoffset = decode_rm01_address(rl); DECODE_PRINTF(","); srcreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); store_data_word(destoffset, *srcreg); } break; case 2: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *srcreg; destoffset = decode_rm10_address(rl); DECODE_PRINTF(","); srcreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); store_data_long(destoffset, *srcreg); } else { u16 *srcreg; destoffset = decode_rm10_address(rl); DECODE_PRINTF(","); srcreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); store_data_word(destoffset, *srcreg); } break; case 3: /* register to register */ if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg,*srcreg; destreg = DECODE_RM_LONG_REGISTER(rl); DECODE_PRINTF(","); srcreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = *srcreg; } else { u16 *destreg,*srcreg; destreg = DECODE_RM_WORD_REGISTER(rl); DECODE_PRINTF(","); srcreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = *srcreg; } break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x8a ****************************************************************************/ void x86emuOp_mov_byte_R_RM(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; u8 *destreg, *srcreg; uint srcoffset; u8 srcval; START_OF_INSTR(); DECODE_PRINTF("MOV\t"); FETCH_DECODE_MODRM(mod, rh, rl); switch (mod) { case 0: destreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm00_address(rl); srcval = fetch_data_byte(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = srcval; break; case 1: destreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm01_address(rl); srcval = fetch_data_byte(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = srcval; break; case 2: destreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm10_address(rl); srcval = fetch_data_byte(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = srcval; break; case 3: /* register to register */ destreg = DECODE_RM_BYTE_REGISTER(rh); DECODE_PRINTF(","); srcreg = DECODE_RM_BYTE_REGISTER(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = *srcreg; break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x8b ****************************************************************************/ void x86emuOp_mov_word_R_RM(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; uint srcoffset; START_OF_INSTR(); DECODE_PRINTF("MOV\t"); FETCH_DECODE_MODRM(mod, rh, rl); switch (mod) { case 0: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg; u32 srcval; destreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm00_address(rl); srcval = fetch_data_long(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = srcval; } else { u16 *destreg; u16 srcval; destreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm00_address(rl); srcval = fetch_data_word(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = srcval; } break; case 1: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg; u32 srcval; destreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm01_address(rl); srcval = fetch_data_long(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = srcval; } else { u16 *destreg; u16 srcval; destreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm01_address(rl); srcval = fetch_data_word(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = srcval; } break; case 2: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg; u32 srcval; destreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm10_address(rl); srcval = fetch_data_long(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = srcval; } else { u16 *destreg; u16 srcval; destreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm10_address(rl); srcval = fetch_data_word(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = srcval; } break; case 3: /* register to register */ if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg, *srcreg; destreg = DECODE_RM_LONG_REGISTER(rh); DECODE_PRINTF(","); srcreg = DECODE_RM_LONG_REGISTER(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = *srcreg; } else { u16 *destreg, *srcreg; destreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF(","); srcreg = DECODE_RM_WORD_REGISTER(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = *srcreg; } break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x8c ****************************************************************************/ void x86emuOp_mov_word_RM_SR(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; u16 *destreg, *srcreg; uint destoffset; u16 destval; START_OF_INSTR(); DECODE_PRINTF("MOV\t"); FETCH_DECODE_MODRM(mod, rh, rl); switch (mod) { case 0: destoffset = decode_rm00_address(rl); DECODE_PRINTF(","); srcreg = decode_rm_seg_register(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = *srcreg; store_data_word(destoffset, destval); break; case 1: destoffset = decode_rm01_address(rl); DECODE_PRINTF(","); srcreg = decode_rm_seg_register(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = *srcreg; store_data_word(destoffset, destval); break; case 2: destoffset = decode_rm10_address(rl); DECODE_PRINTF(","); srcreg = decode_rm_seg_register(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = *srcreg; store_data_word(destoffset, destval); break; case 3: /* register to register */ destreg = DECODE_RM_WORD_REGISTER(rl); DECODE_PRINTF(","); srcreg = decode_rm_seg_register(rh); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = *srcreg; break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x8d ****************************************************************************/ void x86emuOp_lea_word_R_M(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; u16 *srcreg; uint destoffset; /* * TODO: Need to handle address size prefix! * * lea eax,[eax+ebx*2] ?? */ START_OF_INSTR(); DECODE_PRINTF("LEA\t"); FETCH_DECODE_MODRM(mod, rh, rl); switch (mod) { case 0: srcreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF(","); destoffset = decode_rm00_address(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *srcreg = (u16)destoffset; break; case 1: srcreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF(","); destoffset = decode_rm01_address(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *srcreg = (u16)destoffset; break; case 2: srcreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF(","); destoffset = decode_rm10_address(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *srcreg = (u16)destoffset; break; case 3: /* register to register */ /* undefined. Do nothing. */ break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x8e ****************************************************************************/ void x86emuOp_mov_word_SR_RM(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; u16 *destreg, *srcreg; uint srcoffset; u16 srcval; START_OF_INSTR(); DECODE_PRINTF("MOV\t"); FETCH_DECODE_MODRM(mod, rh, rl); switch (mod) { case 0: destreg = decode_rm_seg_register(rh); DECODE_PRINTF(","); srcoffset = decode_rm00_address(rl); srcval = fetch_data_word(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = srcval; break; case 1: destreg = decode_rm_seg_register(rh); DECODE_PRINTF(","); srcoffset = decode_rm01_address(rl); srcval = fetch_data_word(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = srcval; break; case 2: destreg = decode_rm_seg_register(rh); DECODE_PRINTF(","); srcoffset = decode_rm10_address(rl); srcval = fetch_data_word(srcoffset); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = srcval; break; case 3: /* register to register */ destreg = decode_rm_seg_register(rh); DECODE_PRINTF(","); srcreg = DECODE_RM_WORD_REGISTER(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = *srcreg; break; } /* * Clean up, and reset all the R_xSP pointers to the correct * locations. This is about 3x too much overhead (doing all the * segreg ptrs when only one is needed, but this instruction * *cannot* be that common, and this isn't too much work anyway. */ DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x8f ****************************************************************************/ void x86emuOp_pop_RM(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; uint destoffset; START_OF_INSTR(); DECODE_PRINTF("POP\t"); FETCH_DECODE_MODRM(mod, rh, rl); if (rh != 0) { DECODE_PRINTF("ILLEGAL DECODE OF OPCODE 8F\n"); HALT_SYS(); } switch (mod) { case 0: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; destoffset = decode_rm00_address(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = pop_long(); store_data_long(destoffset, destval); } else { u16 destval; destoffset = decode_rm00_address(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = pop_word(); store_data_word(destoffset, destval); } break; case 1: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; destoffset = decode_rm01_address(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = pop_long(); store_data_long(destoffset, destval); } else { u16 destval; destoffset = decode_rm01_address(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = pop_word(); store_data_word(destoffset, destval); } break; case 2: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; destoffset = decode_rm10_address(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = pop_long(); store_data_long(destoffset, destval); } else { u16 destval; destoffset = decode_rm10_address(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); destval = pop_word(); store_data_word(destoffset, destval); } break; case 3: /* register to register */ if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg; destreg = DECODE_RM_LONG_REGISTER(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = pop_long(); } else { u16 *destreg; destreg = DECODE_RM_WORD_REGISTER(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = pop_word(); } break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x90 ****************************************************************************/ void x86emuOp_nop(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); DECODE_PRINTF("NOP\n"); TRACE_AND_STEP(); DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x91 ****************************************************************************/ void x86emuOp_xchg_word_AX_CX(u8 X86EMU_UNUSED(op1)) { u32 tmp; START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("XCHG\tEAX,ECX\n"); } else { DECODE_PRINTF("XCHG\tAX,CX\n"); } TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { tmp = M.x86.R_EAX; M.x86.R_EAX = M.x86.R_ECX; M.x86.R_ECX = tmp; } else { tmp = M.x86.R_AX; M.x86.R_AX = M.x86.R_CX; M.x86.R_CX = (u16)tmp; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x92 ****************************************************************************/ void x86emuOp_xchg_word_AX_DX(u8 X86EMU_UNUSED(op1)) { u32 tmp; START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("XCHG\tEAX,EDX\n"); } else { DECODE_PRINTF("XCHG\tAX,DX\n"); } TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { tmp = M.x86.R_EAX; M.x86.R_EAX = M.x86.R_EDX; M.x86.R_EDX = tmp; } else { tmp = M.x86.R_AX; M.x86.R_AX = M.x86.R_DX; M.x86.R_DX = (u16)tmp; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x93 ****************************************************************************/ void x86emuOp_xchg_word_AX_BX(u8 X86EMU_UNUSED(op1)) { u32 tmp; START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("XCHG\tEAX,EBX\n"); } else { DECODE_PRINTF("XCHG\tAX,BX\n"); } TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { tmp = M.x86.R_EAX; M.x86.R_EAX = M.x86.R_EBX; M.x86.R_EBX = tmp; } else { tmp = M.x86.R_AX; M.x86.R_AX = M.x86.R_BX; M.x86.R_BX = (u16)tmp; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x94 ****************************************************************************/ void x86emuOp_xchg_word_AX_SP(u8 X86EMU_UNUSED(op1)) { u32 tmp; START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("XCHG\tEAX,ESP\n"); } else { DECODE_PRINTF("XCHG\tAX,SP\n"); } TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { tmp = M.x86.R_EAX; M.x86.R_EAX = M.x86.R_ESP; M.x86.R_ESP = tmp; } else { tmp = M.x86.R_AX; M.x86.R_AX = M.x86.R_SP; M.x86.R_SP = (u16)tmp; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x95 ****************************************************************************/ void x86emuOp_xchg_word_AX_BP(u8 X86EMU_UNUSED(op1)) { u32 tmp; START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("XCHG\tEAX,EBP\n"); } else { DECODE_PRINTF("XCHG\tAX,BP\n"); } TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { tmp = M.x86.R_EAX; M.x86.R_EAX = M.x86.R_EBP; M.x86.R_EBP = tmp; } else { tmp = M.x86.R_AX; M.x86.R_AX = M.x86.R_BP; M.x86.R_BP = (u16)tmp; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x96 ****************************************************************************/ void x86emuOp_xchg_word_AX_SI(u8 X86EMU_UNUSED(op1)) { u32 tmp; START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("XCHG\tEAX,ESI\n"); } else { DECODE_PRINTF("XCHG\tAX,SI\n"); } TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { tmp = M.x86.R_EAX; M.x86.R_EAX = M.x86.R_ESI; M.x86.R_ESI = tmp; } else { tmp = M.x86.R_AX; M.x86.R_AX = M.x86.R_SI; M.x86.R_SI = (u16)tmp; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x97 ****************************************************************************/ void x86emuOp_xchg_word_AX_DI(u8 X86EMU_UNUSED(op1)) { u32 tmp; START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("XCHG\tEAX,EDI\n"); } else { DECODE_PRINTF("XCHG\tAX,DI\n"); } TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { tmp = M.x86.R_EAX; M.x86.R_EAX = M.x86.R_EDI; M.x86.R_EDI = tmp; } else { tmp = M.x86.R_AX; M.x86.R_AX = M.x86.R_DI; M.x86.R_DI = (u16)tmp; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x98 ****************************************************************************/ void x86emuOp_cbw(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("CWDE\n"); } else { DECODE_PRINTF("CBW\n"); } TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { if (M.x86.R_AX & 0x8000) { M.x86.R_EAX |= 0xffff0000; } else { M.x86.R_EAX &= 0x0000ffff; } } else { if (M.x86.R_AL & 0x80) { M.x86.R_AH = 0xff; } else { M.x86.R_AH = 0x0; } } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x99 ****************************************************************************/ void x86emuOp_cwd(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("CDQ\n"); } else { DECODE_PRINTF("CWD\n"); } DECODE_PRINTF("CWD\n"); TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { if (M.x86.R_EAX & 0x80000000) { M.x86.R_EDX = 0xffffffff; } else { M.x86.R_EDX = 0x0; } } else { if (M.x86.R_AX & 0x8000) { M.x86.R_DX = 0xffff; } else { M.x86.R_DX = 0x0; } } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x9a ****************************************************************************/ void x86emuOp_call_far_IMM(u8 X86EMU_UNUSED(op1)) { u16 farseg, faroff; START_OF_INSTR(); DECODE_PRINTF("CALL\t"); faroff = fetch_word_imm(); farseg = fetch_word_imm(); DECODE_PRINTF2("%04x:", farseg); DECODE_PRINTF2("%04x\n", faroff); CALL_TRACE(M.x86.saved_cs, M.x86.saved_ip, farseg, faroff, "FAR "); /* XXX * * Hooked interrupt vectors calling into our "BIOS" will cause * problems unless all intersegment stuff is checked for BIOS * access. Check needed here. For moment, let it alone. */ TRACE_AND_STEP(); push_word(M.x86.R_CS); M.x86.R_CS = farseg; push_word(M.x86.R_IP); M.x86.R_IP = faroff; DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x9b ****************************************************************************/ void x86emuOp_wait(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); DECODE_PRINTF("WAIT"); TRACE_AND_STEP(); /* NADA. */ DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x9c ****************************************************************************/ void x86emuOp_pushf_word(u8 X86EMU_UNUSED(op1)) { u32 flags; START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("PUSHFD\n"); } else { DECODE_PRINTF("PUSHF\n"); } TRACE_AND_STEP(); /* clear out *all* bits not representing flags, and turn on real bits */ flags = (M.x86.R_EFLG & F_MSK) | F_ALWAYS_ON; if (M.x86.mode & SYSMODE_PREFIX_DATA) { push_long(flags); } else { push_word((u16)flags); } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x9d ****************************************************************************/ void x86emuOp_popf_word(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("POPFD\n"); } else { DECODE_PRINTF("POPF\n"); } TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { M.x86.R_EFLG = pop_long(); } else { M.x86.R_FLG = pop_word(); } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x9e ****************************************************************************/ void x86emuOp_sahf(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); DECODE_PRINTF("SAHF\n"); TRACE_AND_STEP(); /* clear the lower bits of the flag register */ M.x86.R_FLG &= 0xffffff00; /* or in the AH register into the flags register */ M.x86.R_FLG |= M.x86.R_AH; DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0x9f ****************************************************************************/ void x86emuOp_lahf(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); DECODE_PRINTF("LAHF\n"); TRACE_AND_STEP(); M.x86.R_AH = (u8)(M.x86.R_FLG & 0xff); /*undocumented TC++ behavior??? Nope. It's documented, but you have too look real hard to notice it. */ M.x86.R_AH |= 0x2; DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xa0 ****************************************************************************/ void x86emuOp_mov_AL_M_IMM(u8 X86EMU_UNUSED(op1)) { u16 offset; START_OF_INSTR(); DECODE_PRINTF("MOV\tAL,"); offset = fetch_word_imm(); DECODE_PRINTF2("[%04x]\n", offset); TRACE_AND_STEP(); M.x86.R_AL = fetch_data_byte(offset); DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xa1 ****************************************************************************/ void x86emuOp_mov_AX_M_IMM(u8 X86EMU_UNUSED(op1)) { u16 offset; START_OF_INSTR(); offset = fetch_word_imm(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF2("MOV\tEAX,[%04x]\n", offset); } else { DECODE_PRINTF2("MOV\tAX,[%04x]\n", offset); } TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { M.x86.R_EAX = fetch_data_long(offset); } else { M.x86.R_AX = fetch_data_word(offset); } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xa2 ****************************************************************************/ void x86emuOp_mov_M_AL_IMM(u8 X86EMU_UNUSED(op1)) { u16 offset; START_OF_INSTR(); DECODE_PRINTF("MOV\t"); offset = fetch_word_imm(); DECODE_PRINTF2("[%04x],AL\n", offset); TRACE_AND_STEP(); store_data_byte(offset, M.x86.R_AL); DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xa3 ****************************************************************************/ void x86emuOp_mov_M_AX_IMM(u8 X86EMU_UNUSED(op1)) { u16 offset; START_OF_INSTR(); offset = fetch_word_imm(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF2("MOV\t[%04x],EAX\n", offset); } else { DECODE_PRINTF2("MOV\t[%04x],AX\n", offset); } TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { store_data_long(offset, M.x86.R_EAX); } else { store_data_word(offset, M.x86.R_AX); } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xa4 ****************************************************************************/ void x86emuOp_movs_byte(u8 X86EMU_UNUSED(op1)) { u8 val; u32 count; int inc; START_OF_INSTR(); DECODE_PRINTF("MOVS\tBYTE\n"); if (ACCESS_FLAG(F_DF)) /* down */ inc = -1; else inc = 1; TRACE_AND_STEP(); count = 1; if (M.x86.mode & (SYSMODE_PREFIX_REPE | SYSMODE_PREFIX_REPNE)) { /* dont care whether REPE or REPNE */ /* move them until CX is ZERO. */ count = M.x86.R_CX; M.x86.R_CX = 0; M.x86.mode &= ~(SYSMODE_PREFIX_REPE | SYSMODE_PREFIX_REPNE); } while (count--) { val = fetch_data_byte(M.x86.R_SI); store_data_byte_abs(M.x86.R_ES, M.x86.R_DI, val); M.x86.R_SI += inc; M.x86.R_DI += inc; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xa5 ****************************************************************************/ void x86emuOp_movs_word(u8 X86EMU_UNUSED(op1)) { u32 val; int inc; u32 count; START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("MOVS\tDWORD\n"); if (ACCESS_FLAG(F_DF)) /* down */ inc = -4; else inc = 4; } else { DECODE_PRINTF("MOVS\tWORD\n"); if (ACCESS_FLAG(F_DF)) /* down */ inc = -2; else inc = 2; } TRACE_AND_STEP(); count = 1; if (M.x86.mode & (SYSMODE_PREFIX_REPE | SYSMODE_PREFIX_REPNE)) { /* dont care whether REPE or REPNE */ /* move them until CX is ZERO. */ count = M.x86.R_CX; M.x86.R_CX = 0; M.x86.mode &= ~(SYSMODE_PREFIX_REPE | SYSMODE_PREFIX_REPNE); } while (count--) { if (M.x86.mode & SYSMODE_PREFIX_DATA) { val = fetch_data_long(M.x86.R_SI); store_data_long_abs(M.x86.R_ES, M.x86.R_DI, val); } else { val = fetch_data_word(M.x86.R_SI); store_data_word_abs(M.x86.R_ES, M.x86.R_DI, (u16)val); } M.x86.R_SI += inc; M.x86.R_DI += inc; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xa6 ****************************************************************************/ void x86emuOp_cmps_byte(u8 X86EMU_UNUSED(op1)) { s8 val1, val2; int inc; START_OF_INSTR(); DECODE_PRINTF("CMPS\tBYTE\n"); TRACE_AND_STEP(); if (ACCESS_FLAG(F_DF)) /* down */ inc = -1; else inc = 1; if (M.x86.mode & SYSMODE_PREFIX_REPE) { /* REPE */ /* move them until CX is ZERO. */ while (M.x86.R_CX != 0) { val1 = fetch_data_byte(M.x86.R_SI); val2 = fetch_data_byte_abs(M.x86.R_ES, M.x86.R_DI); cmp_byte(val1, val2); M.x86.R_CX -= 1; M.x86.R_SI += inc; M.x86.R_DI += inc; if (ACCESS_FLAG(F_ZF) == 0) break; } M.x86.mode &= ~SYSMODE_PREFIX_REPE; } else if (M.x86.mode & SYSMODE_PREFIX_REPNE) { /* REPNE */ /* move them until CX is ZERO. */ while (M.x86.R_CX != 0) { val1 = fetch_data_byte(M.x86.R_SI); val2 = fetch_data_byte_abs(M.x86.R_ES, M.x86.R_DI); cmp_byte(val1, val2); M.x86.R_CX -= 1; M.x86.R_SI += inc; M.x86.R_DI += inc; if (ACCESS_FLAG(F_ZF)) break; /* zero flag set means equal */ } M.x86.mode &= ~SYSMODE_PREFIX_REPNE; } else { val1 = fetch_data_byte(M.x86.R_SI); val2 = fetch_data_byte_abs(M.x86.R_ES, M.x86.R_DI); cmp_byte(val1, val2); M.x86.R_SI += inc; M.x86.R_DI += inc; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xa7 ****************************************************************************/ void x86emuOp_cmps_word(u8 X86EMU_UNUSED(op1)) { u32 val1,val2; int inc; START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("CMPS\tDWORD\n"); if (ACCESS_FLAG(F_DF)) /* down */ inc = -4; else inc = 4; } else { DECODE_PRINTF("CMPS\tWORD\n"); if (ACCESS_FLAG(F_DF)) /* down */ inc = -2; else inc = 2; } TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_REPE) { /* REPE */ /* move them until CX is ZERO. */ while (M.x86.R_CX != 0) { if (M.x86.mode & SYSMODE_PREFIX_DATA) { val1 = fetch_data_long(M.x86.R_SI); val2 = fetch_data_long_abs(M.x86.R_ES, M.x86.R_DI); cmp_long(val1, val2); } else { val1 = fetch_data_word(M.x86.R_SI); val2 = fetch_data_word_abs(M.x86.R_ES, M.x86.R_DI); cmp_word((u16)val1, (u16)val2); } M.x86.R_CX -= 1; M.x86.R_SI += inc; M.x86.R_DI += inc; if (ACCESS_FLAG(F_ZF) == 0) break; } M.x86.mode &= ~SYSMODE_PREFIX_REPE; } else if (M.x86.mode & SYSMODE_PREFIX_REPNE) { /* REPNE */ /* move them until CX is ZERO. */ while (M.x86.R_CX != 0) { if (M.x86.mode & SYSMODE_PREFIX_DATA) { val1 = fetch_data_long(M.x86.R_SI); val2 = fetch_data_long_abs(M.x86.R_ES, M.x86.R_DI); cmp_long(val1, val2); } else { val1 = fetch_data_word(M.x86.R_SI); val2 = fetch_data_word_abs(M.x86.R_ES, M.x86.R_DI); cmp_word((u16)val1, (u16)val2); } M.x86.R_CX -= 1; M.x86.R_SI += inc; M.x86.R_DI += inc; if (ACCESS_FLAG(F_ZF)) break; /* zero flag set means equal */ } M.x86.mode &= ~SYSMODE_PREFIX_REPNE; } else { if (M.x86.mode & SYSMODE_PREFIX_DATA) { val1 = fetch_data_long(M.x86.R_SI); val2 = fetch_data_long_abs(M.x86.R_ES, M.x86.R_DI); cmp_long(val1, val2); } else { val1 = fetch_data_word(M.x86.R_SI); val2 = fetch_data_word_abs(M.x86.R_ES, M.x86.R_DI); cmp_word((u16)val1, (u16)val2); } M.x86.R_SI += inc; M.x86.R_DI += inc; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xa8 ****************************************************************************/ void x86emuOp_test_AL_IMM(u8 X86EMU_UNUSED(op1)) { int imm; START_OF_INSTR(); DECODE_PRINTF("TEST\tAL,"); imm = fetch_byte_imm(); DECODE_PRINTF2("%04x\n", imm); TRACE_AND_STEP(); test_byte(M.x86.R_AL, (u8)imm); DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xa9 ****************************************************************************/ void x86emuOp_test_AX_IMM(u8 X86EMU_UNUSED(op1)) { u32 srcval; START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("TEST\tEAX,"); srcval = fetch_long_imm(); } else { DECODE_PRINTF("TEST\tAX,"); srcval = fetch_word_imm(); } DECODE_PRINTF2("%x\n", srcval); TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { test_long(M.x86.R_EAX, srcval); } else { test_word(M.x86.R_AX, (u16)srcval); } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xaa ****************************************************************************/ void x86emuOp_stos_byte(u8 X86EMU_UNUSED(op1)) { int inc; START_OF_INSTR(); DECODE_PRINTF("STOS\tBYTE\n"); if (ACCESS_FLAG(F_DF)) /* down */ inc = -1; else inc = 1; TRACE_AND_STEP(); if (M.x86.mode & (SYSMODE_PREFIX_REPE | SYSMODE_PREFIX_REPNE)) { /* dont care whether REPE or REPNE */ /* move them until CX is ZERO. */ while (M.x86.R_CX != 0) { store_data_byte_abs(M.x86.R_ES, M.x86.R_DI, M.x86.R_AL); M.x86.R_CX -= 1; M.x86.R_DI += inc; } M.x86.mode &= ~(SYSMODE_PREFIX_REPE | SYSMODE_PREFIX_REPNE); } else { store_data_byte_abs(M.x86.R_ES, M.x86.R_DI, M.x86.R_AL); M.x86.R_DI += inc; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xab ****************************************************************************/ void x86emuOp_stos_word(u8 X86EMU_UNUSED(op1)) { int inc; u32 count; START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("STOS\tDWORD\n"); if (ACCESS_FLAG(F_DF)) /* down */ inc = -4; else inc = 4; } else { DECODE_PRINTF("STOS\tWORD\n"); if (ACCESS_FLAG(F_DF)) /* down */ inc = -2; else inc = 2; } TRACE_AND_STEP(); count = 1; if (M.x86.mode & (SYSMODE_PREFIX_REPE | SYSMODE_PREFIX_REPNE)) { /* dont care whether REPE or REPNE */ /* move them until CX is ZERO. */ count = M.x86.R_CX; M.x86.R_CX = 0; M.x86.mode &= ~(SYSMODE_PREFIX_REPE | SYSMODE_PREFIX_REPNE); } while (count--) { if (M.x86.mode & SYSMODE_PREFIX_DATA) { store_data_long_abs(M.x86.R_ES, M.x86.R_DI, M.x86.R_EAX); } else { store_data_word_abs(M.x86.R_ES, M.x86.R_DI, M.x86.R_AX); } M.x86.R_DI += inc; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xac ****************************************************************************/ void x86emuOp_lods_byte(u8 X86EMU_UNUSED(op1)) { int inc; START_OF_INSTR(); DECODE_PRINTF("LODS\tBYTE\n"); TRACE_AND_STEP(); if (ACCESS_FLAG(F_DF)) /* down */ inc = -1; else inc = 1; if (M.x86.mode & (SYSMODE_PREFIX_REPE | SYSMODE_PREFIX_REPNE)) { /* dont care whether REPE or REPNE */ /* move them until CX is ZERO. */ while (M.x86.R_CX != 0) { M.x86.R_AL = fetch_data_byte(M.x86.R_SI); M.x86.R_CX -= 1; M.x86.R_SI += inc; } M.x86.mode &= ~(SYSMODE_PREFIX_REPE | SYSMODE_PREFIX_REPNE); } else { M.x86.R_AL = fetch_data_byte(M.x86.R_SI); M.x86.R_SI += inc; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xad ****************************************************************************/ void x86emuOp_lods_word(u8 X86EMU_UNUSED(op1)) { int inc; u32 count; START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("LODS\tDWORD\n"); if (ACCESS_FLAG(F_DF)) /* down */ inc = -4; else inc = 4; } else { DECODE_PRINTF("LODS\tWORD\n"); if (ACCESS_FLAG(F_DF)) /* down */ inc = -2; else inc = 2; } TRACE_AND_STEP(); count = 1; if (M.x86.mode & (SYSMODE_PREFIX_REPE | SYSMODE_PREFIX_REPNE)) { /* dont care whether REPE or REPNE */ /* move them until CX is ZERO. */ count = M.x86.R_CX; M.x86.R_CX = 0; M.x86.mode &= ~(SYSMODE_PREFIX_REPE | SYSMODE_PREFIX_REPNE); } while (count--) { if (M.x86.mode & SYSMODE_PREFIX_DATA) { M.x86.R_EAX = fetch_data_long(M.x86.R_SI); } else { M.x86.R_AX = fetch_data_word(M.x86.R_SI); } M.x86.R_SI += inc; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xae ****************************************************************************/ void x86emuOp_scas_byte(u8 X86EMU_UNUSED(op1)) { s8 val2; int inc; START_OF_INSTR(); DECODE_PRINTF("SCAS\tBYTE\n"); TRACE_AND_STEP(); if (ACCESS_FLAG(F_DF)) /* down */ inc = -1; else inc = 1; if (M.x86.mode & SYSMODE_PREFIX_REPE) { /* REPE */ /* move them until CX is ZERO. */ while (M.x86.R_CX != 0) { val2 = fetch_data_byte_abs(M.x86.R_ES, M.x86.R_DI); cmp_byte(M.x86.R_AL, val2); M.x86.R_CX -= 1; M.x86.R_DI += inc; if (ACCESS_FLAG(F_ZF) == 0) break; } M.x86.mode &= ~SYSMODE_PREFIX_REPE; } else if (M.x86.mode & SYSMODE_PREFIX_REPNE) { /* REPNE */ /* move them until CX is ZERO. */ while (M.x86.R_CX != 0) { val2 = fetch_data_byte_abs(M.x86.R_ES, M.x86.R_DI); cmp_byte(M.x86.R_AL, val2); M.x86.R_CX -= 1; M.x86.R_DI += inc; if (ACCESS_FLAG(F_ZF)) break; /* zero flag set means equal */ } M.x86.mode &= ~SYSMODE_PREFIX_REPNE; } else { val2 = fetch_data_byte_abs(M.x86.R_ES, M.x86.R_DI); cmp_byte(M.x86.R_AL, val2); M.x86.R_DI += inc; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xaf ****************************************************************************/ void x86emuOp_scas_word(u8 X86EMU_UNUSED(op1)) { int inc; u32 val; START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("SCAS\tDWORD\n"); if (ACCESS_FLAG(F_DF)) /* down */ inc = -4; else inc = 4; } else { DECODE_PRINTF("SCAS\tWORD\n"); if (ACCESS_FLAG(F_DF)) /* down */ inc = -2; else inc = 2; } TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_REPE) { /* REPE */ /* move them until CX is ZERO. */ while (M.x86.R_CX != 0) { if (M.x86.mode & SYSMODE_PREFIX_DATA) { val = fetch_data_long_abs(M.x86.R_ES, M.x86.R_DI); cmp_long(M.x86.R_EAX, val); } else { val = fetch_data_word_abs(M.x86.R_ES, M.x86.R_DI); cmp_word(M.x86.R_AX, (u16)val); } M.x86.R_CX -= 1; M.x86.R_DI += inc; if (ACCESS_FLAG(F_ZF) == 0) break; } M.x86.mode &= ~SYSMODE_PREFIX_REPE; } else if (M.x86.mode & SYSMODE_PREFIX_REPNE) { /* REPNE */ /* move them until CX is ZERO. */ while (M.x86.R_CX != 0) { if (M.x86.mode & SYSMODE_PREFIX_DATA) { val = fetch_data_long_abs(M.x86.R_ES, M.x86.R_DI); cmp_long(M.x86.R_EAX, val); } else { val = fetch_data_word_abs(M.x86.R_ES, M.x86.R_DI); cmp_word(M.x86.R_AX, (u16)val); } M.x86.R_CX -= 1; M.x86.R_DI += inc; if (ACCESS_FLAG(F_ZF)) break; /* zero flag set means equal */ } M.x86.mode &= ~SYSMODE_PREFIX_REPNE; } else { if (M.x86.mode & SYSMODE_PREFIX_DATA) { val = fetch_data_long_abs(M.x86.R_ES, M.x86.R_DI); cmp_long(M.x86.R_EAX, val); } else { val = fetch_data_word_abs(M.x86.R_ES, M.x86.R_DI); cmp_word(M.x86.R_AX, (u16)val); } M.x86.R_DI += inc; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xb0 ****************************************************************************/ void x86emuOp_mov_byte_AL_IMM(u8 X86EMU_UNUSED(op1)) { u8 imm; START_OF_INSTR(); DECODE_PRINTF("MOV\tAL,"); imm = fetch_byte_imm(); DECODE_PRINTF2("%x\n", imm); TRACE_AND_STEP(); M.x86.R_AL = imm; DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xb1 ****************************************************************************/ void x86emuOp_mov_byte_CL_IMM(u8 X86EMU_UNUSED(op1)) { u8 imm; START_OF_INSTR(); DECODE_PRINTF("MOV\tCL,"); imm = fetch_byte_imm(); DECODE_PRINTF2("%x\n", imm); TRACE_AND_STEP(); M.x86.R_CL = imm; DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xb2 ****************************************************************************/ void x86emuOp_mov_byte_DL_IMM(u8 X86EMU_UNUSED(op1)) { u8 imm; START_OF_INSTR(); DECODE_PRINTF("MOV\tDL,"); imm = fetch_byte_imm(); DECODE_PRINTF2("%x\n", imm); TRACE_AND_STEP(); M.x86.R_DL = imm; DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xb3 ****************************************************************************/ void x86emuOp_mov_byte_BL_IMM(u8 X86EMU_UNUSED(op1)) { u8 imm; START_OF_INSTR(); DECODE_PRINTF("MOV\tBL,"); imm = fetch_byte_imm(); DECODE_PRINTF2("%x\n", imm); TRACE_AND_STEP(); M.x86.R_BL = imm; DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xb4 ****************************************************************************/ void x86emuOp_mov_byte_AH_IMM(u8 X86EMU_UNUSED(op1)) { u8 imm; START_OF_INSTR(); DECODE_PRINTF("MOV\tAH,"); imm = fetch_byte_imm(); DECODE_PRINTF2("%x\n", imm); TRACE_AND_STEP(); M.x86.R_AH = imm; DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xb5 ****************************************************************************/ void x86emuOp_mov_byte_CH_IMM(u8 X86EMU_UNUSED(op1)) { u8 imm; START_OF_INSTR(); DECODE_PRINTF("MOV\tCH,"); imm = fetch_byte_imm(); DECODE_PRINTF2("%x\n", imm); TRACE_AND_STEP(); M.x86.R_CH = imm; DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xb6 ****************************************************************************/ void x86emuOp_mov_byte_DH_IMM(u8 X86EMU_UNUSED(op1)) { u8 imm; START_OF_INSTR(); DECODE_PRINTF("MOV\tDH,"); imm = fetch_byte_imm(); DECODE_PRINTF2("%x\n", imm); TRACE_AND_STEP(); M.x86.R_DH = imm; DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xb7 ****************************************************************************/ void x86emuOp_mov_byte_BH_IMM(u8 X86EMU_UNUSED(op1)) { u8 imm; START_OF_INSTR(); DECODE_PRINTF("MOV\tBH,"); imm = fetch_byte_imm(); DECODE_PRINTF2("%x\n", imm); TRACE_AND_STEP(); M.x86.R_BH = imm; DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xb8 ****************************************************************************/ void x86emuOp_mov_word_AX_IMM(u8 X86EMU_UNUSED(op1)) { u32 srcval; START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("MOV\tEAX,"); srcval = fetch_long_imm(); } else { DECODE_PRINTF("MOV\tAX,"); srcval = fetch_word_imm(); } DECODE_PRINTF2("%x\n", srcval); TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { M.x86.R_EAX = srcval; } else { M.x86.R_AX = (u16)srcval; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xb9 ****************************************************************************/ void x86emuOp_mov_word_CX_IMM(u8 X86EMU_UNUSED(op1)) { u32 srcval; START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("MOV\tECX,"); srcval = fetch_long_imm(); } else { DECODE_PRINTF("MOV\tCX,"); srcval = fetch_word_imm(); } DECODE_PRINTF2("%x\n", srcval); TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { M.x86.R_ECX = srcval; } else { M.x86.R_CX = (u16)srcval; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xba ****************************************************************************/ void x86emuOp_mov_word_DX_IMM(u8 X86EMU_UNUSED(op1)) { u32 srcval; START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("MOV\tEDX,"); srcval = fetch_long_imm(); } else { DECODE_PRINTF("MOV\tDX,"); srcval = fetch_word_imm(); } DECODE_PRINTF2("%x\n", srcval); TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { M.x86.R_EDX = srcval; } else { M.x86.R_DX = (u16)srcval; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xbb ****************************************************************************/ void x86emuOp_mov_word_BX_IMM(u8 X86EMU_UNUSED(op1)) { u32 srcval; START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("MOV\tEBX,"); srcval = fetch_long_imm(); } else { DECODE_PRINTF("MOV\tBX,"); srcval = fetch_word_imm(); } DECODE_PRINTF2("%x\n", srcval); TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { M.x86.R_EBX = srcval; } else { M.x86.R_BX = (u16)srcval; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xbc ****************************************************************************/ void x86emuOp_mov_word_SP_IMM(u8 X86EMU_UNUSED(op1)) { u32 srcval; START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("MOV\tESP,"); srcval = fetch_long_imm(); } else { DECODE_PRINTF("MOV\tSP,"); srcval = fetch_word_imm(); } DECODE_PRINTF2("%x\n", srcval); TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { M.x86.R_ESP = srcval; } else { M.x86.R_SP = (u16)srcval; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xbd ****************************************************************************/ void x86emuOp_mov_word_BP_IMM(u8 X86EMU_UNUSED(op1)) { u32 srcval; START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("MOV\tEBP,"); srcval = fetch_long_imm(); } else { DECODE_PRINTF("MOV\tBP,"); srcval = fetch_word_imm(); } DECODE_PRINTF2("%x\n", srcval); TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { M.x86.R_EBP = srcval; } else { M.x86.R_BP = (u16)srcval; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xbe ****************************************************************************/ void x86emuOp_mov_word_SI_IMM(u8 X86EMU_UNUSED(op1)) { u32 srcval; START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("MOV\tESI,"); srcval = fetch_long_imm(); } else { DECODE_PRINTF("MOV\tSI,"); srcval = fetch_word_imm(); } DECODE_PRINTF2("%x\n", srcval); TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { M.x86.R_ESI = srcval; } else { M.x86.R_SI = (u16)srcval; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xbf ****************************************************************************/ void x86emuOp_mov_word_DI_IMM(u8 X86EMU_UNUSED(op1)) { u32 srcval; START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("MOV\tEDI,"); srcval = fetch_long_imm(); } else { DECODE_PRINTF("MOV\tDI,"); srcval = fetch_word_imm(); } DECODE_PRINTF2("%x\n", srcval); TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { M.x86.R_EDI = srcval; } else { M.x86.R_DI = (u16)srcval; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /* used by opcodes c0, d0, and d2. */ static u8(*opcD0_byte_operation[])(u8 d, u8 s) = { rol_byte, ror_byte, rcl_byte, rcr_byte, shl_byte, shr_byte, shl_byte, /* sal_byte === shl_byte by definition */ sar_byte, }; /**************************************************************************** REMARKS: Handles opcode 0xc0 ****************************************************************************/ void x86emuOp_opcC0_byte_RM_MEM(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; u8 *destreg; uint destoffset; u8 destval; u8 amt; /* * Yet another weirdo special case instruction format. Part of * the opcode held below in "RH". Doubly nested case would * result, except that the decoded instruction */ START_OF_INSTR(); FETCH_DECODE_MODRM(mod, rh, rl); #ifdef DEBUG if (DEBUG_DECODE()) { /* XXX DECODE_PRINTF may be changed to something more general, so that it is important to leave the strings in the same format, even though the result is that the above test is done twice. */ switch (rh) { case 0: DECODE_PRINTF("ROL\t"); break; case 1: DECODE_PRINTF("ROR\t"); break; case 2: DECODE_PRINTF("RCL\t"); break; case 3: DECODE_PRINTF("RCR\t"); break; case 4: DECODE_PRINTF("SHL\t"); break; case 5: DECODE_PRINTF("SHR\t"); break; case 6: DECODE_PRINTF("SAL\t"); break; case 7: DECODE_PRINTF("SAR\t"); break; } } #endif /* know operation, decode the mod byte to find the addressing mode. */ switch (mod) { case 0: DECODE_PRINTF("BYTE PTR "); destoffset = decode_rm00_address(rl); amt = fetch_byte_imm(); DECODE_PRINTF2(",%x\n", amt); destval = fetch_data_byte(destoffset); TRACE_AND_STEP(); destval = (*opcD0_byte_operation[rh]) (destval, amt); store_data_byte(destoffset, destval); break; case 1: DECODE_PRINTF("BYTE PTR "); destoffset = decode_rm01_address(rl); amt = fetch_byte_imm(); DECODE_PRINTF2(",%x\n", amt); destval = fetch_data_byte(destoffset); TRACE_AND_STEP(); destval = (*opcD0_byte_operation[rh]) (destval, amt); store_data_byte(destoffset, destval); break; case 2: DECODE_PRINTF("BYTE PTR "); destoffset = decode_rm10_address(rl); amt = fetch_byte_imm(); DECODE_PRINTF2(",%x\n", amt); destval = fetch_data_byte(destoffset); TRACE_AND_STEP(); destval = (*opcD0_byte_operation[rh]) (destval, amt); store_data_byte(destoffset, destval); break; case 3: /* register to register */ destreg = DECODE_RM_BYTE_REGISTER(rl); amt = fetch_byte_imm(); DECODE_PRINTF2(",%x\n", amt); TRACE_AND_STEP(); destval = (*opcD0_byte_operation[rh]) (*destreg, amt); *destreg = destval; break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /* used by opcodes c1, d1, and d3. */ static u16(*opcD1_word_operation[])(u16 s, u8 d) = { rol_word, ror_word, rcl_word, rcr_word, shl_word, shr_word, shl_word, /* sal_byte === shl_byte by definition */ sar_word, }; /* used by opcodes c1, d1, and d3. */ static u32 (*opcD1_long_operation[])(u32 s, u8 d) = { rol_long, ror_long, rcl_long, rcr_long, shl_long, shr_long, shl_long, /* sal_byte === shl_byte by definition */ sar_long, }; /**************************************************************************** REMARKS: Handles opcode 0xc1 ****************************************************************************/ void x86emuOp_opcC1_word_RM_MEM(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; uint destoffset; u8 amt; /* * Yet another weirdo special case instruction format. Part of * the opcode held below in "RH". Doubly nested case would * result, except that the decoded instruction */ START_OF_INSTR(); FETCH_DECODE_MODRM(mod, rh, rl); #ifdef DEBUG if (DEBUG_DECODE()) { /* XXX DECODE_PRINTF may be changed to something more general, so that it is important to leave the strings in the same format, even though the result is that the above test is done twice. */ switch (rh) { case 0: DECODE_PRINTF("ROL\t"); break; case 1: DECODE_PRINTF("ROR\t"); break; case 2: DECODE_PRINTF("RCL\t"); break; case 3: DECODE_PRINTF("RCR\t"); break; case 4: DECODE_PRINTF("SHL\t"); break; case 5: DECODE_PRINTF("SHR\t"); break; case 6: DECODE_PRINTF("SAL\t"); break; case 7: DECODE_PRINTF("SAR\t"); break; } } #endif /* know operation, decode the mod byte to find the addressing mode. */ switch (mod) { case 0: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; DECODE_PRINTF("DWORD PTR "); destoffset = decode_rm00_address(rl); amt = fetch_byte_imm(); DECODE_PRINTF2(",%x\n", amt); destval = fetch_data_long(destoffset); TRACE_AND_STEP(); destval = (*opcD1_long_operation[rh]) (destval, amt); store_data_long(destoffset, destval); } else { u16 destval; DECODE_PRINTF("WORD PTR "); destoffset = decode_rm00_address(rl); amt = fetch_byte_imm(); DECODE_PRINTF2(",%x\n", amt); destval = fetch_data_word(destoffset); TRACE_AND_STEP(); destval = (*opcD1_word_operation[rh]) (destval, amt); store_data_word(destoffset, destval); } break; case 1: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; DECODE_PRINTF("DWORD PTR "); destoffset = decode_rm01_address(rl); amt = fetch_byte_imm(); DECODE_PRINTF2(",%x\n", amt); destval = fetch_data_long(destoffset); TRACE_AND_STEP(); destval = (*opcD1_long_operation[rh]) (destval, amt); store_data_long(destoffset, destval); } else { u16 destval; DECODE_PRINTF("WORD PTR "); destoffset = decode_rm01_address(rl); amt = fetch_byte_imm(); DECODE_PRINTF2(",%x\n", amt); destval = fetch_data_word(destoffset); TRACE_AND_STEP(); destval = (*opcD1_word_operation[rh]) (destval, amt); store_data_word(destoffset, destval); } break; case 2: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; DECODE_PRINTF("DWORD PTR "); destoffset = decode_rm10_address(rl); amt = fetch_byte_imm(); DECODE_PRINTF2(",%x\n", amt); destval = fetch_data_long(destoffset); TRACE_AND_STEP(); destval = (*opcD1_long_operation[rh]) (destval, amt); store_data_long(destoffset, destval); } else { u16 destval; DECODE_PRINTF("WORD PTR "); destoffset = decode_rm10_address(rl); amt = fetch_byte_imm(); DECODE_PRINTF2(",%x\n", amt); destval = fetch_data_word(destoffset); TRACE_AND_STEP(); destval = (*opcD1_word_operation[rh]) (destval, amt); store_data_word(destoffset, destval); } break; case 3: /* register to register */ if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg; destreg = DECODE_RM_LONG_REGISTER(rl); amt = fetch_byte_imm(); DECODE_PRINTF2(",%x\n", amt); TRACE_AND_STEP(); *destreg = (*opcD1_long_operation[rh]) (*destreg, amt); } else { u16 *destreg; destreg = DECODE_RM_WORD_REGISTER(rl); amt = fetch_byte_imm(); DECODE_PRINTF2(",%x\n", amt); TRACE_AND_STEP(); *destreg = (*opcD1_word_operation[rh]) (*destreg, amt); } break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xc2 ****************************************************************************/ void x86emuOp_ret_near_IMM(u8 X86EMU_UNUSED(op1)) { u16 imm; START_OF_INSTR(); DECODE_PRINTF("RET\t"); imm = fetch_word_imm(); DECODE_PRINTF2("%x\n", imm); RETURN_TRACE("RET",M.x86.saved_cs,M.x86.saved_ip); TRACE_AND_STEP(); M.x86.R_IP = pop_word(); M.x86.R_SP += imm; DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xc3 ****************************************************************************/ void x86emuOp_ret_near(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); DECODE_PRINTF("RET\n"); RETURN_TRACE("RET",M.x86.saved_cs,M.x86.saved_ip); TRACE_AND_STEP(); M.x86.R_IP = pop_word(); DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xc4 ****************************************************************************/ void x86emuOp_les_R_IMM(u8 X86EMU_UNUSED(op1)) { int mod, rh, rl; u16 *dstreg; uint srcoffset; START_OF_INSTR(); DECODE_PRINTF("LES\t"); FETCH_DECODE_MODRM(mod, rh, rl); switch (mod) { case 0: dstreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm00_address(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *dstreg = fetch_data_word(srcoffset); M.x86.R_ES = fetch_data_word(srcoffset + 2); break; case 1: dstreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm01_address(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *dstreg = fetch_data_word(srcoffset); M.x86.R_ES = fetch_data_word(srcoffset + 2); break; case 2: dstreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm10_address(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *dstreg = fetch_data_word(srcoffset); M.x86.R_ES = fetch_data_word(srcoffset + 2); break; case 3: /* register to register */ /* UNDEFINED! */ TRACE_AND_STEP(); } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xc5 ****************************************************************************/ void x86emuOp_lds_R_IMM(u8 X86EMU_UNUSED(op1)) { int mod, rh, rl; u16 *dstreg; uint srcoffset; START_OF_INSTR(); DECODE_PRINTF("LDS\t"); FETCH_DECODE_MODRM(mod, rh, rl); switch (mod) { case 0: dstreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm00_address(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *dstreg = fetch_data_word(srcoffset); M.x86.R_DS = fetch_data_word(srcoffset + 2); break; case 1: dstreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm01_address(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *dstreg = fetch_data_word(srcoffset); M.x86.R_DS = fetch_data_word(srcoffset + 2); break; case 2: dstreg = DECODE_RM_WORD_REGISTER(rh); DECODE_PRINTF(","); srcoffset = decode_rm10_address(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *dstreg = fetch_data_word(srcoffset); M.x86.R_DS = fetch_data_word(srcoffset + 2); break; case 3: /* register to register */ /* UNDEFINED! */ TRACE_AND_STEP(); } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xc6 ****************************************************************************/ void x86emuOp_mov_byte_RM_IMM(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; u8 *destreg; uint destoffset; u8 imm; START_OF_INSTR(); DECODE_PRINTF("MOV\t"); FETCH_DECODE_MODRM(mod, rh, rl); if (rh != 0) { DECODE_PRINTF("ILLEGAL DECODE OF OPCODE c6\n"); HALT_SYS(); } switch (mod) { case 0: DECODE_PRINTF("BYTE PTR "); destoffset = decode_rm00_address(rl); imm = fetch_byte_imm(); DECODE_PRINTF2(",%2x\n", imm); TRACE_AND_STEP(); store_data_byte(destoffset, imm); break; case 1: DECODE_PRINTF("BYTE PTR "); destoffset = decode_rm01_address(rl); imm = fetch_byte_imm(); DECODE_PRINTF2(",%2x\n", imm); TRACE_AND_STEP(); store_data_byte(destoffset, imm); break; case 2: DECODE_PRINTF("BYTE PTR "); destoffset = decode_rm10_address(rl); imm = fetch_byte_imm(); DECODE_PRINTF2(",%2x\n", imm); TRACE_AND_STEP(); store_data_byte(destoffset, imm); break; case 3: /* register to register */ destreg = DECODE_RM_BYTE_REGISTER(rl); imm = fetch_byte_imm(); DECODE_PRINTF2(",%2x\n", imm); TRACE_AND_STEP(); *destreg = imm; break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xc7 ****************************************************************************/ void x86emuOp_mov_word_RM_IMM(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; uint destoffset; START_OF_INSTR(); DECODE_PRINTF("MOV\t"); FETCH_DECODE_MODRM(mod, rh, rl); if (rh != 0) { DECODE_PRINTF("ILLEGAL DECODE OF OPCODE 8F\n"); HALT_SYS(); } switch (mod) { case 0: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 imm; DECODE_PRINTF("DWORD PTR "); destoffset = decode_rm00_address(rl); imm = fetch_long_imm(); DECODE_PRINTF2(",%x\n", imm); TRACE_AND_STEP(); store_data_long(destoffset, imm); } else { u16 imm; DECODE_PRINTF("WORD PTR "); destoffset = decode_rm00_address(rl); imm = fetch_word_imm(); DECODE_PRINTF2(",%x\n", imm); TRACE_AND_STEP(); store_data_word(destoffset, imm); } break; case 1: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 imm; DECODE_PRINTF("DWORD PTR "); destoffset = decode_rm01_address(rl); imm = fetch_long_imm(); DECODE_PRINTF2(",%x\n", imm); TRACE_AND_STEP(); store_data_long(destoffset, imm); } else { u16 imm; DECODE_PRINTF("WORD PTR "); destoffset = decode_rm01_address(rl); imm = fetch_word_imm(); DECODE_PRINTF2(",%x\n", imm); TRACE_AND_STEP(); store_data_word(destoffset, imm); } break; case 2: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 imm; DECODE_PRINTF("DWORD PTR "); destoffset = decode_rm10_address(rl); imm = fetch_long_imm(); DECODE_PRINTF2(",%x\n", imm); TRACE_AND_STEP(); store_data_long(destoffset, imm); } else { u16 imm; DECODE_PRINTF("WORD PTR "); destoffset = decode_rm10_address(rl); imm = fetch_word_imm(); DECODE_PRINTF2(",%x\n", imm); TRACE_AND_STEP(); store_data_word(destoffset, imm); } break; case 3: /* register to register */ if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg; u32 imm; destreg = DECODE_RM_LONG_REGISTER(rl); imm = fetch_long_imm(); DECODE_PRINTF2(",%x\n", imm); TRACE_AND_STEP(); *destreg = imm; } else { u16 *destreg; u16 imm; destreg = DECODE_RM_WORD_REGISTER(rl); imm = fetch_word_imm(); DECODE_PRINTF2(",%x\n", imm); TRACE_AND_STEP(); *destreg = imm; } break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xc8 ****************************************************************************/ void x86emuOp_enter(u8 X86EMU_UNUSED(op1)) { u16 local,frame_pointer; u8 nesting; int i; START_OF_INSTR(); local = fetch_word_imm(); nesting = fetch_byte_imm(); DECODE_PRINTF2("ENTER %x\n", local); DECODE_PRINTF2(",%x\n", nesting); TRACE_AND_STEP(); push_word(M.x86.R_BP); frame_pointer = M.x86.R_SP; if (nesting > 0) { for (i = 1; i < nesting; i++) { M.x86.R_BP -= 2; push_word(fetch_data_word_abs(M.x86.R_SS, M.x86.R_BP)); } push_word(frame_pointer); } M.x86.R_BP = frame_pointer; M.x86.R_SP = (u16)(M.x86.R_SP - local); DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xc9 ****************************************************************************/ void x86emuOp_leave(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); DECODE_PRINTF("LEAVE\n"); TRACE_AND_STEP(); M.x86.R_SP = M.x86.R_BP; M.x86.R_BP = pop_word(); DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xca ****************************************************************************/ void x86emuOp_ret_far_IMM(u8 X86EMU_UNUSED(op1)) { u16 imm; START_OF_INSTR(); DECODE_PRINTF("RETF\t"); imm = fetch_word_imm(); DECODE_PRINTF2("%x\n", imm); RETURN_TRACE("RETF",M.x86.saved_cs,M.x86.saved_ip); TRACE_AND_STEP(); M.x86.R_IP = pop_word(); M.x86.R_CS = pop_word(); M.x86.R_SP += imm; DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xcb ****************************************************************************/ void x86emuOp_ret_far(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); DECODE_PRINTF("RETF\n"); RETURN_TRACE("RETF",M.x86.saved_cs,M.x86.saved_ip); TRACE_AND_STEP(); M.x86.R_IP = pop_word(); M.x86.R_CS = pop_word(); DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xcc ****************************************************************************/ void x86emuOp_int3(u8 X86EMU_UNUSED(op1)) { u16 tmp; START_OF_INSTR(); DECODE_PRINTF("INT 3\n"); tmp = (u16) mem_access_word(3 * 4 + 2); /* access the segment register */ TRACE_AND_STEP(); if (_X86EMU_intrTab[3]) { (*_X86EMU_intrTab[3])(3); } else { push_word((u16)M.x86.R_FLG); CLEAR_FLAG(F_IF); CLEAR_FLAG(F_TF); push_word(M.x86.R_CS); M.x86.R_CS = mem_access_word(3 * 4 + 2); push_word(M.x86.R_IP); M.x86.R_IP = mem_access_word(3 * 4); } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xcd ****************************************************************************/ void x86emuOp_int_IMM(u8 X86EMU_UNUSED(op1)) { u16 tmp; u8 intnum; START_OF_INSTR(); DECODE_PRINTF("INT\t"); intnum = fetch_byte_imm(); DECODE_PRINTF2("%x\n", intnum); tmp = mem_access_word(intnum * 4 + 2); TRACE_AND_STEP(); if (_X86EMU_intrTab[intnum]) { (*_X86EMU_intrTab[intnum])(intnum); } else { push_word((u16)M.x86.R_FLG); CLEAR_FLAG(F_IF); CLEAR_FLAG(F_TF); push_word(M.x86.R_CS); M.x86.R_CS = mem_access_word(intnum * 4 + 2); push_word(M.x86.R_IP); M.x86.R_IP = mem_access_word(intnum * 4); } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xce ****************************************************************************/ void x86emuOp_into(u8 X86EMU_UNUSED(op1)) { u16 tmp; START_OF_INSTR(); DECODE_PRINTF("INTO\n"); TRACE_AND_STEP(); if (ACCESS_FLAG(F_OF)) { tmp = mem_access_word(4 * 4 + 2); if (_X86EMU_intrTab[4]) { (*_X86EMU_intrTab[4])(4); } else { push_word((u16)M.x86.R_FLG); CLEAR_FLAG(F_IF); CLEAR_FLAG(F_TF); push_word(M.x86.R_CS); M.x86.R_CS = mem_access_word(4 * 4 + 2); push_word(M.x86.R_IP); M.x86.R_IP = mem_access_word(4 * 4); } } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xcf ****************************************************************************/ void x86emuOp_iret(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); DECODE_PRINTF("IRET\n"); TRACE_AND_STEP(); M.x86.R_IP = pop_word(); M.x86.R_CS = pop_word(); M.x86.R_FLG = pop_word(); DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xd0 ****************************************************************************/ void x86emuOp_opcD0_byte_RM_1(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; u8 *destreg; uint destoffset; u8 destval; /* * Yet another weirdo special case instruction format. Part of * the opcode held below in "RH". Doubly nested case would * result, except that the decoded instruction */ START_OF_INSTR(); FETCH_DECODE_MODRM(mod, rh, rl); #ifdef DEBUG if (DEBUG_DECODE()) { /* XXX DECODE_PRINTF may be changed to something more general, so that it is important to leave the strings in the same format, even though the result is that the above test is done twice. */ switch (rh) { case 0: DECODE_PRINTF("ROL\t"); break; case 1: DECODE_PRINTF("ROR\t"); break; case 2: DECODE_PRINTF("RCL\t"); break; case 3: DECODE_PRINTF("RCR\t"); break; case 4: DECODE_PRINTF("SHL\t"); break; case 5: DECODE_PRINTF("SHR\t"); break; case 6: DECODE_PRINTF("SAL\t"); break; case 7: DECODE_PRINTF("SAR\t"); break; } } #endif /* know operation, decode the mod byte to find the addressing mode. */ switch (mod) { case 0: DECODE_PRINTF("BYTE PTR "); destoffset = decode_rm00_address(rl); DECODE_PRINTF(",1\n"); destval = fetch_data_byte(destoffset); TRACE_AND_STEP(); destval = (*opcD0_byte_operation[rh]) (destval, 1); store_data_byte(destoffset, destval); break; case 1: DECODE_PRINTF("BYTE PTR "); destoffset = decode_rm01_address(rl); DECODE_PRINTF(",1\n"); destval = fetch_data_byte(destoffset); TRACE_AND_STEP(); destval = (*opcD0_byte_operation[rh]) (destval, 1); store_data_byte(destoffset, destval); break; case 2: DECODE_PRINTF("BYTE PTR "); destoffset = decode_rm10_address(rl); DECODE_PRINTF(",1\n"); destval = fetch_data_byte(destoffset); TRACE_AND_STEP(); destval = (*opcD0_byte_operation[rh]) (destval, 1); store_data_byte(destoffset, destval); break; case 3: /* register to register */ destreg = DECODE_RM_BYTE_REGISTER(rl); DECODE_PRINTF(",1\n"); TRACE_AND_STEP(); destval = (*opcD0_byte_operation[rh]) (*destreg, 1); *destreg = destval; break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xd1 ****************************************************************************/ void x86emuOp_opcD1_word_RM_1(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; uint destoffset; /* * Yet another weirdo special case instruction format. Part of * the opcode held below in "RH". Doubly nested case would * result, except that the decoded instruction */ START_OF_INSTR(); FETCH_DECODE_MODRM(mod, rh, rl); #ifdef DEBUG if (DEBUG_DECODE()) { /* XXX DECODE_PRINTF may be changed to something more general, so that it is important to leave the strings in the same format, even though the result is that the above test is done twice. */ switch (rh) { case 0: DECODE_PRINTF("ROL\t"); break; case 1: DECODE_PRINTF("ROR\t"); break; case 2: DECODE_PRINTF("RCL\t"); break; case 3: DECODE_PRINTF("RCR\t"); break; case 4: DECODE_PRINTF("SHL\t"); break; case 5: DECODE_PRINTF("SHR\t"); break; case 6: DECODE_PRINTF("SAL\t"); break; case 7: DECODE_PRINTF("SAR\t"); break; } } #endif /* know operation, decode the mod byte to find the addressing mode. */ switch (mod) { case 0: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; DECODE_PRINTF("DWORD PTR "); destoffset = decode_rm00_address(rl); DECODE_PRINTF(",1\n"); destval = fetch_data_long(destoffset); TRACE_AND_STEP(); destval = (*opcD1_long_operation[rh]) (destval, 1); store_data_long(destoffset, destval); } else { u16 destval; DECODE_PRINTF("WORD PTR "); destoffset = decode_rm00_address(rl); DECODE_PRINTF(",1\n"); destval = fetch_data_word(destoffset); TRACE_AND_STEP(); destval = (*opcD1_word_operation[rh]) (destval, 1); store_data_word(destoffset, destval); } break; case 1: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; DECODE_PRINTF("DWORD PTR "); destoffset = decode_rm01_address(rl); DECODE_PRINTF(",1\n"); destval = fetch_data_long(destoffset); TRACE_AND_STEP(); destval = (*opcD1_long_operation[rh]) (destval, 1); store_data_long(destoffset, destval); } else { u16 destval; DECODE_PRINTF("WORD PTR "); destoffset = decode_rm01_address(rl); DECODE_PRINTF(",1\n"); destval = fetch_data_word(destoffset); TRACE_AND_STEP(); destval = (*opcD1_word_operation[rh]) (destval, 1); store_data_word(destoffset, destval); } break; case 2: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; DECODE_PRINTF("DWORD PTR "); destoffset = decode_rm10_address(rl); DECODE_PRINTF(",1\n"); destval = fetch_data_long(destoffset); TRACE_AND_STEP(); destval = (*opcD1_long_operation[rh]) (destval, 1); store_data_long(destoffset, destval); } else { u16 destval; DECODE_PRINTF("BYTE PTR "); destoffset = decode_rm10_address(rl); DECODE_PRINTF(",1\n"); destval = fetch_data_word(destoffset); TRACE_AND_STEP(); destval = (*opcD1_word_operation[rh]) (destval, 1); store_data_word(destoffset, destval); } break; case 3: /* register to register */ if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; u32 *destreg; destreg = DECODE_RM_LONG_REGISTER(rl); DECODE_PRINTF(",1\n"); TRACE_AND_STEP(); destval = (*opcD1_long_operation[rh]) (*destreg, 1); *destreg = destval; } else { u16 destval; u16 *destreg; destreg = DECODE_RM_WORD_REGISTER(rl); DECODE_PRINTF(",1\n"); TRACE_AND_STEP(); destval = (*opcD1_word_operation[rh]) (*destreg, 1); *destreg = destval; } break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xd2 ****************************************************************************/ void x86emuOp_opcD2_byte_RM_CL(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; u8 *destreg; uint destoffset; u8 destval; u8 amt; /* * Yet another weirdo special case instruction format. Part of * the opcode held below in "RH". Doubly nested case would * result, except that the decoded instruction */ START_OF_INSTR(); FETCH_DECODE_MODRM(mod, rh, rl); #ifdef DEBUG if (DEBUG_DECODE()) { /* XXX DECODE_PRINTF may be changed to something more general, so that it is important to leave the strings in the same format, even though the result is that the above test is done twice. */ switch (rh) { case 0: DECODE_PRINTF("ROL\t"); break; case 1: DECODE_PRINTF("ROR\t"); break; case 2: DECODE_PRINTF("RCL\t"); break; case 3: DECODE_PRINTF("RCR\t"); break; case 4: DECODE_PRINTF("SHL\t"); break; case 5: DECODE_PRINTF("SHR\t"); break; case 6: DECODE_PRINTF("SAL\t"); break; case 7: DECODE_PRINTF("SAR\t"); break; } } #endif /* know operation, decode the mod byte to find the addressing mode. */ amt = M.x86.R_CL; switch (mod) { case 0: DECODE_PRINTF("BYTE PTR "); destoffset = decode_rm00_address(rl); DECODE_PRINTF(",CL\n"); destval = fetch_data_byte(destoffset); TRACE_AND_STEP(); destval = (*opcD0_byte_operation[rh]) (destval, amt); store_data_byte(destoffset, destval); break; case 1: DECODE_PRINTF("BYTE PTR "); destoffset = decode_rm01_address(rl); DECODE_PRINTF(",CL\n"); destval = fetch_data_byte(destoffset); TRACE_AND_STEP(); destval = (*opcD0_byte_operation[rh]) (destval, amt); store_data_byte(destoffset, destval); break; case 2: DECODE_PRINTF("BYTE PTR "); destoffset = decode_rm10_address(rl); DECODE_PRINTF(",CL\n"); destval = fetch_data_byte(destoffset); TRACE_AND_STEP(); destval = (*opcD0_byte_operation[rh]) (destval, amt); store_data_byte(destoffset, destval); break; case 3: /* register to register */ destreg = DECODE_RM_BYTE_REGISTER(rl); DECODE_PRINTF(",CL\n"); TRACE_AND_STEP(); destval = (*opcD0_byte_operation[rh]) (*destreg, amt); *destreg = destval; break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xd3 ****************************************************************************/ void x86emuOp_opcD3_word_RM_CL(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; uint destoffset; u8 amt; /* * Yet another weirdo special case instruction format. Part of * the opcode held below in "RH". Doubly nested case would * result, except that the decoded instruction */ START_OF_INSTR(); FETCH_DECODE_MODRM(mod, rh, rl); #ifdef DEBUG if (DEBUG_DECODE()) { /* XXX DECODE_PRINTF may be changed to something more general, so that it is important to leave the strings in the same format, even though the result is that the above test is done twice. */ switch (rh) { case 0: DECODE_PRINTF("ROL\t"); break; case 1: DECODE_PRINTF("ROR\t"); break; case 2: DECODE_PRINTF("RCL\t"); break; case 3: DECODE_PRINTF("RCR\t"); break; case 4: DECODE_PRINTF("SHL\t"); break; case 5: DECODE_PRINTF("SHR\t"); break; case 6: DECODE_PRINTF("SAL\t"); break; case 7: DECODE_PRINTF("SAR\t"); break; } } #endif /* know operation, decode the mod byte to find the addressing mode. */ amt = M.x86.R_CL; switch (mod) { case 0: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; DECODE_PRINTF("DWORD PTR "); destoffset = decode_rm00_address(rl); DECODE_PRINTF(",CL\n"); destval = fetch_data_long(destoffset); TRACE_AND_STEP(); destval = (*opcD1_long_operation[rh]) (destval, amt); store_data_long(destoffset, destval); } else { u16 destval; DECODE_PRINTF("WORD PTR "); destoffset = decode_rm00_address(rl); DECODE_PRINTF(",CL\n"); destval = fetch_data_word(destoffset); TRACE_AND_STEP(); destval = (*opcD1_word_operation[rh]) (destval, amt); store_data_word(destoffset, destval); } break; case 1: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; DECODE_PRINTF("DWORD PTR "); destoffset = decode_rm01_address(rl); DECODE_PRINTF(",CL\n"); destval = fetch_data_long(destoffset); TRACE_AND_STEP(); destval = (*opcD1_long_operation[rh]) (destval, amt); store_data_long(destoffset, destval); } else { u16 destval; DECODE_PRINTF("WORD PTR "); destoffset = decode_rm01_address(rl); DECODE_PRINTF(",CL\n"); destval = fetch_data_word(destoffset); TRACE_AND_STEP(); destval = (*opcD1_word_operation[rh]) (destval, amt); store_data_word(destoffset, destval); } break; case 2: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; DECODE_PRINTF("DWORD PTR "); destoffset = decode_rm10_address(rl); DECODE_PRINTF(",CL\n"); destval = fetch_data_long(destoffset); TRACE_AND_STEP(); destval = (*opcD1_long_operation[rh]) (destval, amt); store_data_long(destoffset, destval); } else { u16 destval; DECODE_PRINTF("WORD PTR "); destoffset = decode_rm10_address(rl); DECODE_PRINTF(",CL\n"); destval = fetch_data_word(destoffset); TRACE_AND_STEP(); destval = (*opcD1_word_operation[rh]) (destval, amt); store_data_word(destoffset, destval); } break; case 3: /* register to register */ if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg; destreg = DECODE_RM_LONG_REGISTER(rl); DECODE_PRINTF(",CL\n"); TRACE_AND_STEP(); *destreg = (*opcD1_long_operation[rh]) (*destreg, amt); } else { u16 *destreg; destreg = DECODE_RM_WORD_REGISTER(rl); DECODE_PRINTF(",CL\n"); TRACE_AND_STEP(); *destreg = (*opcD1_word_operation[rh]) (*destreg, amt); } break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xd4 ****************************************************************************/ void x86emuOp_aam(u8 X86EMU_UNUSED(op1)) { u8 a; START_OF_INSTR(); DECODE_PRINTF("AAM\n"); a = fetch_byte_imm(); /* this is a stupid encoding. */ if (a != 10) { DECODE_PRINTF("ERROR DECODING AAM\n"); TRACE_REGS(); HALT_SYS(); } TRACE_AND_STEP(); /* note the type change here --- returning AL and AH in AX. */ M.x86.R_AX = aam_word(M.x86.R_AL); DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xd5 ****************************************************************************/ void x86emuOp_aad(u8 X86EMU_UNUSED(op1)) { u8 a; START_OF_INSTR(); DECODE_PRINTF("AAD\n"); a = fetch_byte_imm(); TRACE_AND_STEP(); M.x86.R_AX = aad_word(M.x86.R_AX); DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /* opcode 0xd6 ILLEGAL OPCODE */ /**************************************************************************** REMARKS: Handles opcode 0xd7 ****************************************************************************/ void x86emuOp_xlat(u8 X86EMU_UNUSED(op1)) { u16 addr; START_OF_INSTR(); DECODE_PRINTF("XLAT\n"); TRACE_AND_STEP(); addr = (u16)(M.x86.R_BX + (u8)M.x86.R_AL); M.x86.R_AL = fetch_data_byte(addr); DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /* instuctions D8 .. DF are in i87_ops.c */ /**************************************************************************** REMARKS: Handles opcode 0xe0 ****************************************************************************/ void x86emuOp_loopne(u8 X86EMU_UNUSED(op1)) { s16 ip; START_OF_INSTR(); DECODE_PRINTF("LOOPNE\t"); ip = (s8) fetch_byte_imm(); ip += (s16) M.x86.R_IP; DECODE_PRINTF2("%04x\n", ip); TRACE_AND_STEP(); M.x86.R_CX -= 1; if (M.x86.R_CX != 0 && !ACCESS_FLAG(F_ZF)) /* CX != 0 and !ZF */ M.x86.R_IP = ip; DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xe1 ****************************************************************************/ void x86emuOp_loope(u8 X86EMU_UNUSED(op1)) { s16 ip; START_OF_INSTR(); DECODE_PRINTF("LOOPE\t"); ip = (s8) fetch_byte_imm(); ip += (s16) M.x86.R_IP; DECODE_PRINTF2("%04x\n", ip); TRACE_AND_STEP(); M.x86.R_CX -= 1; if (M.x86.R_CX != 0 && ACCESS_FLAG(F_ZF)) /* CX != 0 and ZF */ M.x86.R_IP = ip; DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xe2 ****************************************************************************/ void x86emuOp_loop(u8 X86EMU_UNUSED(op1)) { s16 ip; START_OF_INSTR(); DECODE_PRINTF("LOOP\t"); ip = (s8) fetch_byte_imm(); ip += (s16) M.x86.R_IP; DECODE_PRINTF2("%04x\n", ip); TRACE_AND_STEP(); M.x86.R_CX -= 1; if (M.x86.R_CX != 0) M.x86.R_IP = ip; DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xe3 ****************************************************************************/ void x86emuOp_jcxz(u8 X86EMU_UNUSED(op1)) { u16 target; s8 offset; /* jump to byte offset if overflow flag is set */ START_OF_INSTR(); DECODE_PRINTF("JCXZ\t"); offset = (s8)fetch_byte_imm(); target = (u16)(M.x86.R_IP + offset); DECODE_PRINTF2("%x\n", target); TRACE_AND_STEP(); if (M.x86.R_CX == 0) M.x86.R_IP = target; DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xe4 ****************************************************************************/ void x86emuOp_in_byte_AL_IMM(u8 X86EMU_UNUSED(op1)) { u8 port; START_OF_INSTR(); DECODE_PRINTF("IN\t"); port = (u8) fetch_byte_imm(); DECODE_PRINTF2("%x,AL\n", port); TRACE_AND_STEP(); M.x86.R_AL = (*sys_inb)(port); DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xe5 ****************************************************************************/ void x86emuOp_in_word_AX_IMM(u8 X86EMU_UNUSED(op1)) { u8 port; START_OF_INSTR(); DECODE_PRINTF("IN\t"); port = (u8) fetch_byte_imm(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF2("EAX,%x\n", port); } else { DECODE_PRINTF2("AX,%x\n", port); } TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { M.x86.R_EAX = (*sys_inl)(port); } else { M.x86.R_AX = (*sys_inw)(port); } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xe6 ****************************************************************************/ void x86emuOp_out_byte_IMM_AL(u8 X86EMU_UNUSED(op1)) { u8 port; START_OF_INSTR(); DECODE_PRINTF("OUT\t"); port = (u8) fetch_byte_imm(); DECODE_PRINTF2("%x,AL\n", port); TRACE_AND_STEP(); (*sys_outb)(port, M.x86.R_AL); DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xe7 ****************************************************************************/ void x86emuOp_out_word_IMM_AX(u8 X86EMU_UNUSED(op1)) { u8 port; START_OF_INSTR(); DECODE_PRINTF("OUT\t"); port = (u8) fetch_byte_imm(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF2("%x,EAX\n", port); } else { DECODE_PRINTF2("%x,AX\n", port); } TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { (*sys_outl)(port, M.x86.R_EAX); } else { (*sys_outw)(port, M.x86.R_AX); } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xe8 ****************************************************************************/ void x86emuOp_call_near_IMM(u8 X86EMU_UNUSED(op1)) { s16 ip; START_OF_INSTR(); DECODE_PRINTF("CALL\t"); ip = (s16) fetch_word_imm(); ip += (s16) M.x86.R_IP; /* CHECK SIGN */ DECODE_PRINTF2("%04x\n", ip); CALL_TRACE(M.x86.saved_cs, M.x86.saved_ip, M.x86.R_CS, ip, ""); TRACE_AND_STEP(); push_word(M.x86.R_IP); M.x86.R_IP = ip; DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xe9 ****************************************************************************/ void x86emuOp_jump_near_IMM(u8 X86EMU_UNUSED(op1)) { int ip; START_OF_INSTR(); DECODE_PRINTF("JMP\t"); ip = (s16)fetch_word_imm(); ip += (s16)M.x86.R_IP; DECODE_PRINTF2("%04x\n", ip); TRACE_AND_STEP(); M.x86.R_IP = (u16)ip; DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xea ****************************************************************************/ void x86emuOp_jump_far_IMM(u8 X86EMU_UNUSED(op1)) { u16 cs, ip; START_OF_INSTR(); DECODE_PRINTF("JMP\tFAR "); ip = fetch_word_imm(); cs = fetch_word_imm(); DECODE_PRINTF2("%04x:", cs); DECODE_PRINTF2("%04x\n", ip); TRACE_AND_STEP(); M.x86.R_IP = ip; M.x86.R_CS = cs; DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xeb ****************************************************************************/ void x86emuOp_jump_byte_IMM(u8 X86EMU_UNUSED(op1)) { u16 target; s8 offset; START_OF_INSTR(); DECODE_PRINTF("JMP\t"); offset = (s8)fetch_byte_imm(); target = (u16)(M.x86.R_IP + offset); DECODE_PRINTF2("%x\n", target); TRACE_AND_STEP(); M.x86.R_IP = target; DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xec ****************************************************************************/ void x86emuOp_in_byte_AL_DX(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); DECODE_PRINTF("IN\tAL,DX\n"); TRACE_AND_STEP(); M.x86.R_AL = (*sys_inb)(M.x86.R_DX); DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xed ****************************************************************************/ void x86emuOp_in_word_AX_DX(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("IN\tEAX,DX\n"); } else { DECODE_PRINTF("IN\tAX,DX\n"); } TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { M.x86.R_EAX = (*sys_inl)(M.x86.R_DX); } else { M.x86.R_AX = (*sys_inw)(M.x86.R_DX); } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xee ****************************************************************************/ void x86emuOp_out_byte_DX_AL(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); DECODE_PRINTF("OUT\tDX,AL\n"); TRACE_AND_STEP(); (*sys_outb)(M.x86.R_DX, M.x86.R_AL); DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xef ****************************************************************************/ void x86emuOp_out_word_DX_AX(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("OUT\tDX,EAX\n"); } else { DECODE_PRINTF("OUT\tDX,AX\n"); } TRACE_AND_STEP(); if (M.x86.mode & SYSMODE_PREFIX_DATA) { (*sys_outl)(M.x86.R_DX, M.x86.R_EAX); } else { (*sys_outw)(M.x86.R_DX, M.x86.R_AX); } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xf0 ****************************************************************************/ void x86emuOp_lock(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); DECODE_PRINTF("LOCK:\n"); TRACE_AND_STEP(); DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /*opcode 0xf1 ILLEGAL OPERATION */ /**************************************************************************** REMARKS: Handles opcode 0xf2 ****************************************************************************/ void x86emuOp_repne(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); DECODE_PRINTF("REPNE\n"); TRACE_AND_STEP(); M.x86.mode |= SYSMODE_PREFIX_REPNE; DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xf3 ****************************************************************************/ void x86emuOp_repe(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); DECODE_PRINTF("REPE\n"); TRACE_AND_STEP(); M.x86.mode |= SYSMODE_PREFIX_REPE; DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xf4 ****************************************************************************/ void x86emuOp_halt(u8 X86EMU_UNUSED(op1)) { START_OF_INSTR(); DECODE_PRINTF("HALT\n"); TRACE_AND_STEP(); HALT_SYS(); DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xf5 ****************************************************************************/ void x86emuOp_cmc(u8 X86EMU_UNUSED(op1)) { /* complement the carry flag. */ START_OF_INSTR(); DECODE_PRINTF("CMC\n"); TRACE_AND_STEP(); TOGGLE_FLAG(F_CF); DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xf6 ****************************************************************************/ void x86emuOp_opcF6_byte_RM(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; u8 *destreg; uint destoffset; u8 destval, srcval; /* long, drawn out code follows. Double switch for a total of 32 cases. */ START_OF_INSTR(); FETCH_DECODE_MODRM(mod, rh, rl); switch (mod) { case 0: /* mod=00 */ switch (rh) { case 0: /* test byte imm */ DECODE_PRINTF("TEST\tBYTE PTR "); destoffset = decode_rm00_address(rl); DECODE_PRINTF(","); srcval = fetch_byte_imm(); DECODE_PRINTF2("%02x\n", srcval); destval = fetch_data_byte(destoffset); TRACE_AND_STEP(); test_byte(destval, srcval); break; case 1: DECODE_PRINTF("ILLEGAL OP MOD=00 RH=01 OP=F6\n"); HALT_SYS(); break; case 2: DECODE_PRINTF("NOT\tBYTE PTR "); destoffset = decode_rm00_address(rl); DECODE_PRINTF("\n"); destval = fetch_data_byte(destoffset); TRACE_AND_STEP(); destval = not_byte(destval); store_data_byte(destoffset, destval); break; case 3: DECODE_PRINTF("NEG\tBYTE PTR "); destoffset = decode_rm00_address(rl); DECODE_PRINTF("\n"); destval = fetch_data_byte(destoffset); TRACE_AND_STEP(); destval = neg_byte(destval); store_data_byte(destoffset, destval); break; case 4: DECODE_PRINTF("MUL\tBYTE PTR "); destoffset = decode_rm00_address(rl); DECODE_PRINTF("\n"); destval = fetch_data_byte(destoffset); TRACE_AND_STEP(); mul_byte(destval); break; case 5: DECODE_PRINTF("IMUL\tBYTE PTR "); destoffset = decode_rm00_address(rl); DECODE_PRINTF("\n"); destval = fetch_data_byte(destoffset); TRACE_AND_STEP(); imul_byte(destval); break; case 6: DECODE_PRINTF("DIV\tBYTE PTR "); destoffset = decode_rm00_address(rl); DECODE_PRINTF("\n"); destval = fetch_data_byte(destoffset); TRACE_AND_STEP(); div_byte(destval); break; case 7: DECODE_PRINTF("IDIV\tBYTE PTR "); destoffset = decode_rm00_address(rl); DECODE_PRINTF("\n"); destval = fetch_data_byte(destoffset); TRACE_AND_STEP(); idiv_byte(destval); break; } break; /* end mod==00 */ case 1: /* mod=01 */ switch (rh) { case 0: /* test byte imm */ DECODE_PRINTF("TEST\tBYTE PTR "); destoffset = decode_rm01_address(rl); DECODE_PRINTF(","); srcval = fetch_byte_imm(); DECODE_PRINTF2("%02x\n", srcval); destval = fetch_data_byte(destoffset); TRACE_AND_STEP(); test_byte(destval, srcval); break; case 1: DECODE_PRINTF("ILLEGAL OP MOD=01 RH=01 OP=F6\n"); HALT_SYS(); break; case 2: DECODE_PRINTF("NOT\tBYTE PTR "); destoffset = decode_rm01_address(rl); DECODE_PRINTF("\n"); destval = fetch_data_byte(destoffset); TRACE_AND_STEP(); destval = not_byte(destval); store_data_byte(destoffset, destval); break; case 3: DECODE_PRINTF("NEG\tBYTE PTR "); destoffset = decode_rm01_address(rl); DECODE_PRINTF("\n"); destval = fetch_data_byte(destoffset); TRACE_AND_STEP(); destval = neg_byte(destval); store_data_byte(destoffset, destval); break; case 4: DECODE_PRINTF("MUL\tBYTE PTR "); destoffset = decode_rm01_address(rl); DECODE_PRINTF("\n"); destval = fetch_data_byte(destoffset); TRACE_AND_STEP(); mul_byte(destval); break; case 5: DECODE_PRINTF("IMUL\tBYTE PTR "); destoffset = decode_rm01_address(rl); DECODE_PRINTF("\n"); destval = fetch_data_byte(destoffset); TRACE_AND_STEP(); imul_byte(destval); break; case 6: DECODE_PRINTF("DIV\tBYTE PTR "); destoffset = decode_rm01_address(rl); DECODE_PRINTF("\n"); destval = fetch_data_byte(destoffset); TRACE_AND_STEP(); div_byte(destval); break; case 7: DECODE_PRINTF("IDIV\tBYTE PTR "); destoffset = decode_rm01_address(rl); DECODE_PRINTF("\n"); destval = fetch_data_byte(destoffset); TRACE_AND_STEP(); idiv_byte(destval); break; } break; /* end mod==01 */ case 2: /* mod=10 */ switch (rh) { case 0: /* test byte imm */ DECODE_PRINTF("TEST\tBYTE PTR "); destoffset = decode_rm10_address(rl); DECODE_PRINTF(","); srcval = fetch_byte_imm(); DECODE_PRINTF2("%02x\n", srcval); destval = fetch_data_byte(destoffset); TRACE_AND_STEP(); test_byte(destval, srcval); break; case 1: DECODE_PRINTF("ILLEGAL OP MOD=10 RH=01 OP=F6\n"); HALT_SYS(); break; case 2: DECODE_PRINTF("NOT\tBYTE PTR "); destoffset = decode_rm10_address(rl); DECODE_PRINTF("\n"); destval = fetch_data_byte(destoffset); TRACE_AND_STEP(); destval = not_byte(destval); store_data_byte(destoffset, destval); break; case 3: DECODE_PRINTF("NEG\tBYTE PTR "); destoffset = decode_rm10_address(rl); DECODE_PRINTF("\n"); destval = fetch_data_byte(destoffset); TRACE_AND_STEP(); destval = neg_byte(destval); store_data_byte(destoffset, destval); break; case 4: DECODE_PRINTF("MUL\tBYTE PTR "); destoffset = decode_rm10_address(rl); DECODE_PRINTF("\n"); destval = fetch_data_byte(destoffset); TRACE_AND_STEP(); mul_byte(destval); break; case 5: DECODE_PRINTF("IMUL\tBYTE PTR "); destoffset = decode_rm10_address(rl); DECODE_PRINTF("\n"); destval = fetch_data_byte(destoffset); TRACE_AND_STEP(); imul_byte(destval); break; case 6: DECODE_PRINTF("DIV\tBYTE PTR "); destoffset = decode_rm10_address(rl); DECODE_PRINTF("\n"); destval = fetch_data_byte(destoffset); TRACE_AND_STEP(); div_byte(destval); break; case 7: DECODE_PRINTF("IDIV\tBYTE PTR "); destoffset = decode_rm10_address(rl); DECODE_PRINTF("\n"); destval = fetch_data_byte(destoffset); TRACE_AND_STEP(); idiv_byte(destval); break; } break; /* end mod==10 */ case 3: /* mod=11 */ switch (rh) { case 0: /* test byte imm */ DECODE_PRINTF("TEST\t"); destreg = DECODE_RM_BYTE_REGISTER(rl); DECODE_PRINTF(","); srcval = fetch_byte_imm(); DECODE_PRINTF2("%02x\n", srcval); TRACE_AND_STEP(); test_byte(*destreg, srcval); break; case 1: DECODE_PRINTF("ILLEGAL OP MOD=00 RH=01 OP=F6\n"); HALT_SYS(); break; case 2: DECODE_PRINTF("NOT\t"); destreg = DECODE_RM_BYTE_REGISTER(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = not_byte(*destreg); break; case 3: DECODE_PRINTF("NEG\t"); destreg = DECODE_RM_BYTE_REGISTER(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = neg_byte(*destreg); break; case 4: DECODE_PRINTF("MUL\t"); destreg = DECODE_RM_BYTE_REGISTER(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); mul_byte(*destreg); /*!!! */ break; case 5: DECODE_PRINTF("IMUL\t"); destreg = DECODE_RM_BYTE_REGISTER(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); imul_byte(*destreg); break; case 6: DECODE_PRINTF("DIV\t"); destreg = DECODE_RM_BYTE_REGISTER(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); div_byte(*destreg); break; case 7: DECODE_PRINTF("IDIV\t"); destreg = DECODE_RM_BYTE_REGISTER(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); idiv_byte(*destreg); break; } break; /* end mod==11 */ } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xf7 ****************************************************************************/ void x86emuOp_opcF7_word_RM(u8 X86EMU_UNUSED(op1)) { int mod, rl, rh; uint destoffset; /* long, drawn out code follows. Double switch for a total of 32 cases. */ START_OF_INSTR(); FETCH_DECODE_MODRM(mod, rh, rl); switch (mod) { case 0: /* mod=00 */ switch (rh) { case 0: /* test word imm */ if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval,srcval; DECODE_PRINTF("TEST\tDWORD PTR "); destoffset = decode_rm00_address(rl); DECODE_PRINTF(","); srcval = fetch_long_imm(); DECODE_PRINTF2("%x\n", srcval); destval = fetch_data_long(destoffset); TRACE_AND_STEP(); test_long(destval, srcval); } else { u16 destval,srcval; DECODE_PRINTF("TEST\tWORD PTR "); destoffset = decode_rm00_address(rl); DECODE_PRINTF(","); srcval = fetch_word_imm(); DECODE_PRINTF2("%x\n", srcval); destval = fetch_data_word(destoffset); TRACE_AND_STEP(); test_word(destval, srcval); } break; case 1: DECODE_PRINTF("ILLEGAL OP MOD=00 RH=01 OP=F7\n"); HALT_SYS(); break; case 2: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; DECODE_PRINTF("NOT\tDWORD PTR "); destoffset = decode_rm00_address(rl); DECODE_PRINTF("\n"); destval = fetch_data_long(destoffset); TRACE_AND_STEP(); destval = not_long(destval); store_data_long(destoffset, destval); } else { u16 destval; DECODE_PRINTF("NOT\tWORD PTR "); destoffset = decode_rm00_address(rl); DECODE_PRINTF("\n"); destval = fetch_data_word(destoffset); TRACE_AND_STEP(); destval = not_word(destval); store_data_word(destoffset, destval); } break; case 3: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; DECODE_PRINTF("NEG\tDWORD PTR "); destoffset = decode_rm00_address(rl); DECODE_PRINTF("\n"); destval = fetch_data_long(destoffset); TRACE_AND_STEP(); destval = neg_long(destval); store_data_long(destoffset, destval); } else { u16 destval; DECODE_PRINTF("NEG\tWORD PTR "); destoffset = decode_rm00_address(rl); DECODE_PRINTF("\n"); destval = fetch_data_word(destoffset); TRACE_AND_STEP(); destval = neg_word(destval); store_data_word(destoffset, destval); } break; case 4: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; DECODE_PRINTF("MUL\tDWORD PTR "); destoffset = decode_rm00_address(rl); DECODE_PRINTF("\n"); destval = fetch_data_long(destoffset); TRACE_AND_STEP(); mul_long(destval); } else { u16 destval; DECODE_PRINTF("MUL\tWORD PTR "); destoffset = decode_rm00_address(rl); DECODE_PRINTF("\n"); destval = fetch_data_word(destoffset); TRACE_AND_STEP(); mul_word(destval); } break; case 5: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; DECODE_PRINTF("IMUL\tDWORD PTR "); destoffset = decode_rm00_address(rl); DECODE_PRINTF("\n"); destval = fetch_data_long(destoffset); TRACE_AND_STEP(); imul_long(destval); } else { u16 destval; DECODE_PRINTF("IMUL\tWORD PTR "); destoffset = decode_rm00_address(rl); DECODE_PRINTF("\n"); destval = fetch_data_word(destoffset); TRACE_AND_STEP(); imul_word(destval); } break; case 6: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; DECODE_PRINTF("DIV\tDWORD PTR "); destoffset = decode_rm00_address(rl); DECODE_PRINTF("\n"); destval = fetch_data_long(destoffset); TRACE_AND_STEP(); div_long(destval); } else { u16 destval; DECODE_PRINTF("DIV\tWORD PTR "); destoffset = decode_rm00_address(rl); DECODE_PRINTF("\n"); destval = fetch_data_word(destoffset); TRACE_AND_STEP(); div_word(destval); } break; case 7: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; DECODE_PRINTF("IDIV\tDWORD PTR "); destoffset = decode_rm00_address(rl); DECODE_PRINTF("\n"); destval = fetch_data_long(destoffset); TRACE_AND_STEP(); idiv_long(destval); } else { u16 destval; DECODE_PRINTF("IDIV\tWORD PTR "); destoffset = decode_rm00_address(rl); DECODE_PRINTF("\n"); destval = fetch_data_word(destoffset); TRACE_AND_STEP(); idiv_word(destval); } break; } break; /* end mod==00 */ case 1: /* mod=01 */ switch (rh) { case 0: /* test word imm */ if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval,srcval; DECODE_PRINTF("TEST\tDWORD PTR "); destoffset = decode_rm01_address(rl); DECODE_PRINTF(","); srcval = fetch_long_imm(); DECODE_PRINTF2("%x\n", srcval); destval = fetch_data_long(destoffset); TRACE_AND_STEP(); test_long(destval, srcval); } else { u16 destval,srcval; DECODE_PRINTF("TEST\tWORD PTR "); destoffset = decode_rm01_address(rl); DECODE_PRINTF(","); srcval = fetch_word_imm(); DECODE_PRINTF2("%x\n", srcval); destval = fetch_data_word(destoffset); TRACE_AND_STEP(); test_word(destval, srcval); } break; case 1: DECODE_PRINTF("ILLEGAL OP MOD=01 RH=01 OP=F6\n"); HALT_SYS(); break; case 2: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; DECODE_PRINTF("NOT\tDWORD PTR "); destoffset = decode_rm01_address(rl); DECODE_PRINTF("\n"); destval = fetch_data_long(destoffset); TRACE_AND_STEP(); destval = not_long(destval); store_data_long(destoffset, destval); } else { u16 destval; DECODE_PRINTF("NOT\tWORD PTR "); destoffset = decode_rm01_address(rl); DECODE_PRINTF("\n"); destval = fetch_data_word(destoffset); TRACE_AND_STEP(); destval = not_word(destval); store_data_word(destoffset, destval); } break; case 3: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; DECODE_PRINTF("NEG\tDWORD PTR "); destoffset = decode_rm01_address(rl); DECODE_PRINTF("\n"); destval = fetch_data_long(destoffset); TRACE_AND_STEP(); destval = neg_long(destval); store_data_long(destoffset, destval); } else { u16 destval; DECODE_PRINTF("NEG\tWORD PTR "); destoffset = decode_rm01_address(rl); DECODE_PRINTF("\n"); destval = fetch_data_word(destoffset); TRACE_AND_STEP(); destval = neg_word(destval); store_data_word(destoffset, destval); } break; case 4: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; DECODE_PRINTF("MUL\tDWORD PTR "); destoffset = decode_rm01_address(rl); DECODE_PRINTF("\n"); destval = fetch_data_long(destoffset); TRACE_AND_STEP(); mul_long(destval); } else { u16 destval; DECODE_PRINTF("MUL\tWORD PTR "); destoffset = decode_rm01_address(rl); DECODE_PRINTF("\n"); destval = fetch_data_word(destoffset); TRACE_AND_STEP(); mul_word(destval); } break; case 5: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; DECODE_PRINTF("IMUL\tDWORD PTR "); destoffset = decode_rm01_address(rl); DECODE_PRINTF("\n"); destval = fetch_data_long(destoffset); TRACE_AND_STEP(); imul_long(destval); } else { u16 destval; DECODE_PRINTF("IMUL\tWORD PTR "); destoffset = decode_rm01_address(rl); DECODE_PRINTF("\n"); destval = fetch_data_word(destoffset); TRACE_AND_STEP(); imul_word(destval); } break; case 6: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; DECODE_PRINTF("DIV\tDWORD PTR "); destoffset = decode_rm01_address(rl); DECODE_PRINTF("\n"); destval = fetch_data_long(destoffset); TRACE_AND_STEP(); div_long(destval); } else { u16 destval; DECODE_PRINTF("DIV\tWORD PTR "); destoffset = decode_rm01_address(rl); DECODE_PRINTF("\n"); destval = fetch_data_word(destoffset); TRACE_AND_STEP(); div_word(destval); } break; case 7: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; DECODE_PRINTF("IDIV\tDWORD PTR "); destoffset = decode_rm01_address(rl); DECODE_PRINTF("\n"); destval = fetch_data_long(destoffset); TRACE_AND_STEP(); idiv_long(destval); } else { u16 destval; DECODE_PRINTF("IDIV\tWORD PTR "); destoffset = decode_rm01_address(rl); DECODE_PRINTF("\n"); destval = fetch_data_word(destoffset); TRACE_AND_STEP(); idiv_word(destval); } break; } break; /* end mod==01 */ case 2: /* mod=10 */ switch (rh) { case 0: /* test word imm */ if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval,srcval; DECODE_PRINTF("TEST\tDWORD PTR "); destoffset = decode_rm10_address(rl); DECODE_PRINTF(","); srcval = fetch_long_imm(); DECODE_PRINTF2("%x\n", srcval); destval = fetch_data_long(destoffset); TRACE_AND_STEP(); test_long(destval, srcval); } else { u16 destval,srcval; DECODE_PRINTF("TEST\tWORD PTR "); destoffset = decode_rm10_address(rl); DECODE_PRINTF(","); srcval = fetch_word_imm(); DECODE_PRINTF2("%x\n", srcval); destval = fetch_data_word(destoffset); TRACE_AND_STEP(); test_word(destval, srcval); } break; case 1: DECODE_PRINTF("ILLEGAL OP MOD=10 RH=01 OP=F6\n"); HALT_SYS(); break; case 2: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; DECODE_PRINTF("NOT\tDWORD PTR "); destoffset = decode_rm10_address(rl); DECODE_PRINTF("\n"); destval = fetch_data_long(destoffset); TRACE_AND_STEP(); destval = not_long(destval); store_data_long(destoffset, destval); } else { u16 destval; DECODE_PRINTF("NOT\tWORD PTR "); destoffset = decode_rm10_address(rl); DECODE_PRINTF("\n"); destval = fetch_data_word(destoffset); TRACE_AND_STEP(); destval = not_word(destval); store_data_word(destoffset, destval); } break; case 3: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; DECODE_PRINTF("NEG\tDWORD PTR "); destoffset = decode_rm10_address(rl); DECODE_PRINTF("\n"); destval = fetch_data_long(destoffset); TRACE_AND_STEP(); destval = neg_long(destval); store_data_long(destoffset, destval); } else { u16 destval; DECODE_PRINTF("NEG\tWORD PTR "); destoffset = decode_rm10_address(rl); DECODE_PRINTF("\n"); destval = fetch_data_word(destoffset); TRACE_AND_STEP(); destval = neg_word(destval); store_data_word(destoffset, destval); } break; case 4: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; DECODE_PRINTF("MUL\tDWORD PTR "); destoffset = decode_rm10_address(rl); DECODE_PRINTF("\n"); destval = fetch_data_long(destoffset); TRACE_AND_STEP(); mul_long(destval); } else { u16 destval; DECODE_PRINTF("MUL\tWORD PTR "); destoffset = decode_rm10_address(rl); DECODE_PRINTF("\n"); destval = fetch_data_word(destoffset); TRACE_AND_STEP(); mul_word(destval); } break; case 5: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; DECODE_PRINTF("IMUL\tDWORD PTR "); destoffset = decode_rm10_address(rl); DECODE_PRINTF("\n"); destval = fetch_data_long(destoffset); TRACE_AND_STEP(); imul_long(destval); } else { u16 destval; DECODE_PRINTF("IMUL\tWORD PTR "); destoffset = decode_rm10_address(rl); DECODE_PRINTF("\n"); destval = fetch_data_word(destoffset); TRACE_AND_STEP(); imul_word(destval); } break; case 6: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; DECODE_PRINTF("DIV\tDWORD PTR "); destoffset = decode_rm10_address(rl); DECODE_PRINTF("\n"); destval = fetch_data_long(destoffset); TRACE_AND_STEP(); div_long(destval); } else { u16 destval; DECODE_PRINTF("DIV\tWORD PTR "); destoffset = decode_rm10_address(rl); DECODE_PRINTF("\n"); destval = fetch_data_word(destoffset); TRACE_AND_STEP(); div_word(destval); } break; case 7: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; DECODE_PRINTF("IDIV\tDWORD PTR "); destoffset = decode_rm10_address(rl); DECODE_PRINTF("\n"); destval = fetch_data_long(destoffset); TRACE_AND_STEP(); idiv_long(destval); } else { u16 destval; DECODE_PRINTF("IDIV\tWORD PTR "); destoffset = decode_rm10_address(rl); DECODE_PRINTF("\n"); destval = fetch_data_word(destoffset); TRACE_AND_STEP(); idiv_word(destval); } break; } break; /* end mod==10 */ case 3: /* mod=11 */ switch (rh) { case 0: /* test word imm */ if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg; u32 srcval; DECODE_PRINTF("TEST\t"); destreg = DECODE_RM_LONG_REGISTER(rl); DECODE_PRINTF(","); srcval = fetch_long_imm(); DECODE_PRINTF2("%x\n", srcval); TRACE_AND_STEP(); test_long(*destreg, srcval); } else { u16 *destreg; u16 srcval; DECODE_PRINTF("TEST\t"); destreg = DECODE_RM_WORD_REGISTER(rl); DECODE_PRINTF(","); srcval = fetch_word_imm(); DECODE_PRINTF2("%x\n", srcval); TRACE_AND_STEP(); test_word(*destreg, srcval); } break; case 1: DECODE_PRINTF("ILLEGAL OP MOD=00 RH=01 OP=F6\n"); HALT_SYS(); break; case 2: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg; DECODE_PRINTF("NOT\t"); destreg = DECODE_RM_LONG_REGISTER(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = not_long(*destreg); } else { u16 *destreg; DECODE_PRINTF("NOT\t"); destreg = DECODE_RM_WORD_REGISTER(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = not_word(*destreg); } break; case 3: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg; DECODE_PRINTF("NEG\t"); destreg = DECODE_RM_LONG_REGISTER(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = neg_long(*destreg); } else { u16 *destreg; DECODE_PRINTF("NEG\t"); destreg = DECODE_RM_WORD_REGISTER(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = neg_word(*destreg); } break; case 4: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg; DECODE_PRINTF("MUL\t"); destreg = DECODE_RM_LONG_REGISTER(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); mul_long(*destreg); /*!!! */ } else { u16 *destreg; DECODE_PRINTF("MUL\t"); destreg = DECODE_RM_WORD_REGISTER(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); mul_word(*destreg); /*!!! */ } break; case 5: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg; DECODE_PRINTF("IMUL\t"); destreg = DECODE_RM_LONG_REGISTER(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); imul_long(*destreg); } else { u16 *destreg; DECODE_PRINTF("IMUL\t"); destreg = DECODE_RM_WORD_REGISTER(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); imul_word(*destreg); } break; case 6: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg; DECODE_PRINTF("DIV\t"); destreg = DECODE_RM_LONG_REGISTER(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); div_long(*destreg); } else { u16 *destreg; DECODE_PRINTF("DIV\t"); destreg = DECODE_RM_WORD_REGISTER(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); div_word(*destreg); } break; case 7: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg; DECODE_PRINTF("IDIV\t"); destreg = DECODE_RM_LONG_REGISTER(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); idiv_long(*destreg); } else { u16 *destreg; DECODE_PRINTF("IDIV\t"); destreg = DECODE_RM_WORD_REGISTER(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); idiv_word(*destreg); } break; } break; /* end mod==11 */ } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xf8 ****************************************************************************/ void x86emuOp_clc(u8 X86EMU_UNUSED(op1)) { /* clear the carry flag. */ START_OF_INSTR(); DECODE_PRINTF("CLC\n"); TRACE_AND_STEP(); CLEAR_FLAG(F_CF); DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xf9 ****************************************************************************/ void x86emuOp_stc(u8 X86EMU_UNUSED(op1)) { /* set the carry flag. */ START_OF_INSTR(); DECODE_PRINTF("STC\n"); TRACE_AND_STEP(); SET_FLAG(F_CF); DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xfa ****************************************************************************/ void x86emuOp_cli(u8 X86EMU_UNUSED(op1)) { /* clear interrupts. */ START_OF_INSTR(); DECODE_PRINTF("CLI\n"); TRACE_AND_STEP(); CLEAR_FLAG(F_IF); DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xfb ****************************************************************************/ void x86emuOp_sti(u8 X86EMU_UNUSED(op1)) { /* enable interrupts. */ START_OF_INSTR(); DECODE_PRINTF("STI\n"); TRACE_AND_STEP(); SET_FLAG(F_IF); DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xfc ****************************************************************************/ void x86emuOp_cld(u8 X86EMU_UNUSED(op1)) { /* clear interrupts. */ START_OF_INSTR(); DECODE_PRINTF("CLD\n"); TRACE_AND_STEP(); CLEAR_FLAG(F_DF); DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xfd ****************************************************************************/ void x86emuOp_std(u8 X86EMU_UNUSED(op1)) { /* clear interrupts. */ START_OF_INSTR(); DECODE_PRINTF("STD\n"); TRACE_AND_STEP(); SET_FLAG(F_DF); DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xfe ****************************************************************************/ void x86emuOp_opcFE_byte_RM(u8 X86EMU_UNUSED(op1)) { int mod, rh, rl; u8 destval; uint destoffset; u8 *destreg; /* Yet another special case instruction. */ START_OF_INSTR(); FETCH_DECODE_MODRM(mod, rh, rl); #ifdef DEBUG if (DEBUG_DECODE()) { /* XXX DECODE_PRINTF may be changed to something more general, so that it is important to leave the strings in the same format, even though the result is that the above test is done twice. */ switch (rh) { case 0: DECODE_PRINTF("INC\t"); break; case 1: DECODE_PRINTF("DEC\t"); break; case 2: case 3: case 4: case 5: case 6: case 7: DECODE_PRINTF2("ILLEGAL OP MAJOR OP 0xFE MINOR OP %x \n", mod); HALT_SYS(); break; } } #endif switch (mod) { case 0: DECODE_PRINTF("BYTE PTR "); destoffset = decode_rm00_address(rl); DECODE_PRINTF("\n"); switch (rh) { case 0: /* inc word ptr ... */ destval = fetch_data_byte(destoffset); TRACE_AND_STEP(); destval = inc_byte(destval); store_data_byte(destoffset, destval); break; case 1: /* dec word ptr ... */ destval = fetch_data_byte(destoffset); TRACE_AND_STEP(); destval = dec_byte(destval); store_data_byte(destoffset, destval); break; } break; case 1: DECODE_PRINTF("BYTE PTR "); destoffset = decode_rm01_address(rl); DECODE_PRINTF("\n"); switch (rh) { case 0: destval = fetch_data_byte(destoffset); TRACE_AND_STEP(); destval = inc_byte(destval); store_data_byte(destoffset, destval); break; case 1: destval = fetch_data_byte(destoffset); TRACE_AND_STEP(); destval = dec_byte(destval); store_data_byte(destoffset, destval); break; } break; case 2: DECODE_PRINTF("BYTE PTR "); destoffset = decode_rm10_address(rl); DECODE_PRINTF("\n"); switch (rh) { case 0: destval = fetch_data_byte(destoffset); TRACE_AND_STEP(); destval = inc_byte(destval); store_data_byte(destoffset, destval); break; case 1: destval = fetch_data_byte(destoffset); TRACE_AND_STEP(); destval = dec_byte(destval); store_data_byte(destoffset, destval); break; } break; case 3: destreg = DECODE_RM_BYTE_REGISTER(rl); DECODE_PRINTF("\n"); switch (rh) { case 0: TRACE_AND_STEP(); *destreg = inc_byte(*destreg); break; case 1: TRACE_AND_STEP(); *destreg = dec_byte(*destreg); break; } break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /**************************************************************************** REMARKS: Handles opcode 0xff ****************************************************************************/ void x86emuOp_opcFF_word_RM(u8 X86EMU_UNUSED(op1)) { int mod, rh, rl; uint destoffset = 0; u16 *destreg; u16 destval,destval2; /* Yet another special case instruction. */ START_OF_INSTR(); FETCH_DECODE_MODRM(mod, rh, rl); #ifdef DEBUG if (DEBUG_DECODE()) { /* XXX DECODE_PRINTF may be changed to something more general, so that it is important to leave the strings in the same format, even though the result is that the above test is done twice. */ switch (rh) { case 0: if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("INC\tDWORD PTR "); } else { DECODE_PRINTF("INC\tWORD PTR "); } break; case 1: if (M.x86.mode & SYSMODE_PREFIX_DATA) { DECODE_PRINTF("DEC\tDWORD PTR "); } else { DECODE_PRINTF("DEC\tWORD PTR "); } break; case 2: DECODE_PRINTF("CALL\t "); break; case 3: DECODE_PRINTF("CALL\tFAR "); break; case 4: DECODE_PRINTF("JMP\t"); break; case 5: DECODE_PRINTF("JMP\tFAR "); break; case 6: DECODE_PRINTF("PUSH\t"); break; case 7: DECODE_PRINTF("ILLEGAL DECODING OF OPCODE FF\t"); HALT_SYS(); break; } } #endif switch (mod) { case 0: destoffset = decode_rm00_address(rl); DECODE_PRINTF("\n"); switch (rh) { case 0: /* inc word ptr ... */ if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; destval = fetch_data_long(destoffset); TRACE_AND_STEP(); destval = inc_long(destval); store_data_long(destoffset, destval); } else { u16 destval; destval = fetch_data_word(destoffset); TRACE_AND_STEP(); destval = inc_word(destval); store_data_word(destoffset, destval); } break; case 1: /* dec word ptr ... */ if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; destval = fetch_data_long(destoffset); TRACE_AND_STEP(); destval = dec_long(destval); store_data_long(destoffset, destval); } else { u16 destval; destval = fetch_data_word(destoffset); TRACE_AND_STEP(); destval = dec_word(destval); store_data_word(destoffset, destval); } break; case 2: /* call word ptr ... */ destval = fetch_data_word(destoffset); TRACE_AND_STEP(); push_word(M.x86.R_IP); M.x86.R_IP = destval; break; case 3: /* call far ptr ... */ destval = fetch_data_word(destoffset); destval2 = fetch_data_word(destoffset + 2); TRACE_AND_STEP(); push_word(M.x86.R_CS); M.x86.R_CS = destval2; push_word(M.x86.R_IP); M.x86.R_IP = destval; break; case 4: /* jmp word ptr ... */ destval = fetch_data_word(destoffset); TRACE_AND_STEP(); M.x86.R_IP = destval; break; case 5: /* jmp far ptr ... */ destval = fetch_data_word(destoffset); destval2 = fetch_data_word(destoffset + 2); TRACE_AND_STEP(); M.x86.R_IP = destval; M.x86.R_CS = destval2; break; case 6: /* push word ptr ... */ if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; destval = fetch_data_long(destoffset); TRACE_AND_STEP(); push_long(destval); } else { u16 destval; destval = fetch_data_word(destoffset); TRACE_AND_STEP(); push_word(destval); } break; } break; case 1: destoffset = decode_rm01_address(rl); DECODE_PRINTF("\n"); switch (rh) { case 0: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; destval = fetch_data_long(destoffset); TRACE_AND_STEP(); destval = inc_long(destval); store_data_long(destoffset, destval); } else { u16 destval; destval = fetch_data_word(destoffset); TRACE_AND_STEP(); destval = inc_word(destval); store_data_word(destoffset, destval); } break; case 1: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; destval = fetch_data_long(destoffset); TRACE_AND_STEP(); destval = dec_long(destval); store_data_long(destoffset, destval); } else { u16 destval; destval = fetch_data_word(destoffset); TRACE_AND_STEP(); destval = dec_word(destval); store_data_word(destoffset, destval); } break; case 2: /* call word ptr ... */ destval = fetch_data_word(destoffset); TRACE_AND_STEP(); push_word(M.x86.R_IP); M.x86.R_IP = destval; break; case 3: /* call far ptr ... */ destval = fetch_data_word(destoffset); destval2 = fetch_data_word(destoffset + 2); TRACE_AND_STEP(); push_word(M.x86.R_CS); M.x86.R_CS = destval2; push_word(M.x86.R_IP); M.x86.R_IP = destval; break; case 4: /* jmp word ptr ... */ destval = fetch_data_word(destoffset); TRACE_AND_STEP(); M.x86.R_IP = destval; break; case 5: /* jmp far ptr ... */ destval = fetch_data_word(destoffset); destval2 = fetch_data_word(destoffset + 2); TRACE_AND_STEP(); M.x86.R_IP = destval; M.x86.R_CS = destval2; break; case 6: /* push word ptr ... */ if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; destval = fetch_data_long(destoffset); TRACE_AND_STEP(); push_long(destval); } else { u16 destval; destval = fetch_data_word(destoffset); TRACE_AND_STEP(); push_word(destval); } break; } break; case 2: destoffset = decode_rm10_address(rl); DECODE_PRINTF("\n"); switch (rh) { case 0: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; destval = fetch_data_long(destoffset); TRACE_AND_STEP(); destval = inc_long(destval); store_data_long(destoffset, destval); } else { u16 destval; destval = fetch_data_word(destoffset); TRACE_AND_STEP(); destval = inc_word(destval); store_data_word(destoffset, destval); } break; case 1: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; destval = fetch_data_long(destoffset); TRACE_AND_STEP(); destval = dec_long(destval); store_data_long(destoffset, destval); } else { u16 destval; destval = fetch_data_word(destoffset); TRACE_AND_STEP(); destval = dec_word(destval); store_data_word(destoffset, destval); } break; case 2: /* call word ptr ... */ destval = fetch_data_word(destoffset); TRACE_AND_STEP(); push_word(M.x86.R_IP); M.x86.R_IP = destval; break; case 3: /* call far ptr ... */ destval = fetch_data_word(destoffset); destval2 = fetch_data_word(destoffset + 2); TRACE_AND_STEP(); push_word(M.x86.R_CS); M.x86.R_CS = destval2; push_word(M.x86.R_IP); M.x86.R_IP = destval; break; case 4: /* jmp word ptr ... */ destval = fetch_data_word(destoffset); TRACE_AND_STEP(); M.x86.R_IP = destval; break; case 5: /* jmp far ptr ... */ destval = fetch_data_word(destoffset); destval2 = fetch_data_word(destoffset + 2); TRACE_AND_STEP(); M.x86.R_IP = destval; M.x86.R_CS = destval2; break; case 6: /* push word ptr ... */ if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 destval; destval = fetch_data_long(destoffset); TRACE_AND_STEP(); push_long(destval); } else { u16 destval; destval = fetch_data_word(destoffset); TRACE_AND_STEP(); push_word(destval); } break; } break; case 3: switch (rh) { case 0: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg; destreg = DECODE_RM_LONG_REGISTER(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = inc_long(*destreg); } else { u16 *destreg; destreg = DECODE_RM_WORD_REGISTER(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = inc_word(*destreg); } break; case 1: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg; destreg = DECODE_RM_LONG_REGISTER(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = dec_long(*destreg); } else { u16 *destreg; destreg = DECODE_RM_WORD_REGISTER(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); *destreg = dec_word(*destreg); } break; case 2: /* call word ptr ... */ destreg = DECODE_RM_WORD_REGISTER(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); push_word(M.x86.R_IP); M.x86.R_IP = *destreg; break; case 3: /* jmp far ptr ... */ DECODE_PRINTF("OPERATION UNDEFINED 0XFF \n"); TRACE_AND_STEP(); HALT_SYS(); break; case 4: /* jmp ... */ destreg = DECODE_RM_WORD_REGISTER(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); M.x86.R_IP = (u16) (*destreg); break; case 5: /* jmp far ptr ... */ DECODE_PRINTF("OPERATION UNDEFINED 0XFF \n"); TRACE_AND_STEP(); HALT_SYS(); break; case 6: if (M.x86.mode & SYSMODE_PREFIX_DATA) { u32 *destreg; destreg = DECODE_RM_LONG_REGISTER(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); push_long(*destreg); } else { u16 *destreg; destreg = DECODE_RM_WORD_REGISTER(rl); DECODE_PRINTF("\n"); TRACE_AND_STEP(); push_word(*destreg); } break; } break; } DECODE_CLEAR_SEGOVR(); END_OF_INSTR(); } /*************************************************************************** * Single byte operation code table: **************************************************************************/ void (*x86emu_optab[256])(u8) = { /* 0x00 */ x86emuOp_add_byte_RM_R, /* 0x01 */ x86emuOp_add_word_RM_R, /* 0x02 */ x86emuOp_add_byte_R_RM, /* 0x03 */ x86emuOp_add_word_R_RM, /* 0x04 */ x86emuOp_add_byte_AL_IMM, /* 0x05 */ x86emuOp_add_word_AX_IMM, /* 0x06 */ x86emuOp_push_ES, /* 0x07 */ x86emuOp_pop_ES, /* 0x08 */ x86emuOp_or_byte_RM_R, /* 0x09 */ x86emuOp_or_word_RM_R, /* 0x0a */ x86emuOp_or_byte_R_RM, /* 0x0b */ x86emuOp_or_word_R_RM, /* 0x0c */ x86emuOp_or_byte_AL_IMM, /* 0x0d */ x86emuOp_or_word_AX_IMM, /* 0x0e */ x86emuOp_push_CS, /* 0x0f */ x86emuOp_two_byte, /* 0x10 */ x86emuOp_adc_byte_RM_R, /* 0x11 */ x86emuOp_adc_word_RM_R, /* 0x12 */ x86emuOp_adc_byte_R_RM, /* 0x13 */ x86emuOp_adc_word_R_RM, /* 0x14 */ x86emuOp_adc_byte_AL_IMM, /* 0x15 */ x86emuOp_adc_word_AX_IMM, /* 0x16 */ x86emuOp_push_SS, /* 0x17 */ x86emuOp_pop_SS, /* 0x18 */ x86emuOp_sbb_byte_RM_R, /* 0x19 */ x86emuOp_sbb_word_RM_R, /* 0x1a */ x86emuOp_sbb_byte_R_RM, /* 0x1b */ x86emuOp_sbb_word_R_RM, /* 0x1c */ x86emuOp_sbb_byte_AL_IMM, /* 0x1d */ x86emuOp_sbb_word_AX_IMM, /* 0x1e */ x86emuOp_push_DS, /* 0x1f */ x86emuOp_pop_DS, /* 0x20 */ x86emuOp_and_byte_RM_R, /* 0x21 */ x86emuOp_and_word_RM_R, /* 0x22 */ x86emuOp_and_byte_R_RM, /* 0x23 */ x86emuOp_and_word_R_RM, /* 0x24 */ x86emuOp_and_byte_AL_IMM, /* 0x25 */ x86emuOp_and_word_AX_IMM, /* 0x26 */ x86emuOp_segovr_ES, /* 0x27 */ x86emuOp_daa, /* 0x28 */ x86emuOp_sub_byte_RM_R, /* 0x29 */ x86emuOp_sub_word_RM_R, /* 0x2a */ x86emuOp_sub_byte_R_RM, /* 0x2b */ x86emuOp_sub_word_R_RM, /* 0x2c */ x86emuOp_sub_byte_AL_IMM, /* 0x2d */ x86emuOp_sub_word_AX_IMM, /* 0x2e */ x86emuOp_segovr_CS, /* 0x2f */ x86emuOp_das, /* 0x30 */ x86emuOp_xor_byte_RM_R, /* 0x31 */ x86emuOp_xor_word_RM_R, /* 0x32 */ x86emuOp_xor_byte_R_RM, /* 0x33 */ x86emuOp_xor_word_R_RM, /* 0x34 */ x86emuOp_xor_byte_AL_IMM, /* 0x35 */ x86emuOp_xor_word_AX_IMM, /* 0x36 */ x86emuOp_segovr_SS, /* 0x37 */ x86emuOp_aaa, /* 0x38 */ x86emuOp_cmp_byte_RM_R, /* 0x39 */ x86emuOp_cmp_word_RM_R, /* 0x3a */ x86emuOp_cmp_byte_R_RM, /* 0x3b */ x86emuOp_cmp_word_R_RM, /* 0x3c */ x86emuOp_cmp_byte_AL_IMM, /* 0x3d */ x86emuOp_cmp_word_AX_IMM, /* 0x3e */ x86emuOp_segovr_DS, /* 0x3f */ x86emuOp_aas, /* 0x40 */ x86emuOp_inc_AX, /* 0x41 */ x86emuOp_inc_CX, /* 0x42 */ x86emuOp_inc_DX, /* 0x43 */ x86emuOp_inc_BX, /* 0x44 */ x86emuOp_inc_SP, /* 0x45 */ x86emuOp_inc_BP, /* 0x46 */ x86emuOp_inc_SI, /* 0x47 */ x86emuOp_inc_DI, /* 0x48 */ x86emuOp_dec_AX, /* 0x49 */ x86emuOp_dec_CX, /* 0x4a */ x86emuOp_dec_DX, /* 0x4b */ x86emuOp_dec_BX, /* 0x4c */ x86emuOp_dec_SP, /* 0x4d */ x86emuOp_dec_BP, /* 0x4e */ x86emuOp_dec_SI, /* 0x4f */ x86emuOp_dec_DI, /* 0x50 */ x86emuOp_push_AX, /* 0x51 */ x86emuOp_push_CX, /* 0x52 */ x86emuOp_push_DX, /* 0x53 */ x86emuOp_push_BX, /* 0x54 */ x86emuOp_push_SP, /* 0x55 */ x86emuOp_push_BP, /* 0x56 */ x86emuOp_push_SI, /* 0x57 */ x86emuOp_push_DI, /* 0x58 */ x86emuOp_pop_AX, /* 0x59 */ x86emuOp_pop_CX, /* 0x5a */ x86emuOp_pop_DX, /* 0x5b */ x86emuOp_pop_BX, /* 0x5c */ x86emuOp_pop_SP, /* 0x5d */ x86emuOp_pop_BP, /* 0x5e */ x86emuOp_pop_SI, /* 0x5f */ x86emuOp_pop_DI, /* 0x60 */ x86emuOp_push_all, /* 0x61 */ x86emuOp_pop_all, /* 0x62 */ x86emuOp_illegal_op, /* bound */ /* 0x63 */ x86emuOp_illegal_op, /* arpl */ /* 0x64 */ x86emuOp_segovr_FS, /* 0x65 */ x86emuOp_segovr_GS, /* 0x66 */ x86emuOp_prefix_data, /* 0x67 */ x86emuOp_prefix_addr, /* 0x68 */ x86emuOp_push_word_IMM, /* 0x69 */ x86emuOp_imul_word_IMM, /* 0x6a */ x86emuOp_push_byte_IMM, /* 0x6b */ x86emuOp_imul_byte_IMM, /* 0x6c */ x86emuOp_ins_byte, /* 0x6d */ x86emuOp_ins_word, /* 0x6e */ x86emuOp_outs_byte, /* 0x6f */ x86emuOp_outs_word, /* 0x70 */ x86emuOp_jump_near_O, /* 0x71 */ x86emuOp_jump_near_NO, /* 0x72 */ x86emuOp_jump_near_B, /* 0x73 */ x86emuOp_jump_near_NB, /* 0x74 */ x86emuOp_jump_near_Z, /* 0x75 */ x86emuOp_jump_near_NZ, /* 0x76 */ x86emuOp_jump_near_BE, /* 0x77 */ x86emuOp_jump_near_NBE, /* 0x78 */ x86emuOp_jump_near_S, /* 0x79 */ x86emuOp_jump_near_NS, /* 0x7a */ x86emuOp_jump_near_P, /* 0x7b */ x86emuOp_jump_near_NP, /* 0x7c */ x86emuOp_jump_near_L, /* 0x7d */ x86emuOp_jump_near_NL, /* 0x7e */ x86emuOp_jump_near_LE, /* 0x7f */ x86emuOp_jump_near_NLE, /* 0x80 */ x86emuOp_opc80_byte_RM_IMM, /* 0x81 */ x86emuOp_opc81_word_RM_IMM, /* 0x82 */ x86emuOp_opc82_byte_RM_IMM, /* 0x83 */ x86emuOp_opc83_word_RM_IMM, /* 0x84 */ x86emuOp_test_byte_RM_R, /* 0x85 */ x86emuOp_test_word_RM_R, /* 0x86 */ x86emuOp_xchg_byte_RM_R, /* 0x87 */ x86emuOp_xchg_word_RM_R, /* 0x88 */ x86emuOp_mov_byte_RM_R, /* 0x89 */ x86emuOp_mov_word_RM_R, /* 0x8a */ x86emuOp_mov_byte_R_RM, /* 0x8b */ x86emuOp_mov_word_R_RM, /* 0x8c */ x86emuOp_mov_word_RM_SR, /* 0x8d */ x86emuOp_lea_word_R_M, /* 0x8e */ x86emuOp_mov_word_SR_RM, /* 0x8f */ x86emuOp_pop_RM, /* 0x90 */ x86emuOp_nop, /* 0x91 */ x86emuOp_xchg_word_AX_CX, /* 0x92 */ x86emuOp_xchg_word_AX_DX, /* 0x93 */ x86emuOp_xchg_word_AX_BX, /* 0x94 */ x86emuOp_xchg_word_AX_SP, /* 0x95 */ x86emuOp_xchg_word_AX_BP, /* 0x96 */ x86emuOp_xchg_word_AX_SI, /* 0x97 */ x86emuOp_xchg_word_AX_DI, /* 0x98 */ x86emuOp_cbw, /* 0x99 */ x86emuOp_cwd, /* 0x9a */ x86emuOp_call_far_IMM, /* 0x9b */ x86emuOp_wait, /* 0x9c */ x86emuOp_pushf_word, /* 0x9d */ x86emuOp_popf_word, /* 0x9e */ x86emuOp_sahf, /* 0x9f */ x86emuOp_lahf, /* 0xa0 */ x86emuOp_mov_AL_M_IMM, /* 0xa1 */ x86emuOp_mov_AX_M_IMM, /* 0xa2 */ x86emuOp_mov_M_AL_IMM, /* 0xa3 */ x86emuOp_mov_M_AX_IMM, /* 0xa4 */ x86emuOp_movs_byte, /* 0xa5 */ x86emuOp_movs_word, /* 0xa6 */ x86emuOp_cmps_byte, /* 0xa7 */ x86emuOp_cmps_word, /* 0xa8 */ x86emuOp_test_AL_IMM, /* 0xa9 */ x86emuOp_test_AX_IMM, /* 0xaa */ x86emuOp_stos_byte, /* 0xab */ x86emuOp_stos_word, /* 0xac */ x86emuOp_lods_byte, /* 0xad */ x86emuOp_lods_word, /* 0xac */ x86emuOp_scas_byte, /* 0xad */ x86emuOp_scas_word, /* 0xb0 */ x86emuOp_mov_byte_AL_IMM, /* 0xb1 */ x86emuOp_mov_byte_CL_IMM, /* 0xb2 */ x86emuOp_mov_byte_DL_IMM, /* 0xb3 */ x86emuOp_mov_byte_BL_IMM, /* 0xb4 */ x86emuOp_mov_byte_AH_IMM, /* 0xb5 */ x86emuOp_mov_byte_CH_IMM, /* 0xb6 */ x86emuOp_mov_byte_DH_IMM, /* 0xb7 */ x86emuOp_mov_byte_BH_IMM, /* 0xb8 */ x86emuOp_mov_word_AX_IMM, /* 0xb9 */ x86emuOp_mov_word_CX_IMM, /* 0xba */ x86emuOp_mov_word_DX_IMM, /* 0xbb */ x86emuOp_mov_word_BX_IMM, /* 0xbc */ x86emuOp_mov_word_SP_IMM, /* 0xbd */ x86emuOp_mov_word_BP_IMM, /* 0xbe */ x86emuOp_mov_word_SI_IMM, /* 0xbf */ x86emuOp_mov_word_DI_IMM, /* 0xc0 */ x86emuOp_opcC0_byte_RM_MEM, /* 0xc1 */ x86emuOp_opcC1_word_RM_MEM, /* 0xc2 */ x86emuOp_ret_near_IMM, /* 0xc3 */ x86emuOp_ret_near, /* 0xc4 */ x86emuOp_les_R_IMM, /* 0xc5 */ x86emuOp_lds_R_IMM, /* 0xc6 */ x86emuOp_mov_byte_RM_IMM, /* 0xc7 */ x86emuOp_mov_word_RM_IMM, /* 0xc8 */ x86emuOp_enter, /* 0xc9 */ x86emuOp_leave, /* 0xca */ x86emuOp_ret_far_IMM, /* 0xcb */ x86emuOp_ret_far, /* 0xcc */ x86emuOp_int3, /* 0xcd */ x86emuOp_int_IMM, /* 0xce */ x86emuOp_into, /* 0xcf */ x86emuOp_iret, /* 0xd0 */ x86emuOp_opcD0_byte_RM_1, /* 0xd1 */ x86emuOp_opcD1_word_RM_1, /* 0xd2 */ x86emuOp_opcD2_byte_RM_CL, /* 0xd3 */ x86emuOp_opcD3_word_RM_CL, /* 0xd4 */ x86emuOp_aam, /* 0xd5 */ x86emuOp_aad, /* 0xd6 */ x86emuOp_illegal_op, /* Undocumented SETALC instruction */ /* 0xd7 */ x86emuOp_xlat, /* 0xd8 */ x86emuOp_esc_coprocess_d8, /* 0xd9 */ x86emuOp_esc_coprocess_d9, /* 0xda */ x86emuOp_esc_coprocess_da, /* 0xdb */ x86emuOp_esc_coprocess_db, /* 0xdc */ x86emuOp_esc_coprocess_dc, /* 0xdd */ x86emuOp_esc_coprocess_dd, /* 0xde */ x86emuOp_esc_coprocess_de, /* 0xdf */ x86emuOp_esc_coprocess_df, /* 0xe0 */ x86emuOp_loopne, /* 0xe1 */ x86emuOp_loope, /* 0xe2 */ x86emuOp_loop, /* 0xe3 */ x86emuOp_jcxz, /* 0xe4 */ x86emuOp_in_byte_AL_IMM, /* 0xe5 */ x86emuOp_in_word_AX_IMM, /* 0xe6 */ x86emuOp_out_byte_IMM_AL, /* 0xe7 */ x86emuOp_out_word_IMM_AX, /* 0xe8 */ x86emuOp_call_near_IMM, /* 0xe9 */ x86emuOp_jump_near_IMM, /* 0xea */ x86emuOp_jump_far_IMM, /* 0xeb */ x86emuOp_jump_byte_IMM, /* 0xec */ x86emuOp_in_byte_AL_DX, /* 0xed */ x86emuOp_in_word_AX_DX, /* 0xee */ x86emuOp_out_byte_DX_AL, /* 0xef */ x86emuOp_out_word_DX_AX, /* 0xf0 */ x86emuOp_lock, /* 0xf1 */ x86emuOp_illegal_op, /* 0xf2 */ x86emuOp_repne, /* 0xf3 */ x86emuOp_repe, /* 0xf4 */ x86emuOp_halt, /* 0xf5 */ x86emuOp_cmc, /* 0xf6 */ x86emuOp_opcF6_byte_RM, /* 0xf7 */ x86emuOp_opcF7_word_RM, /* 0xf8 */ x86emuOp_clc, /* 0xf9 */ x86emuOp_stc, /* 0xfa */ x86emuOp_cli, /* 0xfb */ x86emuOp_sti, /* 0xfc */ x86emuOp_cld, /* 0xfd */ x86emuOp_std, /* 0xfe */ x86emuOp_opcFE_byte_RM, /* 0xff */ x86emuOp_opcFF_word_RM, }; void tables_relocate(unsigned int offset) { int i; for (i=0; i<8; i++) { opc80_byte_operation[i] -= offset; opc81_word_operation[i] -= offset; opc81_long_operation[i] -= offset; opc82_byte_operation[i] -= offset; opc83_word_operation[i] -= offset; opc83_long_operation[i] -= offset; opcD0_byte_operation[i] -= offset; opcD1_word_operation[i] -= offset; opcD1_long_operation[i] -= offset; } }
agpl-3.0
cris-iisc/mpc-primitives
crislib/libscapi/lib/boost_1_64_0/libs/math/example/policy_ref_snip6.cpp
63
1200
// Copyright John Maddock 2007. // Copyright Paul A. Bristow 2010. // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // Note that this file contains quickbook mark-up as well as code // and comments, don't change any of the special comment mark-ups! //[policy_ref_snip6 #include <boost/math/distributions/negative_binomial.hpp> using boost::math::negative_binomial; // Use the default rounding policy integer_round_outwards. // Lower quantile rounded down: double x = quantile(negative_binomial(20, 0.3), 0.05); // rounded up 27 from 27.3898 // Upper quantile rounded up: double y = quantile(complement(negative_binomial(20, 0.3), 0.05)); // rounded down to 69 from 68.1584 //] //[/policy_ref_snip6] #include <iostream> using std::cout; using std::endl; int main() { cout << "quantile(negative_binomial(20, 0.3), 0.05) = "<< x <<endl << "quantile(complement(negative_binomial(20, 0.3), 0.05)) = " << y << endl; } /* Output: quantile(negative_binomial(20, 0.3), 0.05) = 27 quantile(complement(negative_binomial(20, 0.3), 0.05)) = 69 */
agpl-3.0
f4grx/c2fxp
c2dec.c
1
1065
/* * c2fxp - codec2 fixed point encoder/decoder. * Copyright (C) 2017 Sebastien F4GRX <f4grx@f4grx.net> * Based on original code by David Rowe <david@rowetel.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1 as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, see <http://www.gnu.org/licenses/>. */ /* codec2 decoder implementation */ #include <stdint.h> #include <stdio.h> #include "c2fxp.h" int c2dec_init(struct c2dec_context_s *ctx) { return 0; } int c2dec_write(struct c2dec_context_s *ctx, uint8_t *buf, uint32_t nsamples) { printf("c2dec process, len=%d\n",nsamples); }
lgpl-2.1
qtproject/qt-mobility
plugins/contacts/symbian/contactsmodel/tsrc/t_lowdiskspace.cpp
2
8968
/* * Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). * Contact: http://www.qt-project.org/legal * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: * */ #include <e32test.h> #include <cntdb.h> #include <cntitem.h> #include "t_lowdiskspace.h" #include <cntfldst.h> _LIT(KTestName, "T_LOWDISKSPACE"); _LIT( KFileName, "c:\\anyfile.any" ); _LIT(KDatabaseFileName,"C:T_LOWDISKSPACE"); GLDEF_D RTest test(KTestName); static const TInt KMinusFull = 50000; static const TInt64 KLowDiskThreshold = 0x20000; const TInt KFiveHundredContactItems = 500; CLowDiskSpaceTest* CLowDiskSpaceTest::NewL() { CLowDiskSpaceTest* self = new(ELeave) CLowDiskSpaceTest(); CleanupStack::PushL(self); self->ConstructL(); CleanupStack::Pop(self); return self; } CLowDiskSpaceTest::CLowDiskSpaceTest():CActive(EPriorityIdle), iCount(0), iManyFiles(0) { CActiveScheduler::Add(this); } CLowDiskSpaceTest::~CLowDiskSpaceTest() { Cleanup(); } void CLowDiskSpaceTest::Cleanup() { TRAP_IGNORE(ClearDiskL() ); delete iContactDatabase; iContactDatabase = NULL; iFileSession.Close(); iFile->Close(); delete iFile; iFile = NULL; TRAP_IGNORE(CContactDatabase::DeleteDatabaseL(KDatabaseFileName) ); Cancel(); } void CLowDiskSpaceTest::DoCancel() { } void CLowDiskSpaceTest::ConstructL() { iContactDatabase = CContactDatabase::ReplaceL(KDatabaseFileName); // populate the database with 500 contact items for (TInt i = 0; i < KFiveHundredContactItems; ++i) { AddContactToDatabaseL(); } User::LeaveIfError(iFileSession.Connect()); iFile = new(ELeave) RFile(); } void CLowDiskSpaceTest::AddContactToDatabaseL() { _LIT(KXChar, "x"); CContactItem* item = CContactCard::NewLC(); CContactItemField* field = CContactItemField::NewLC(KStorageTypeText, KUidContactFieldCompanyName); field->SetMapping(KUidContactFieldVCardMapORG); field->TextStorage()->SetTextL(KXChar() ); item->AddFieldL(*field); CleanupStack::Pop(); // field field = CContactItemField::NewLC(KStorageTypeText,KUidContactFieldPhoneNumber); field->SetMapping(KUidContactFieldVCardMapTEL); field->TextStorage()->SetTextL(KXChar() ); item->AddFieldL(*field); CleanupStack::Pop(); // field field = CContactItemField::NewLC(KStorageTypeText,KUidContactFieldPhoneNumber); field->SetMapping(KUidContactFieldVCardMapTEL); field->TextStorage()->SetTextL(KXChar() ); item->AddFieldL(*field); CleanupStack::Pop(); // field field = CContactItemField::NewLC(KStorageTypeText,KUidContactFieldPhoneNumber); field->SetMapping(KUidContactFieldVCardMapTEL); field->TextStorage()->SetTextL(KXChar() ); item->AddFieldL(*field); CleanupStack::Pop(); // field field = CContactItemField::NewLC(KStorageTypeText,KUidContactFieldPhoneNumber); field->SetMapping(KUidContactFieldVCardMapTEL); field->SetHidden(ETrue); field->TextStorage()->SetTextL(KXChar() ); item->AddFieldL(*field); CleanupStack::Pop(); // field field = CContactItemField::NewLC(KStorageTypeText,KUidContactFieldSuffixName); field->SetMapping(KUidContactFieldVCardMapUnusedN); field->TextStorage()->SetTextL(KXChar() ); item->AddFieldL(*field); CleanupStack::Pop(); // field field=CContactItemField::NewLC(KStorageTypeText,KUidContactFieldPrefixName); field->SetMapping(KUidContactFieldVCardMapUnusedN); field->TextStorage()->SetTextL(KXChar() ); item->AddFieldL(*field); CleanupStack::Pop(); // field iContactDatabase->AddNewContactL(*item); CleanupStack::PopAndDestroy(); // item } void CLowDiskSpaceTest::Start() { TRequestStatus *pS=&iStatus; User::RequestComplete(pS,KErrNone); SetActive(); } void CLowDiskSpaceTest::RunL() { TVolumeInfo tv; switch(iCount) { case EFillDisk: FillDiskL();//Fill the disk iCount++; Start(); break; case EDatabaseTest: User::LeaveIfError( iFileSession.Volume(tv) ); if(tv.iFree >= KLowDiskThreshold) { test.Printf(_L("Free space increased, refill the disk again.\n")); ClearDiskL(); FillDiskL();//Fill the disk Start(); break; } DatabaseTestL(); iCount++; Start(); break; case EClearDisk: ClearDiskL(); iCount++; Start(); break; default: CActiveScheduler::Stop(); break; } } void CLowDiskSpaceTest::FillDiskL() { _LIT(KFillDiskTitle, "Fill the disk"); test.Next(_L("Fill the disk")); TVolumeInfo tv; User::LeaveIfError( iFileSession.Volume(tv) ); TInt frees = 0; iManyFiles = tv.iFree / KMaxTInt; if ( iManyFiles > 0) { TPtrC tname( KFileName ); TInt i = 0; for( ; i < iManyFiles; ++i ) { HBufC *fval=HBufC::NewLC( tname.Length()+4 );//assume #files < 10000 TPtr fptr = fval->Des() ; fptr.Append( tname ); fptr.AppendNum( i ); User::LeaveIfError( iFile->Replace( iFileSession, fptr, EFileWrite ) ); User::LeaveIfError( iFile->SetSize( KMaxTInt ) ); iFile->Close(); CleanupStack::PopAndDestroy( fval ); } User::LeaveIfError( iFileSession.Volume(tv) ); frees = tv.iFree - KMinusFull ; if( frees <= 0 ) { frees = tv.iFree; } User::LeaveIfError( iFile->Replace( iFileSession, KFileName, EFileWrite ) ); #ifdef __SYMBIAN_CNTMODEL_USE_SQLITE__ TInt err = KErrDiskFull; while(err == KErrDiskFull) { err = iFile->SetSize(frees); frees -= 100; if(frees <= 0) { break; } } #else User::LeaveIfError( iFile->SetSize( frees ) ); #endif iFile->Close(); } else { frees = tv.iFree - KMinusFull ; if( frees <= 0 ) { frees = tv.iFree; } User::LeaveIfError( iFile->Replace( iFileSession, KFileName, EFileWrite ) ); #ifdef __SYMBIAN_CNTMODEL_USE_SQLITE__ TInt err = KErrDiskFull; while(err == KErrDiskFull) { err = iFile->SetSize(frees); frees -= 100; if(frees <= 0) { break; } } #else User::LeaveIfError( iFile->SetSize( frees ) ); #endif iFile->Close(); } } void CLowDiskSpaceTest::DatabaseTestL() { #ifndef __SYMBIAN_CNTMODEL_USE_SQLITE__ _LIT(KDatabaseTestTitle, "Add new contact and check whether disk is full"); #else _LIT(KDatabaseTestTitle, "Test add/delete contacts in low disk conditions"); #endif test.Next(_L("Test add/delete contacts in low disk conditions")); CContactCard* card=CContactCard::NewL(); CleanupStack::PushL(card); TRAPD(ret, iContactDatabase->AddNewContactL(*card)); if (ret != KErrDiskFull) { Cleanup(); // delete files filling up disk before exiting the test test(EFalse); // fail the test } #ifdef __SYMBIAN_CNTMODEL_USE_SQLITE__ _LIT(KNumContactsMsg, "Number of contacts in the database: %d\n"); _LIT(KDeletingMsg, "Deleting contact item: %d... "); _LIT(KPassMsg, " [PASS -- Contacts deleted]\n"); _LIT(KFailMsg, " [FAILED with err code: %d]\n"); test.Printf(KNumContactsMsg, iContactDatabase->CountL()); const CContactIdArray* idArray = iContactDatabase->SortedItemsL(); // don't take ownership const TInt KCount = idArray->Count(); test(KCount == KFiveHundredContactItems); // check we have all 500 items in the database iContactDatabase->DatabaseBeginLC(ETrue); for (TInt i = KCount - 1; i >= 0; --i) { const TContactItemId KItemId = (*idArray)[i]; test.Printf(KDeletingMsg, KItemId); TRAP(ret, iContactDatabase->DeleteContactL(KItemId) ); if (ret != KErrNone) { test.Printf(KFailMsg, ret); Cleanup(); // delete files filling up disk before exiting the test test(EFalse); // fail the test } } iContactDatabase->DatabaseCommitLP(ETrue); test.Printf(KPassMsg); #endif CleanupStack::PopAndDestroy(card); } void CLowDiskSpaceTest::ClearDiskL() { test.Next(_L("Clear the disk")); TPtrC tname( KFileName ); TInt i = 0; for(i = 0 ; i < iManyFiles; ++i ) { HBufC *fval=HBufC::NewLC( tname.Length()+4 );//assume #files < 10000 TPtr fptr=fval->Des(); fptr.Append( tname ); fptr.AppendNum( i ); TInt err = iFileSession.Delete( fptr ); if( err != KErrNone && err != KErrNotFound ) { User::Leave( err ); } CleanupStack::PopAndDestroy( fval ); } TInt err = iFileSession.Delete( KFileName ); if( err != KErrNone && err != KErrNotFound ) { User::Leave( err ); } } LOCAL_C void DoTestL() { CLowDiskSpaceTest* test = CLowDiskSpaceTest::NewL(); test->Start(); CActiveScheduler::Start(); delete test; } /** @SYMTestCaseID PIM-T-LOWDISKSPACE-0001 */ GLDEF_C TInt E32Main() { __UHEAP_MARK; CActiveScheduler* scheduler=new CActiveScheduler; if (scheduler) { CActiveScheduler::Install(scheduler); CTrapCleanup* cleanup=CTrapCleanup::New(); test.Start(_L("@SYMTESTCaseID:PIM-T-LOWDISKSPACE-0001 T_LOWDISKSPACE")); TRAPD(r, DoTestL()); test(r == KErrNone); test.End(); test.Close(); delete scheduler; delete cleanup; } __UHEAP_MARKEND; return KErrNone; }
lgpl-2.1
tectronics/relic-toolkit
test/test_rand.c
2
16208
/* * RELIC is an Efficient LIbrary for Cryptography * Copyright (C) 2007-2014 RELIC Authors * * This file is part of RELIC. RELIC is legal property of its developers, * whose names are not listed here. Please refer to the COPYRIGHT file * for contact information. * * RELIC is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * RELIC is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with RELIC. If not, see <http://www.gnu.org/licenses/>. */ /** * @file * * Tests for random number generation. * * @version $Id$ * @ingroup test */ #include <stdio.h> #include "relic.h" #include "relic_test.h" #if RAND == HASH /* * Test vectors taken from: * - http://csrc.nist.gov/groups/ST/toolkit/documents/Examples/Hash_DRBG.pdf */ #if MD_MAP == SHONE #define FUNCTION "sha-1" uint8_t seed1[60]; uint8_t result1[] = { 0x9F, 0x7C, 0xFF, 0x1E, 0xCA, 0x23, 0xE7, 0x50, 0xF6, 0x63, 0x26, 0x96, 0x9F, 0x11, 0x80, 0x0F, 0x12, 0x08, 0x8B, 0xA6, 0x8E, 0x44, 0x1D, 0x15, 0xD8, 0x88, 0xB3, 0xFE, 0x12, 0xBF, 0x66, 0xFE, 0x05, 0x74, 0x94, 0xF4, 0x54, 0x6D, 0xE2, 0xF1, 0xB7, 0x7A, 0xA5, 0xC0, 0xCD, 0x55, 0xBB, 0xCE, 0xED, 0x75, 0x74, 0xAF, 0x22, 0x3A, 0xFD, 0x98, 0x8C, 0x7E, 0xEC, 0x8E, 0xFF, 0x4A, 0x94, 0xE5, 0xE8, 0x9D, 0x26, 0xA0, 0x4F, 0x58, 0xFA, 0x79, 0xF5, 0xE0, 0xD3, 0x70, 0x2D, 0x7A, 0x9A, 0x6A, }; uint8_t result2[] = { 0x56, 0xEF, 0x49, 0x13, 0x37, 0x39, 0x94, 0xD5, 0x53, 0x9F, 0x4D, 0x7D, 0x17, 0xAF, 0xE7, 0x44, 0x8C, 0xDF, 0x5E, 0x72, 0x41, 0x6C, 0xC6, 0xA7, 0x1A, 0x34, 0x00, 0x59, 0xFA, 0x0D, 0x5A, 0xE5, 0x26, 0xB2, 0x32, 0x50, 0xC4, 0x6C, 0x09, 0x44, 0x57, 0x5B, 0x37, 0xA2, 0x73, 0x98, 0x14, 0xF9, 0x66, 0xC6, 0x3B, 0x60, 0xA2, 0xC4, 0xF1, 0x49, 0xCA, 0x9A, 0xCC, 0x84, 0xFC, 0x4B, 0x25, 0x49, 0x32, 0x89, 0xB0, 0x85, 0xC6, 0x7B, 0x2E, 0x30, 0xF5, 0xF0, 0xB9, 0x9A, 0x2C, 0x34, 0x9E, 0x2A, }; #elif MD_MAP == SH224 #define FUNCTION "sha-224" uint8_t seed1[62]; uint8_t result1[] = { 0x5E, 0x68, 0xBD, 0xE0, 0x9A, 0xAA, 0x08, 0xBC, 0x11, 0xB3, 0x27, 0x90, 0x2C, 0x82, 0xF0, 0x11, 0x4C, 0xBA, 0x0F, 0x9C, 0xCC, 0xA6, 0x20, 0x3B, 0xA3, 0x94, 0x00, 0x91, 0x3E, 0xCD, 0x36, 0x71, 0xA5, 0xB6, 0x0E, 0xF9, 0x22, 0x99, 0x9D, 0x90, 0xFC, 0xEE, 0xEC, 0x5C, 0x22, 0x7E, 0x5D, 0x25, 0xC5, 0x69, 0x21, 0xEE, 0x57, 0x2E, 0xD4, 0x72, 0xDC, 0x05, 0x6F, 0xCB, 0x35, 0xFF, 0x51, 0xD7, 0xD9, 0xFB, 0x72, 0xFD, 0x4F, 0xD1, 0xB1, 0xD2, 0x46, 0x45, 0x1D, 0xB5, 0x6C, 0xD4, 0xF8, 0x89, 0xE4, 0x32, 0xE3, 0x27, 0x3F, 0x9E, 0xD8, 0x2D, 0xE3, 0xEF, 0x7C, 0xD2, 0x8B, 0x6A, 0x9C, 0x0F, 0x4D, 0x78, 0xE5, 0xC8, 0x45, 0x1D, 0x36, 0x34, 0x0A, 0x2B, 0xD7, 0xE6, 0x9F, 0xAB, 0x32, 0xEB }; uint8_t result2[] = { 0x3F, 0xE2, 0xAD, 0x85, 0x24, 0xCE, 0x60, 0xE7, 0xC2, 0x1C, 0x38, 0xA1, 0xDA, 0xB0, 0x2F, 0x3C, 0x20, 0x50, 0x11, 0x82, 0xF3, 0x89, 0xEE, 0x69, 0x9F, 0x03, 0xFD, 0x87, 0x79, 0xED, 0x17, 0xC6, 0x5B, 0x87, 0xAC, 0xEE, 0xEB, 0xF1, 0xD1, 0x46, 0xE7, 0xEE, 0x10, 0x6C, 0xEC, 0x89, 0x55, 0xEE, 0xAF, 0xC1, 0x8A, 0xBB, 0xC5, 0x62, 0xA5, 0x66, 0x8B, 0xB4, 0x9B, 0x0B, 0x9C, 0x2F, 0xC7, 0x01, 0x89, 0xB2, 0x4E, 0x02, 0x73, 0x59, 0x54, 0x58, 0xCD, 0x78, 0x0F, 0xBF, 0xA5, 0xF2, 0x16, 0x12, 0x24, 0x21, 0xB8, 0x0B, 0xF7, 0x73, 0xD7, 0x36, 0xE6, 0xE1, 0x1D, 0xEB, 0xB4, 0x24, 0x77, 0xD6, 0x96, 0x68, 0xD2, 0xF9, 0x40, 0xC6, 0x60, 0xF6, 0xA2, 0xC1, 0xC9, 0xB4, 0x17, 0x95, 0x92, 0xE0 }; #elif MD_MAP == SH256 uint8_t seed1[63]; #define FUNCTION "sha-256" uint8_t result1[] = { 0x77, 0xE0, 0x5A, 0x0E, 0x7D, 0xC7, 0x8A, 0xB5, 0xD8, 0x93, 0x4D, 0x5E, 0x93, 0xE8, 0x2C, 0x06, 0xA0, 0x7C, 0x04, 0xCE, 0xE6, 0xC9, 0xC5, 0x30, 0x45, 0xEE, 0xB4, 0x85, 0x87, 0x27, 0x77, 0xCF, 0x3B, 0x3E, 0x35, 0xC4, 0x74, 0xF9, 0x76, 0xB8, 0x94, 0xBF, 0x30, 0x1A, 0x86, 0xFA, 0x65, 0x1F, 0x46, 0x39, 0x70, 0xE8, 0x9D, 0x4A, 0x05, 0x34, 0xB2, 0xEC, 0xAD, 0x29, 0xEC, 0x04, 0x4E, 0x7E, 0x5F, 0xF4, 0xBA, 0x49, 0x3C, 0x40, 0xCF, 0xFF, 0x3B, 0x01, 0xE4, 0x72, 0xC5, 0x75, 0x66, 0x8C, 0xCE, 0x38, 0x80, 0xB9, 0x29, 0x0B, 0x05, 0xBF, 0xED, 0xE5, 0xEC, 0x96, 0xED, 0x5E, 0x9B, 0x28, 0x98, 0x50, 0x8B, 0x09, 0xBC, 0x80, 0x0E, 0xEE, 0x09, 0x9A, 0x3C, 0x90, 0x60, 0x2A, 0xBD, 0x4B, 0x1D, 0x4F, 0x34, 0x3D, 0x49, 0x7C, 0x60, 0x55, 0xC8, 0x7B, 0xB9, 0x56, 0xD5, 0x3B, 0xF3, 0x51 }; uint8_t result2[] = { 0x92, 0x27, 0x55, 0x23, 0xC7, 0x0E, 0x56, 0x7B, 0xCF, 0x9B, 0x35, 0xEC, 0x50, 0xB9, 0x33, 0xF8, 0x12, 0x61, 0x6D, 0xF5, 0x86, 0xB7, 0xF7, 0x2E, 0xE1, 0xBC, 0x77, 0x35, 0xA5, 0xC2, 0x65, 0x43, 0x73, 0xCB, 0xBC, 0x72, 0x31, 0x6D, 0xFF, 0x84, 0x20, 0xA3, 0x3B, 0xF0, 0x2B, 0x97, 0xAC, 0x8D, 0x19, 0x52, 0x58, 0x3F, 0x27, 0x0A, 0xCD, 0x70, 0x05, 0xCC, 0x02, 0x7F, 0x4C, 0xF1, 0x18, 0x7E, 0x68, 0x1A, 0x46, 0xB2, 0xAA, 0x86, 0x94, 0xA0, 0xFE, 0x4D, 0xEE, 0xA7, 0x20, 0x92, 0x7A, 0x84, 0xEA, 0xAA, 0x98, 0x5E, 0x59, 0xC1, 0x9F, 0x8B, 0xE0, 0x98, 0x4D, 0x8C, 0xBE, 0xF8, 0xC6, 0x9B, 0x75, 0x41, 0x67, 0x64, 0x19, 0x46, 0xE0, 0x40, 0xEE, 0x20, 0x43, 0xE1, 0xCC, 0xB2, 0x9D, 0xCF, 0x06, 0x3C, 0x0A, 0x50, 0x83, 0x0E, 0x42, 0x8E, 0x6D, 0xCA, 0x26, 0x2E, 0xCD, 0x77, 0xC5, 0x42 }; #elif MD_MAP == SH384 #define FUNCTION "sha-384" uint8_t seed1[123]; uint8_t result1[] = { 0x04, 0xFF, 0x23, 0xAD, 0x15, 0xE7, 0x87, 0x90, 0xAD, 0xD3, 0x6B, 0x43, 0x8B, 0xBC, 0x09, 0x7C, 0x7A, 0x11, 0x74, 0x7C, 0xC2, 0xCC, 0xEE, 0xDE, 0x2C, 0x97, 0x8B, 0x23, 0xB3, 0xDC, 0x63, 0xB7, 0x32, 0xC9, 0x53, 0x06, 0x1D, 0x77, 0x64, 0x99, 0x0A, 0xBF, 0xEF, 0xC4, 0x7A, 0x58, 0x1B, 0x92, 0x1B, 0xC0, 0x42, 0x8C, 0x4F, 0x12, 0x21, 0x24, 0x60, 0xE4, 0x06, 0xA0, 0xF0, 0x65, 0x1E, 0x7F, 0x0C, 0xB9, 0xA9, 0x0A, 0xBF, 0xDB, 0x07, 0xB5, 0x25, 0x56, 0x5C, 0x74, 0xF0, 0xAA, 0x08, 0x50, 0x82, 0xF6, 0xCF, 0x21, 0x3A, 0xAF, 0xAD, 0x0C, 0x06, 0x46, 0x89, 0x50, 0x78, 0xF1, 0xE1, 0xFE, 0x4F, 0x35, 0xB8, 0x5F, 0x95, 0xDE, 0xE3, 0xE8, 0x73, 0x05, 0x49, 0x05, 0xCF, 0xD0, 0x23, 0x41, 0x65, 0x3E, 0x18, 0xF5, 0x29, 0x93, 0x0C, 0xBE, 0x14, 0xD9, 0x09, 0xF3, 0x7F, 0xEA, 0xF2, 0xC7, 0x90, 0xD2, 0x2F, 0xAE, 0x75, 0x16, 0xB4, 0x59, 0x0B, 0xE3, 0x5D, 0x53, 0xE2, 0xFE, 0x1A, 0x35, 0xAF, 0xE4, 0xB6, 0x60, 0x7C, 0xB3, 0x58, 0x58, 0x9C, 0x3B, 0x4D, 0x09, 0x4A, 0x1D, 0x81, 0xFE, 0x07, 0x17, 0xF1, 0xDF, 0x5B, 0xDD, 0xEB, 0x3E, 0x11, 0x4F, 0x13, 0x0B, 0xB7, 0x81, 0xE6, 0x6C, 0x22, 0xB5, 0xB7, 0x70, 0xE8, 0xAE, 0x11, 0x5F, 0xF3, 0x9F, 0x8A, 0xDA, 0xF6, 0x6D, 0xEE, 0xDF }; uint8_t result2[] = { 0x97, 0x99, 0x3B, 0x78, 0xF7, 0xC3, 0x1C, 0x0E, 0x87, 0x6D, 0xC9, 0x2E, 0xB7, 0xD6, 0xC4, 0x08, 0xE0, 0x9D, 0x60, 0x8A, 0xD6, 0xB9, 0x9D, 0x0E, 0xA2, 0x22, 0x9B, 0x05, 0xA5, 0x78, 0xC4, 0x26, 0x33, 0x4F, 0xCC, 0x8A, 0x1C, 0x7E, 0x67, 0x6E, 0xD2, 0xD8, 0x9A, 0x5B, 0x4C, 0xDF, 0x5B, 0x3F, 0x4A, 0xDF, 0x11, 0x93, 0x6B, 0xF1, 0x4F, 0x4E, 0x10, 0x90, 0x9D, 0xBA, 0x9C, 0x24, 0xF4, 0xFD, 0xFF, 0xDE, 0x72, 0x35, 0x1D, 0xA8, 0xE2, 0xCC, 0x3B, 0x13, 0x5A, 0x39, 0x53, 0x73, 0x89, 0x9E, 0x5F, 0x1A, 0x59, 0x55, 0xB8, 0x80, 0xCA, 0x9B, 0x9E, 0x9D, 0xD4, 0xC9, 0xCA, 0x7F, 0xA4, 0xD4, 0xF5, 0x98, 0x39, 0x46, 0x32, 0x0E, 0x36, 0xC6, 0x4E, 0xF2, 0x83, 0xCA, 0x1F, 0x65, 0xD1, 0x97, 0xCF, 0x81, 0x62, 0x4E, 0xC6, 0x77, 0x8E, 0x77, 0x0E, 0x78, 0x94, 0x9D, 0x84, 0xEF, 0x21, 0xA4, 0x5C, 0xDD, 0x62, 0xD1, 0xDB, 0x76, 0x92, 0x0D, 0x4C, 0x28, 0x36, 0xFC, 0x6A, 0xE5, 0x29, 0x9F, 0xAF, 0x13, 0x57, 0xD9, 0x70, 0x1F, 0xAD, 0x10, 0xFB, 0xD8, 0x8D, 0x1E, 0x28, 0x32, 0x23, 0x94, 0x36, 0xD7, 0x6E, 0xB2, 0x71, 0xBD, 0xC3, 0xCA, 0x04, 0x42, 0x5E, 0xC8, 0x8B, 0xC0, 0xE8, 0x9A, 0x4D, 0x5C, 0x37, 0xFF, 0xCE, 0x7C, 0x6C, 0x3A, 0xBD, 0xE9, 0xC4, 0x13, 0xAE, 0x6D, 0x3F, 0xEA }; #elif MD_MAP == SH512 #define FUNCTION "sha-512" uint8_t seed1[127]; uint8_t result1[] = { 0x17, 0x0C, 0xC7, 0x07, 0xC7, 0x1C, 0x69, 0xCE, 0x45, 0xC4, 0x3C, 0xBA, 0xFF, 0x52, 0x10, 0x14, 0x05, 0x72, 0xD4, 0x78, 0x59, 0x52, 0x1B, 0xA1, 0x31, 0x41, 0xBA, 0xDD, 0x2E, 0x5B, 0x9A, 0x7B, 0x3E, 0x80, 0x20, 0x62, 0x5C, 0xD8, 0x89, 0x3F, 0xD6, 0xA4, 0x73, 0x9C, 0x58, 0x1E, 0xD5, 0xBE, 0x7F, 0xA3, 0x14, 0x8A, 0x05, 0xD7, 0xF5, 0x4A, 0xE9, 0xEA, 0xDA, 0xE8, 0xF1, 0xA7, 0x19, 0x4D, 0xF9, 0x4B, 0x6B, 0x75, 0x5B, 0x94, 0x8E, 0x0C, 0x27, 0xE1, 0x74, 0x7F, 0x02, 0xF6, 0x63, 0xD6, 0xB5, 0x14, 0xA0, 0xF5, 0x86, 0xF9, 0x4E, 0x53, 0xD3, 0x21, 0x69, 0xE1, 0xCC, 0xC6, 0x21, 0x1A, 0xD0, 0x34, 0x81, 0x24, 0x19, 0xB6, 0xBA, 0x8F, 0x3C, 0x82, 0x93, 0x04, 0x89, 0x83, 0x93, 0xBF, 0x39, 0xE5, 0x7E, 0x2F, 0xED, 0xF7, 0x75, 0xFC, 0x6E, 0x5E, 0xB0, 0xE3, 0x07, 0xED, 0xCA, 0x0B, 0xD5, 0x15, 0xB9, 0x2B, 0x18, 0x11, 0xF5, 0xAA, 0xD0, 0x2A, 0xAC, 0x9B, 0x39, 0xDF, 0xA5, 0xB8, 0xB1, 0xA9, 0x50, 0x48, 0x7D, 0x34, 0x29, 0xB1, 0x08, 0x1D, 0x0F, 0xEC, 0x28, 0xD5, 0x76, 0x86, 0xD8, 0x5B, 0xC6, 0xB4, 0x5A, 0xB8, 0xB8, 0x4C, 0x54, 0xDD, 0x80, 0xB2, 0x82, 0x59, 0x1F, 0x55, 0x07, 0xED, 0x9B, 0x3F, 0xB1, 0xCD, 0xEE, 0xFD, 0x58, 0xAD, 0x5A, 0x98, 0x12, 0xED, 0x92, 0x9C, 0x77, 0x9B, 0x0F, 0x54, 0xBA, 0xDF, 0x2C, 0xAF, 0xBA, 0xCF, 0xAC, 0xB3, 0xEC, 0xAC, 0xC1, 0x27, 0xC7, 0x64, 0x0C, 0xBB, 0x67, 0x15, 0x4F, 0x54, 0x5A, 0x62, 0x2B, 0xE0, 0xA9, 0xB5, 0x52, 0xA2, 0x42, 0x08, 0x31, 0x3B, 0xFA, 0x49, 0x1F, 0x53, 0xAA, 0xA3, 0x07, 0x4B, 0xDC, 0x48, 0xBC, 0x5B, 0xDB, 0x3F, 0xF0, 0xE2, 0xD0, 0x5B, 0xB4, 0x77, 0xB5, 0x9F, 0x87, 0xE3, 0xA1, 0xEA, 0xB3, 0xE6 }; uint8_t result2[] = { 0xF9, 0x3C, 0xA6, 0x85, 0x55, 0x90, 0xA7, 0x7F, 0x07, 0x35, 0x40, 0x97, 0xE9, 0x0E, 0x02, 0x66, 0x48, 0xB6, 0x11, 0x5D, 0xF0, 0x08, 0xFF, 0xED, 0xBD, 0x9D, 0x98, 0x11, 0xF5, 0x4E, 0x82, 0x86, 0xEF, 0x00, 0xFD, 0xD6, 0xBA, 0x1E, 0x58, 0xDF, 0x25, 0x35, 0xE3, 0xFB, 0xDD, 0x9A, 0x9B, 0xA3, 0x75, 0x4A, 0x97, 0xF3, 0x6E, 0xE8, 0x33, 0x22, 0x15, 0x82, 0x06, 0x0A, 0x1F, 0x37, 0xFC, 0xE4, 0xEE, 0x88, 0x26, 0x63, 0x6B, 0x28, 0xEA, 0xD5, 0x89, 0x59, 0x3F, 0x4C, 0xA8, 0xB6, 0x47, 0x38, 0x8F, 0x24, 0xEB, 0x3F, 0x0A, 0x34, 0x79, 0x69, 0x68, 0xD2, 0x1B, 0xDE, 0xE6, 0xF8, 0x1F, 0xD5, 0xDF, 0x93, 0x53, 0x6F, 0x93, 0x59, 0x37, 0xB8, 0x02, 0x5E, 0xC8, 0xCB, 0xF5, 0x7D, 0xDB, 0x0C, 0x61, 0xF2, 0xE4, 0x14, 0x63, 0xCC, 0x15, 0x16, 0xD6, 0x57, 0xDA, 0x28, 0x29, 0xC6, 0xBF, 0x90, 0x48, 0x17, 0x61, 0x8F, 0x48, 0xC6, 0x0F, 0xB1, 0xCE, 0x5B, 0xFB, 0xDA, 0x0C, 0xAF, 0x45, 0x91, 0x88, 0x2A, 0x31, 0xF6, 0xEE, 0x3F, 0xE0, 0xF7, 0x87, 0x79, 0x99, 0x2A, 0x06, 0xEC, 0x60, 0xF3, 0x7F, 0xB9, 0xA8, 0xD6, 0x10, 0x8C, 0x23, 0x1F, 0x0A, 0x92, 0x77, 0x54, 0xB0, 0x59, 0x9F, 0xA4, 0xFA, 0x27, 0xA4, 0xE2, 0x5E, 0x06, 0x5E, 0xF0, 0x30, 0x85, 0xB8, 0x92, 0x97, 0x9D, 0xC0, 0xE7, 0xA1, 0x08, 0x08, 0x83, 0xCA, 0xEB, 0xFD, 0xFD, 0x36, 0x65, 0xA8, 0xF2, 0xD0, 0x61, 0xC5, 0x21, 0xF7, 0xD6, 0xE3, 0xDA, 0x2A, 0xF8, 0xB9, 0x7B, 0x6B, 0x43, 0xB6, 0xEC, 0x83, 0x1A, 0xF5, 0x15, 0x07, 0x0A, 0x83, 0xBB, 0xB9, 0xAC, 0x95, 0xED, 0x4E, 0xF4, 0x9B, 0x75, 0x6A, 0x23, 0x77, 0xA5, 0xF0, 0x83, 0x3D, 0x84, 0x7E, 0x27, 0xA8, 0x8D, 0xDB, 0x0C, 0x2C, 0xE4, 0xAD, 0x78, 0x2E, 0x7B }; #endif static int test(void) { int i, len = 2 * MD_LEN, size = (RAND_SIZE - 1) / 2, code = STS_ERR; uint8_t out[len], seed2[size], seed3[size]; for (i = 0; i < (RAND_SIZE - 1) / 2; i++) { seed1[i] = i; seed2[i] = 0x80 + i; seed3[i] = 0xC0 + i; } for (; i < sizeof(seed1); i++) { seed1[i] = 0x20 + (i - (RAND_SIZE - 1) / 2); } TEST_ONCE("hash-dbrg (" FUNCTION ") random generator is correct") { rand_clean(); rand_seed(seed1, sizeof(seed1)); rand_bytes(out, len); TEST_ASSERT(memcmp(out, result1, len) == 0, end); rand_bytes(out, len); TEST_ASSERT(memcmp(out, result1 + len, len) == 0, end); } TEST_END; TEST_ONCE("hash-dbrg (" FUNCTION ") reseeding is correct") { rand_clean(); rand_seed(seed1, sizeof(seed1)); rand_seed(seed2, sizeof(seed2)); rand_bytes(out, len); TEST_ASSERT(memcmp(out, result2, len) == 0, end); rand_seed(seed3, sizeof(seed3)); rand_bytes(out, len); TEST_ASSERT(memcmp(out, result2 + len, len) == 0, end); } TEST_END; code = STS_OK; end: return code; } #elif RAND == FIPS /* * Test vectors taken from: * - http://csrc.nist.gov/encryption/dss/Examples-1024bit.pdf * - http://www.ietf.org/rfc/rfc4186.txt */ uint8_t test1[20] = { 0xBD, 0x02, 0x9B, 0xBE, 0x7F, 0x51, 0x96, 0x0B, 0xCF, 0x9E, 0xDB, 0x2B, 0x61, 0xF0, 0x6F, 0x0F, 0xEB, 0x5A, 0x38, 0xB6 }; uint8_t test2[20] = { 0xE5, 0x76, 0xD5, 0xCA, 0x33, 0x2E, 0x99, 0x30, 0x01, 0x8B, 0xF1, 0xBA, 0xEE, 0x27, 0x63, 0xC7, 0x95, 0xB3, 0xC7, 0x12 }; uint8_t result1[40] = { 0x20, 0x70, 0xb3, 0x22, 0x3D, 0xBA, 0x37, 0x2F, 0xDE, 0x1C, 0x0F, 0xFC, 0x7B, 0x2E, 0x3B, 0x49, 0x8B, 0x26, 0x06, 0x14, 0x3C, 0x6C, 0x18, 0xBA, 0xCB, 0x0F, 0x6C, 0x55, 0xBA, 0xBB, 0x13, 0x78, 0x8E, 0x20, 0xD7, 0x37, 0xA3, 0x27, 0x51, 0x16 }; uint8_t result2[160] = { 0x53, 0x6E, 0x5E, 0xBC, 0x44, 0x65, 0x58, 0x2A, 0xA6, 0xA8, 0xEC, 0x99, 0x86, 0xEB, 0xB6, 0x20, 0x25, 0xAF, 0x19, 0x42, 0xEF, 0xCB, 0xF4, 0xBC, 0x72, 0xB3, 0x94, 0x34, 0x21, 0xF2, 0xA9, 0x74, 0x39, 0xD4, 0x5A, 0xEA, 0xF4, 0xE3, 0x06, 0x01, 0x98, 0x3E, 0x97, 0x2B, 0x6C, 0xFD, 0x46, 0xD1, 0xC3, 0x63, 0x77, 0x33, 0x65, 0x69, 0x0D, 0x09, 0xCD, 0x44, 0x97, 0x6B, 0x52, 0x5F, 0x47, 0xD3, 0xA6, 0x0A, 0x98, 0x5E, 0x95, 0x5C, 0x53, 0xB0, 0x90, 0xB2, 0xE4, 0xB7, 0x37, 0x19, 0x19, 0x6A, 0x40, 0x25, 0x42, 0x96, 0x8F, 0xD1, 0x4A, 0x88, 0x8F, 0x46, 0xB9, 0xA7, 0x88, 0x6E, 0x44, 0x88, 0x59, 0x49, 0xEA, 0xB0, 0xFF, 0xF6, 0x9D, 0x52, 0x31, 0x5C, 0x6C, 0x63, 0x4F, 0xD1, 0x4A, 0x7F, 0x0D, 0x52, 0x02, 0x3D, 0x56, 0xF7, 0x96, 0x98, 0xFA, 0x65, 0x96, 0xAB, 0xEE, 0xD4, 0xF9, 0x3F, 0xBB, 0x48, 0xEB, 0x53, 0x4D, 0x98, 0x54, 0x14, 0xCE, 0xED, 0x0D, 0x9A, 0x8E, 0xD3, 0x3C, 0x38, 0x7C, 0x9D, 0xFD, 0xAB, 0x92, 0xFF, 0xBD, 0xF2, 0x40, 0xFC, 0xEC, 0xF6, 0x5A, 0x2C, 0x93, 0xB9, }; static int test(void) { int code = STS_ERR; uint8_t out[160]; TEST_ONCE("fips 186-2 (cn1) random generator is correct") { rand_seed(test1, 20); rand_bytes(out, 40); TEST_ASSERT(memcmp(out, result1, 40) == 0, end); rand_seed(test2, 20); rand_bytes(out, 160); TEST_ASSERT(memcmp(out, result2, 160) == 0, end); } TEST_END; code = STS_OK; end: return code; } #elif RAND == UDEV static int test(void) { uint8_t out[20], digit; TEST_ONCE("reading from /dev/urandom is correct") { digit = 0; memset(out, 0, sizeof(out)); rand_bytes(out, sizeof(out)); for (int j = 0; j < sizeof(20); j++) { digit ^= out[j]; } TEST_ASSERT(digit != 0, end); } TEST_END; end: return STS_OK; } #elif RAND == RDRND static int test(void) { uint8_t out[64]; int len = sizeof(out) / 2, code = STS_ERR; TEST_ONCE("rdrand hardware generator is non-trivial") { memset(out, 0, 2 * len); rand_bytes(out, len); /* This fails with negligible probability. */ TEST_ASSERT(memcmp(out, out + len, len) != 0, end); } TEST_END; code = STS_OK; end: return code; } #elif RAND == CALL #include <unistd.h> #include <sys/stat.h> #include <fcntl.h> static void test_bytes(uint8_t *buf, int size, void *args) { int c, l, fd = *(int *)args; if (fd == -1) { THROW(ERR_NO_FILE); } l = 0; do { c = read(fd, buf + l, size - l); l += c; if (c == -1) { THROW(ERR_NO_READ); } } while (l < size); } static int test(void) { uint8_t out[20], digit; int fd = open("/dev/urandom", O_RDONLY); TEST_ONCE("callback to reading /dev/urandom is correct") { digit = 0; memset(out, 0, sizeof(out)); rand_bytes(out, sizeof(out)); for (int j = 0; j < sizeof(20); j++) { digit ^= out[j]; } TEST_ASSERT(digit != 0, end); rand_seed(&test_bytes, (void *)&fd); rand_bytes(out, sizeof(out)); for (int j = 0; j < sizeof(20); j++) { digit ^= out[j]; } TEST_ASSERT(digit != 0, end); } TEST_END; end: close(fd); return STS_OK; } #endif int main(void) { if (core_init() != STS_OK) { core_clean(); return 1; } util_banner("Tests for the RAND module:\n", 0); if (test() != STS_OK) { core_clean(); return 1; } util_banner("All tests have passed.\n", 0); core_clean(); return 0; }
lgpl-2.1
vladimir-kazakov/gpac
src/compositor/texturing.c
3
9401
/* * GPAC - Multimedia Framework C SDK * * Authors: Jean Le Feuvre * Copyright (c) Telecom ParisTech 2000-2012 * All rights reserved * * This file is part of GPAC / Scene Compositor sub-project * * GPAC is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * GPAC is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. * */ #include "texturing.h" #include <gpac/internal/terminal_dev.h> #include <gpac/options.h> #include "nodes_stacks.h" static void update_texture_void(GF_TextureHandler *txh) { } GF_EXPORT void gf_sc_texture_setup(GF_TextureHandler *txh, GF_Compositor *compositor, GF_Node *owner) { memset(txh, 0, sizeof(GF_TextureHandler)); txh->owner = owner; txh->compositor = compositor; /*insert texture in reverse order, so that textures in sub documents/scenes are updated before parent ones*/ if (gf_list_find(compositor->textures, txh)<0) { gf_list_insert(compositor->textures, txh, 0); compositor->texture_inserted = GF_TRUE; } if (!txh->update_texture_fcnt) txh->update_texture_fcnt = update_texture_void; } GF_EXPORT void gf_sc_texture_destroy(GF_TextureHandler *txh) { GF_Compositor *compositor = txh->compositor; Bool lock = gf_mx_try_lock(compositor->mx); gf_sc_texture_release(txh); if (txh->is_open) gf_sc_texture_stop(txh); gf_list_del_item(txh->compositor->textures, txh); if (lock) gf_mx_v(compositor->mx); } GF_EXPORT Bool gf_sc_texture_check_url_change(GF_TextureHandler *txh, MFURL *url) { if (!txh->stream) return url->count; return gf_mo_url_changed(txh->stream, url); } GF_EXPORT GF_Err gf_sc_texture_open(GF_TextureHandler *txh, MFURL *url, Bool lock_scene_timeline) { if (txh->is_open) return GF_BAD_PARAM; /*if existing texture in cache destroy it - we don't destroy it on stop to handle MovieTexture*/ if (txh->tx_io) gf_sc_texture_release(txh); /*get media object*/ txh->stream = gf_mo_register(txh->owner, url, lock_scene_timeline, 0); /*bad/Empty URL*/ if (!txh->stream) return GF_NOT_SUPPORTED; return GF_OK; } GF_EXPORT GF_Err gf_sc_texture_play_from_to(GF_TextureHandler *txh, MFURL *url, Double start_offset, Double end_offset, Bool can_loop, Bool lock_scene_timeline) { if (!txh->stream) { GF_Err e; e = gf_sc_texture_open(txh, url, lock_scene_timeline); if (e != GF_OK) return e; } /*request play*/ gf_mo_play(txh->stream, start_offset, end_offset, can_loop); txh->last_frame_time = (u32) (-1); //gf_sc_invalidate(txh->compositor, NULL); txh->is_open = 1; /*request play*/ txh->raw_memory = gf_mo_is_raw_memory(txh->stream); return GF_OK; } GF_EXPORT GF_Err gf_sc_texture_play(GF_TextureHandler *txh, MFURL *url) { Double offset = 0; Bool loop = 0; if (txh->compositor->term && (txh->compositor->term->play_state!=GF_STATE_PLAYING)) { offset = gf_node_get_scene_time(txh->owner); loop = /*gf_mo_get_loop(gf_mo_register(txh->owner, url, 0, 0), 0)*/ 1; } return gf_sc_texture_play_from_to(txh, url, offset, -1, loop, 0); } GF_EXPORT void gf_sc_texture_stop(GF_TextureHandler *txh) { if (!txh->is_open) return; /*release texture WITHOUT droping frame*/ if (txh->needs_release) { gf_mo_release_data(txh->stream, 0xFFFFFFFF, -1); txh->needs_release = 0; } gf_sc_invalidate(txh->compositor, NULL); if (gf_mo_stop(txh->stream)) { txh->data = NULL; } txh->is_open = 0; /*and deassociate object*/ gf_mo_unregister(txh->owner, txh->stream); txh->stream = NULL; } GF_EXPORT void gf_sc_texture_restart(GF_TextureHandler *txh) { if (!txh->is_open) return; gf_sc_texture_release_stream(txh); txh->stream_finished = 0; gf_mo_restart(txh->stream); } static void setup_texture_object(GF_TextureHandler *txh, Bool private_media) { if (!txh->tx_io) { gf_sc_texture_allocate(txh); if (!txh->tx_io) return; gf_mo_get_visual_info(txh->stream, &txh->width, &txh->height, &txh->stride, &txh->pixel_ar, &txh->pixelformat, &txh->is_flipped); if (private_media) { txh->transparent = 1; txh->pixelformat = GF_PIXEL_ARGB; txh->flags |= GF_SR_TEXTURE_PRIVATE_MEDIA; } else { txh->transparent = 0; switch (txh->pixelformat) { case GF_PIXEL_ALPHAGREY: case GF_PIXEL_ARGB: case GF_PIXEL_RGBA: case GF_PIXEL_YUVA: case GF_PIXEL_RGBDS: txh->transparent = 1; break; } } gf_mo_set_flag(txh->stream, GF_MO_IS_INIT, GF_TRUE); } } GF_EXPORT void gf_sc_texture_update_frame(GF_TextureHandler *txh, Bool disable_resync) { Bool needs_reload = 0; u32 size, ts; s32 ms_until_pres, ms_until_next; /*already refreshed*/ if ((txh->stream_finished && txh->tx_io) || txh->needs_refresh) return; if (!txh->stream) { txh->data = NULL; return; } /*should never happen!!*/ if (txh->needs_release) gf_mo_release_data(txh->stream, 0xFFFFFFFF, 0); /*check init flag*/ if (!(gf_mo_get_flags(txh->stream) & GF_MO_IS_INIT)) { needs_reload = 1; txh->data = NULL; if (txh->tx_io) { gf_sc_texture_release(txh); } } txh->data = gf_mo_fetch_data(txh->stream, disable_resync ? GF_MO_FETCH : GF_MO_FETCH_RESYNC, &txh->stream_finished, &ts, &size, &ms_until_pres, &ms_until_next); if (!(gf_mo_get_flags(txh->stream) & GF_MO_IS_INIT)) { needs_reload = 1; } else if (size && txh->size && (size != txh->size)) { needs_reload = 1; } if (needs_reload) { /*if we had a texture this means the object has changed - delete texture and resetup. Do not skip texture update as this may lead to an empty rendering pass (blank frame for this object), especially in DASH*/ if (txh->tx_io) { gf_sc_texture_release(txh); txh->needs_refresh = 1; } if (gf_mo_is_private_media(txh->stream)) { setup_texture_object(txh, 1); gf_node_dirty_set(txh->owner, 0, 0); } } /*if no frame or muted don't draw*/ if (!txh->data || !size) { GF_LOG(GF_LOG_INFO, GF_LOG_COMPOSE, ("[Visual Texture] No output frame available \n")); /*TODO - check if this is needed */ if (txh->flags & GF_SR_TEXTURE_PRIVATE_MEDIA) { //txh->needs_refresh = 1; gf_sc_invalidate(txh->compositor, NULL); } return; } if (txh->compositor->frame_delay > ms_until_pres) txh->compositor->frame_delay = ms_until_pres; /*if setup and same frame return*/ if (txh->tx_io && (txh->stream_finished || (txh->last_frame_time==ts)) ) { gf_mo_release_data(txh->stream, 0xFFFFFFFF, 0); txh->needs_release = 0; if (!txh->stream_finished) { GF_LOG(GF_LOG_DEBUG, GF_LOG_COMPOSE, ("[Visual Texture] Same frame fetched (TS %d)\n", ts)); if (txh->compositor->ms_until_next_frame > ms_until_next) txh->compositor->ms_until_next_frame = ms_until_next; } return; } txh->stream_finished = 0; txh->needs_release = 1; txh->last_frame_time = ts; txh->size = size; if (txh->raw_memory) { gf_mo_get_raw_image_planes(txh->stream, (u8 **) &txh->data, (u8 **) &txh->pU, (u8 **) &txh->pV); } if (gf_mo_is_muted(txh->stream)) return; if (txh->nb_frames) { s32 push_delay = txh->upload_time / txh->nb_frames; if (push_delay > ms_until_pres) ms_until_pres = 0; else ms_until_pres -= push_delay; } if (txh->compositor->ms_until_next_frame > ms_until_next) txh->compositor->ms_until_next_frame = ms_until_next; if (!txh->tx_io) { setup_texture_object(txh, 0); } /*try to push texture on graphics but don't complain if failure*/ gf_sc_texture_set_data(txh); txh->needs_refresh = 1; gf_sc_invalidate(txh->compositor, NULL); } GF_EXPORT void gf_sc_texture_release_stream(GF_TextureHandler *txh) { if (txh->needs_release) { assert(txh->stream); gf_mo_release_data(txh->stream, 0xFFFFFFFF, 0); txh->needs_release = 0; } txh->needs_refresh = 0; } GF_EXPORT GF_TextureHandler *gf_sc_texture_get_handler(GF_Node *n) { if (!n) return NULL; switch (gf_node_get_tag(n)) { #ifndef GPAC_DISABLE_VRML case TAG_MPEG4_ImageTexture: case TAG_MPEG4_CacheTexture: return it_get_texture(n); case TAG_MPEG4_MovieTexture: return mt_get_texture(n); case TAG_MPEG4_PixelTexture: return pt_get_texture(n); case TAG_MPEG4_CompositeTexture2D: case TAG_MPEG4_CompositeTexture3D: return compositor_get_composite_texture(n); case TAG_MPEG4_LinearGradient: case TAG_MPEG4_RadialGradient: return compositor_mpeg4_get_gradient_texture(n); case TAG_MPEG4_MatteTexture: { GF_TextureHandler *hdl = gf_sc_texture_get_handler( ((M_MatteTexture*)n)->surfaceB ); if (hdl) hdl->matteTexture = n; return hdl; } #endif /*GPAC_DISABLE_VRML*/ #ifndef GPAC_DISABLE_X3D case TAG_X3D_ImageTexture: return it_get_texture(n); case TAG_X3D_MovieTexture: return mt_get_texture(n); case TAG_X3D_PixelTexture: return pt_get_texture(n); #endif #ifndef GPAC_DISABLE_SVG case TAG_SVG_linearGradient: case TAG_SVG_radialGradient: return compositor_svg_get_gradient_texture(n); case TAG_SVG_image: case TAG_SVG_video: return compositor_svg_get_image_texture(n); #endif default: return NULL; } }
lgpl-2.1
Distrotech/cogl
cogl/cogl-boxed-value.c
3
9696
/* * Cogl * * An object oriented GL/GLES Abstraction/Utility Layer * * Copyright (C) 2011 Intel Corporation. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. * * */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <string.h> #include "cogl-boxed-value.h" #include "cogl-context-private.h" #include "cogl-util-gl-private.h" CoglBool _cogl_boxed_value_equal (const CoglBoxedValue *bva, const CoglBoxedValue *bvb) { const void *pa, *pb; if (bva->type != bvb->type) return FALSE; switch (bva->type) { case COGL_BOXED_NONE: return TRUE; case COGL_BOXED_INT: if (bva->size != bvb->size || bva->count != bvb->count) return FALSE; if (bva->count == 1) { pa = bva->v.int_value; pb = bvb->v.int_value; } else { pa = bva->v.int_array; pb = bvb->v.int_array; } return !memcmp (pa, pb, sizeof (int) * bva->size * bva->count); case COGL_BOXED_FLOAT: if (bva->size != bvb->size || bva->count != bvb->count) return FALSE; if (bva->count == 1) { pa = bva->v.float_value; pb = bvb->v.float_value; } else { pa = bva->v.float_array; pb = bvb->v.float_array; } return !memcmp (pa, pb, sizeof (float) * bva->size * bva->count); case COGL_BOXED_MATRIX: if (bva->size != bvb->size || bva->count != bvb->count) return FALSE; if (bva->count == 1) { pa = bva->v.matrix; pb = bvb->v.matrix; } else { pa = bva->v.array; pb = bvb->v.array; } return !memcmp (pa, pb, sizeof (float) * bva->size * bva->size * bva->count); } g_warn_if_reached (); return FALSE; } static void _cogl_boxed_value_tranpose (float *dst, int size, const float *src) { int y, x; /* If the value is transposed we'll just transpose it now as it * is copied into the boxed value instead of passing TRUE to * glUniformMatrix because that is not supported on GLES and it * doesn't seem like the GL driver would be able to do anything * much smarter than this anyway */ for (y = 0; y < size; y++) for (x = 0; x < size; x++) *(dst++) = src[y + x * size]; } static void _cogl_boxed_value_set_x (CoglBoxedValue *bv, int size, int count, CoglBoxedType type, size_t value_size, const void *value, CoglBool transpose) { if (count == 1) { if (bv->count > 1) g_free (bv->v.array); if (transpose) _cogl_boxed_value_tranpose (bv->v.float_value, size, value); else memcpy (bv->v.float_value, value, value_size); } else { if (bv->count > 1) { if (bv->count != count || bv->size != size || bv->type != type) { g_free (bv->v.array); bv->v.array = g_malloc (count * value_size); } } else bv->v.array = g_malloc (count * value_size); if (transpose) { int value_num; for (value_num = 0; value_num < count; value_num++) _cogl_boxed_value_tranpose (bv->v.float_array + value_num * size * size, size, (const float *) value + value_num * size * size); } else memcpy (bv->v.array, value, count * value_size); } bv->type = type; bv->size = size; bv->count = count; } void _cogl_boxed_value_set_1f (CoglBoxedValue *bv, float value) { _cogl_boxed_value_set_x (bv, 1, 1, COGL_BOXED_FLOAT, sizeof (float), &value, FALSE); } void _cogl_boxed_value_set_1i (CoglBoxedValue *bv, int value) { _cogl_boxed_value_set_x (bv, 1, 1, COGL_BOXED_INT, sizeof (int), &value, FALSE); } void _cogl_boxed_value_set_float (CoglBoxedValue *bv, int n_components, int count, const float *value) { _cogl_boxed_value_set_x (bv, n_components, count, COGL_BOXED_FLOAT, sizeof (float) * n_components, value, FALSE); } void _cogl_boxed_value_set_int (CoglBoxedValue *bv, int n_components, int count, const int *value) { _cogl_boxed_value_set_x (bv, n_components, count, COGL_BOXED_INT, sizeof (int) * n_components, value, FALSE); } void _cogl_boxed_value_set_matrix (CoglBoxedValue *bv, int dimensions, int count, CoglBool transpose, const float *value) { _cogl_boxed_value_set_x (bv, dimensions, count, COGL_BOXED_MATRIX, sizeof (float) * dimensions * dimensions, value, transpose); } void _cogl_boxed_value_copy (CoglBoxedValue *dst, const CoglBoxedValue *src) { *dst = *src; if (src->count > 1) { switch (src->type) { case COGL_BOXED_NONE: break; case COGL_BOXED_INT: dst->v.int_array = g_memdup (src->v.int_array, src->size * src->count * sizeof (int)); break; case COGL_BOXED_FLOAT: dst->v.float_array = g_memdup (src->v.float_array, src->size * src->count * sizeof (float)); break; case COGL_BOXED_MATRIX: dst->v.float_array = g_memdup (src->v.float_array, src->size * src->size * src->count * sizeof (float)); break; } } } void _cogl_boxed_value_destroy (CoglBoxedValue *bv) { if (bv->count > 1) g_free (bv->v.array); } void _cogl_boxed_value_set_uniform (CoglContext *ctx, GLint location, const CoglBoxedValue *value) { switch (value->type) { case COGL_BOXED_NONE: break; case COGL_BOXED_INT: { const int *ptr; if (value->count == 1) ptr = value->v.int_value; else ptr = value->v.int_array; switch (value->size) { case 1: GE( ctx, glUniform1iv (location, value->count, ptr) ); break; case 2: GE( ctx, glUniform2iv (location, value->count, ptr) ); break; case 3: GE( ctx, glUniform3iv (location, value->count, ptr) ); break; case 4: GE( ctx, glUniform4iv (location, value->count, ptr) ); break; } } break; case COGL_BOXED_FLOAT: { const float *ptr; if (value->count == 1) ptr = value->v.float_value; else ptr = value->v.float_array; switch (value->size) { case 1: GE( ctx, glUniform1fv (location, value->count, ptr) ); break; case 2: GE( ctx, glUniform2fv (location, value->count, ptr) ); break; case 3: GE( ctx, glUniform3fv (location, value->count, ptr) ); break; case 4: GE( ctx, glUniform4fv (location, value->count, ptr) ); break; } } break; case COGL_BOXED_MATRIX: { const float *ptr; if (value->count == 1) ptr = value->v.matrix; else ptr = value->v.float_array; switch (value->size) { case 2: GE( ctx, glUniformMatrix2fv (location, value->count, FALSE, ptr) ); break; case 3: GE( ctx, glUniformMatrix3fv (location, value->count, FALSE, ptr) ); break; case 4: GE( ctx, glUniformMatrix4fv (location, value->count, FALSE, ptr) ); break; } } break; } }
lgpl-2.1
calincru/marble
src/lib/marble/MarbleWidgetInputHandler.cpp
4
4454
// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2006-2007 Torsten Rahn <tackat@kde.org> // Copyright 2007 Inge Wallin <ingwa@kde.org> // Copyright 2014 Adam Dabrowski <adamdbrw@gmail.com> // #include "MarbleWidgetInputHandler.h" #include <QRubberBand> #include <QToolTip> #include <QTimer> #include "MarbleGlobal.h" #include "MarbleDebug.h" #include "MarbleWidget.h" #include "AbstractDataPluginItem.h" #include "MarbleWidgetPopupMenu.h" #include "PopupLayer.h" #include "RenderPlugin.h" #include "RoutingLayer.h" namespace Marble { class MarbleWidgetInputHandlerPrivate { class MarbleWidgetSelectionRubber : public AbstractSelectionRubber { public: MarbleWidgetSelectionRubber(MarbleWidget *widget) : m_rubberBand(QRubberBand::Rectangle, widget) { m_rubberBand.hide(); } void show() { m_rubberBand.show(); } void hide() { m_rubberBand.hide(); } bool isVisible() const { return m_rubberBand.isVisible(); } const QRect &geometry() const { return m_rubberBand.geometry(); } void setGeometry(const QRect &geometry) { m_rubberBand.setGeometry(geometry); } private: QRubberBand m_rubberBand; }; public: MarbleWidgetInputHandlerPrivate(MarbleWidgetInputHandler *handler, MarbleWidget *widget) : m_inputHandler(handler) ,m_marbleWidget(widget) ,m_selectionRubber(widget) { foreach(RenderPlugin *renderPlugin, widget->renderPlugins()) { if(renderPlugin->isInitialized()) { installPluginEventFilter(renderPlugin); } } m_marbleWidget->grabGesture(Qt::PinchGesture); } void setCursor(const QCursor &cursor) { m_marbleWidget->setCursor(cursor); } bool layersEventFilter(QObject *o, QEvent *e) { //FIXME - this should go up in hierarchy to MarbleInputHandler if (m_marbleWidget->popupLayer()->eventFilter(o, e)) { return true; } if (m_marbleWidget->routingLayer()->eventFilter(o, e)) { return true; } return false; } void installPluginEventFilter(RenderPlugin *renderPlugin) { m_marbleWidget->installEventFilter(renderPlugin); } MarbleWidgetInputHandler *m_inputHandler; MarbleWidget *m_marbleWidget; MarbleWidgetSelectionRubber m_selectionRubber; }; void MarbleWidgetInputHandler::setCursor(const QCursor &cursor) { d->setCursor(cursor); } AbstractSelectionRubber *MarbleWidgetInputHandler::selectionRubber() { return &d->m_selectionRubber; } bool MarbleWidgetInputHandler::layersEventFilter(QObject *o, QEvent *e) { return d->layersEventFilter(o, e); } void MarbleWidgetInputHandler::installPluginEventFilter(RenderPlugin *renderPlugin) { d->installPluginEventFilter(renderPlugin); } MarbleWidgetInputHandler::MarbleWidgetInputHandler(MarbleAbstractPresenter *marblePresenter, MarbleWidget *widget) : MarbleDefaultInputHandler(marblePresenter) ,d(new MarbleWidgetInputHandlerPrivate(this, widget)) { } //FIXME - these should be moved to superclass and popupMenu should be abstracted in MarbleAbstractPresenter void MarbleWidgetInputHandler::showLmbMenu(int x, int y) { if (isMouseButtonPopupEnabled(Qt::LeftButton)) { d->m_marbleWidget->popupMenu()->showLmbMenu(x, y); toolTipTimer()->stop(); } } void MarbleWidgetInputHandler::showRmbMenu(int x, int y) { if (isMouseButtonPopupEnabled(Qt::RightButton)) { d->m_marbleWidget->popupMenu()->showRmbMenu(x, y); } } void MarbleWidgetInputHandler::openItemToolTip() { if (!lastToolTipItem().isNull()) { QToolTip::showText(d->m_marbleWidget->mapToGlobal(toolTipPosition()), lastToolTipItem()->toolTip(), d->m_marbleWidget, lastToolTipItem()->containsRect(toolTipPosition()).toRect()); } } } #include "MarbleWidgetInputHandler.moc"
lgpl-2.1
take-cheeze/pthreads-emb
tests/mutex7e.c
4
3410
/* * mutex7e.c * * * -------------------------------------------------------------------------- * * Pthreads-embedded (PTE) - POSIX Threads Library for embedded systems * Copyright(C) 2008 Jason Schmidlapp * * Contact Email: jschmidlapp@users.sourceforge.net * * * Based upon Pthreads-win32 - POSIX Threads Library for Win32 * Copyright(C) 1998 John E. Bossom * Copyright(C) 1999,2005 Pthreads-win32 contributors * * Contact Email: rpj@callisto.canberra.edu.au * * The original list of contributors to the Pthreads-win32 project * is contained in the file CONTRIBUTORS.ptw32 included with the * source code distribution. The list can also be seen at the * following World Wide Web location: * http://sources.redhat.com/pthreads-win32/contributors.html * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library in the file COPYING.LIB; * if not, write to the Free Software Foundation, Inc., * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA * * -------------------------------------------------------------------------- * * Tests PTHREAD_MUTEX_ERRORCHECK mutex type. * Thread locks and then trylocks mutex (attempted recursive lock). * Trylock should fail with an EBUSY error. * The second unlock attempt should fail with an EPERM error. * * Depends on API functions: * pthread_create() * pthread_join() * pthread_mutexattr_init() * pthread_mutexattr_destroy() * pthread_mutexattr_settype() * pthread_mutexattr_gettype() * pthread_mutex_init() * pthread_mutex_destroy() * pthread_mutex_lock() * pthread_mutex_unlock() */ #include <stdio.h> #include <stdlib.h> #include "test.h" static int lockCount = 0; static pthread_mutex_t mutex; static pthread_mutexattr_t mxAttr; static void * locker(void * arg) { assert(pthread_mutex_lock(&mutex) == 0); lockCount++; assert(pthread_mutex_trylock(&mutex) == EBUSY); lockCount++; assert(pthread_mutex_unlock(&mutex) == 0); assert(pthread_mutex_unlock(&mutex) == EPERM); return (void *) 555; } int pthread_test_mutex7e() { pthread_t t; int result = 0; int mxType = -1; lockCount = 0; assert(pthread_mutexattr_init(&mxAttr) == 0); assert(pthread_mutexattr_settype(&mxAttr, PTHREAD_MUTEX_ERRORCHECK) == 0); assert(pthread_mutexattr_gettype(&mxAttr, &mxType) == 0); assert(mxType == PTHREAD_MUTEX_ERRORCHECK); assert(pthread_mutex_init(&mutex, &mxAttr) == 0); assert(pthread_create(&t, NULL, locker, NULL) == 0); assert(pthread_join(t, (void **) &result) == 0); assert(result == 555); assert(lockCount == 2); assert(pthread_mutex_destroy(&mutex) == 0); assert(pthread_mutexattr_destroy(&mxAttr) == 0); /* Never reached */ return 0; }
lgpl-2.1
mangokingTW/libchewing
src/chewingutil.c
4
50121
/** * chewingutil.c * * Copyright (c) 1999, 2000, 2001 * Lu-chuan Kung and Kang-pen Chen. * All rights reserved. * * Copyright (c) 2004-2006, 2008, 2010-2014 * libchewing Core Team. See ChangeLog for details. * * See the file "COPYING" for information on usage and redistribution * of this file. */ /* This file is encoded in UTF-8 */ #ifdef HAVE_CONFIG_H # include <config.h> #endif #include <ctype.h> #include <string.h> #include <assert.h> #include <stdlib.h> #include <stdio.h> #include "chewing-utf8-util.h" #include "global.h" #include "global-private.h" #include "chewingutil.h" #include "bopomofo-private.h" #include "choice-private.h" #include "tree-private.h" #include "userphrase-private.h" #include "private.h" #ifdef HAVE_ASPRINTF /* asprintf is provided by GNU extensions and *BSD */ # ifndef _GNU_SOURCE # define _GNU_SOURCE # endif # include <stdio.h> #else # include "plat_path.h" #endif extern const char *const zhuin_tab[]; static void MakePreferInterval(ChewingData *pgdata); static void ShiftInterval(ChewingOutput *pgo, ChewingData *pgdata); static int ChewingKillSelectIntervalAcross(int cursor, ChewingData *pgdata); static int FindSymbolKey(const char *symbol); /* Note: Keep synchronize with `FindEasySymbolIndex`! */ static const char G_EASY_SYMBOL_KEY[EASY_SYMBOL_KEY_TAB_LEN] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' }; static const char NO_SYM_KEY = '\t'; /* * FindEasySymbolIndex(ch) = char ch's index in G_EASY_SYMBOL_KEY * Just return -1 if not found. */ static int FindEasySymbolIndex(char ch) { /** * '0' => 0, ..., '9' => 9 * 'A' => 10, 'B' => 11, ... 'Z' => 35 */ if (isdigit(ch)) { return ch - '0'; } else if (isupper(ch)) { return ch - 'A' + 10; } else { return -1; } } void SetUpdatePhraseMsg(ChewingData *pgdata, const char *addWordSeq, int len, int state) { if (state == USER_UPDATE_INSERT) { /* 加入: */ snprintf(pgdata->showMsg, sizeof(pgdata->showMsg), "\xE5\x8A\xA0\xE5\x85\xA5\xEF\xBC\x9A%s", addWordSeq); } else { /* 已有: */ snprintf(pgdata->showMsg, sizeof(pgdata->showMsg), "\xE5\xB7\xB2\xE6\x9C\x89\xEF\xBC\x9A%s", addWordSeq); } pgdata->showMsgLen = AUX_PREFIX_LEN + len; } int NoSymbolBetween(ChewingData *pgdata, int begin, int end) { int i; for (i = begin; i < end; ++i) { if (pgdata->preeditBuf[i].category == CHEWING_SYMBOL) { return 0; } } return 1; } int ChewingIsEntering(ChewingData *pgdata) { if (pgdata->choiceInfo.isSymbol != WORD_CHOICE) return 1; return (pgdata->chiSymbolBufLen != 0 || BopomofoIsEntering(&(pgdata->bopomofoData))); } int HaninSymbolInput(ChewingData *pgdata) { unsigned int i; ChoiceInfo *pci = &(pgdata->choiceInfo); AvailInfo *pai = &(pgdata->availInfo); /* No available symbol table */ if (!pgdata->static_data.symbol_table) return BOPOMOFO_ABSORB; pci->nTotalChoice = 0; for (i = 0; i < pgdata->static_data.n_symbol_entry; i++) { strcpy(pci->totalChoiceStr[pci->nTotalChoice], pgdata->static_data.symbol_table[i]->category); pci->nTotalChoice++; } pai->avail[0].len = 1; pai->avail[0].id = NULL; pai->nAvail = 1; pai->currentAvail = 0; pci->nChoicePerPage = pgdata->config.candPerPage; assert(pci->nTotalChoice > 0); pci->nPage = CEIL_DIV(pci->nTotalChoice, pci->nChoicePerPage); pci->pageNo = 0; pci->isSymbol = SYMBOL_CATEGORY_CHOICE; return BOPOMOFO_ABSORB; } static int _Inner_InternalSpecialSymbol(int key, ChewingData *pgdata, char symkey, const char *const chibuf) { int kbtype; PreeditBuf *buf; if (key == symkey && NULL != chibuf) { assert(pgdata->chiSymbolBufLen >= pgdata->chiSymbolCursor); buf = &pgdata->preeditBuf[pgdata->chiSymbolCursor]; memmove(&pgdata->preeditBuf[pgdata->chiSymbolCursor + 1], &pgdata->preeditBuf[pgdata->chiSymbolCursor], sizeof(pgdata->preeditBuf[0]) * (pgdata->chiSymbolBufLen - pgdata->chiSymbolCursor)); strncpy(buf->char_, chibuf, sizeof(buf->char_) - 1); buf->category = CHEWING_SYMBOL; /* Save Symbol Key */ memmove(&(pgdata->symbolKeyBuf[pgdata->chiSymbolCursor + 1]), &(pgdata->symbolKeyBuf[pgdata->chiSymbolCursor]), sizeof(pgdata->symbolKeyBuf[0]) * (pgdata->chiSymbolBufLen - pgdata->chiSymbolCursor)); pgdata->symbolKeyBuf[pgdata->chiSymbolCursor] = key; pgdata->bUserArrCnnct[PhoneSeqCursor(pgdata)] = 0; pgdata->chiSymbolCursor++; pgdata->chiSymbolBufLen++; /* reset Bopomofo data */ /* Don't forget the kbtype */ kbtype = pgdata->bopomofoData.kbtype; memset(&(pgdata->bopomofoData), 0, sizeof(BopomofoData)); pgdata->bopomofoData.kbtype = kbtype; return 1; } return 0; } static int InternalSpecialSymbol(int key, ChewingData *pgdata, int nSpecial, const char keybuf[], const char *const chibuf[]) { int i, rtn = BOPOMOFO_IGNORE; /* very strange and difficult to understand */ for (i = 0; i < nSpecial; i++) { if (1 == _Inner_InternalSpecialSymbol(key, pgdata, keybuf[i], chibuf[i])) { rtn = BOPOMOFO_ABSORB; break; } } return rtn; } int SpecialSymbolInput(int key, ChewingData *pgdata) { static const char keybuf[] = { '[', ']', '{', '}', '\'', '<', ':', '\"', '>', '~', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '+', '=', '\\', '|', '?', ',', '.', ';' }; static const char *const chibuf[] = { "\xE3\x80\x8C", "\xE3\x80\x8D", "\xE3\x80\x8E", "\xE3\x80\x8F", /* "「", "」", "『", "』" */ "\xE3\x80\x81", "\xEF\xBC\x8C", "\xEF\xBC\x9A", "\xEF\xBC\x9B", /* "、", ",", ":", ";" */ "\xE3\x80\x82", "\xEF\xBD\x9E", "\xEF\xBC\x81", "\xEF\xBC\xA0", /* "。", "~", "!", "@" */ "\xEF\xBC\x83", "\xEF\xBC\x84", "\xEF\xBC\x85", "\xEF\xB8\xBF", /* "#", "$", "%", "︿" */ "\xEF\xBC\x86", "\xEF\xBC\x8A", "\xEF\xBC\x88", "\xEF\xBC\x89", /* "&", "*", "(", ")" */ "\xE2\x80\x94", "\xEF\xBC\x8B", "\xEF\xBC\x9D", "\xEF\xBC\xBC", /* "—", "+", "=", "\" */ "\xEF\xBD\x9C", "\xEF\xBC\x9F", "\xEF\xBC\x8C", "\xE3\x80\x82", /* "|", "?", ",", "。" */ "\xEF\xBC\x9B" /* ";" */ }; STATIC_ASSERT(ARRAY_SIZE(keybuf) == ARRAY_SIZE(chibuf)); return InternalSpecialSymbol(key, pgdata, ARRAY_SIZE(keybuf), keybuf, chibuf); } int FullShapeSymbolInput(int key, ChewingData *pgdata) { int rtn; static char keybuf[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', ' ', '\"', '\'', '/', '<', '>', '`', '[', ']', '{', '}', '+', '-' }; static const char *chibuf[] = { "\xEF\xBC\x90", "\xEF\xBC\x91", "\xEF\xBC\x92", "\xEF\xBC\x93", /* "0","1","2","3" */ "\xEF\xBC\x94", "\xEF\xBC\x95", "\xEF\xBC\x96", "\xEF\xBC\x97", /* "4","5","6","7" */ "\xEF\xBC\x98", "\xEF\xBC\x99", "\xEF\xBD\x81", "\xEF\xBD\x82", /* "8","9","a","b" */ "\xEF\xBD\x83", "\xEF\xBD\x84", "\xEF\xBD\x85", "\xEF\xBD\x86", /* "c","d","e","f" */ "\xEF\xBD\x87", "\xEF\xBD\x88", "\xEF\xBD\x89", "\xEF\xBD\x8A", /* "g","h","i","j" */ "\xEF\xBD\x8B", "\xEF\xBD\x8C", "\xEF\xBD\x8D", "\xEF\xBD\x8E", /* "k","l","m","n" */ "\xEF\xBD\x8F", "\xEF\xBD\x90", "\xEF\xBD\x91", "\xEF\xBD\x92", /* "o","p","q","r" */ "\xEF\xBD\x93", "\xEF\xBD\x94", "\xEF\xBD\x95", "\xEF\xBD\x96", /* "s","t","u","v" */ "\xEF\xBD\x97", "\xEF\xBD\x98", "\xEF\xBD\x99", "\xEF\xBD\x9A", /* "w","x","y","z" */ "\xEF\xBC\xA1", "\xEF\xBC\xA2", "\xEF\xBC\xA3", "\xEF\xBC\xA4", /* "A","B","C","D" */ "\xEF\xBC\xA5", "\xEF\xBC\xA6", "\xEF\xBC\xA7", "\xEF\xBC\xA8", /* "E","F","G","H" */ "\xEF\xBC\xA9", "\xEF\xBC\xAA", "\xEF\xBC\xAB", "\xEF\xBC\xAC", /* "I","J","K","L" */ "\xEF\xBC\xAD", "\xEF\xBC\xAE", "\xEF\xBC\xAF", "\xEF\xBC\xB0", /* "M","N","O","P" */ "\xEF\xBC\xB1", "\xEF\xBC\xB2", "\xEF\xBC\xB3", "\xEF\xBC\xB4", /* "Q","R","S","T" */ "\xEF\xBC\xB5", "\xEF\xBC\xB6", "\xEF\xBC\xB7", "\xEF\xBC\xB8", /* "U","V","W","X" */ "\xEF\xBC\xB9", "\xEF\xBC\xBA", "\xE3\x80\x80", "\xE2\x80\x9D", /* "Y","Z"," ","”" */ "\xE2\x80\x99", "\xEF\xBC\x8F", "\xEF\xBC\x9C", "\xEF\xBC\x9E", /* "’","/","<",">" */ "\xE2\x80\xB5", "\xE3\x80\x94", "\xE3\x80\x95", "\xEF\xBD\x9B", /* "‵","〔""〕","{" */ "\xEF\xBD\x9D", "\xEF\xBC\x8B", "\xEF\xBC\x8D" /* "}","+","-" */ }; STATIC_ASSERT(ARRAY_SIZE(keybuf) == ARRAY_SIZE(chibuf)); rtn = InternalSpecialSymbol(key, pgdata, ARRAY_SIZE(keybuf), keybuf, chibuf); if (rtn == BOPOMOFO_IGNORE) rtn = SpecialSymbolInput(key, pgdata); return (rtn == BOPOMOFO_IGNORE ? SYMBOL_KEY_ERROR : SYMBOL_KEY_OK); } int EasySymbolInput(int key, ChewingData *pgdata) { int rtn, loop, _index; char wordbuf[8]; int nSpecial = EASY_SYMBOL_KEY_TAB_LEN; _index = FindEasySymbolIndex(key); if (-1 != _index) { for (loop = 0; loop < pgdata->static_data.g_easy_symbol_num[_index]; ++loop) { ueStrNCpy(wordbuf, ueStrSeek(pgdata->static_data.g_easy_symbol_value[_index], loop), 1, 1); rtn = _Inner_InternalSpecialSymbol(key, pgdata, key, wordbuf); } return SYMBOL_KEY_OK; } rtn = InternalSpecialSymbol(key, pgdata, nSpecial, G_EASY_SYMBOL_KEY, (const char **) pgdata->static_data.g_easy_symbol_value); if (rtn == BOPOMOFO_IGNORE) rtn = SpecialSymbolInput(key, pgdata); return (rtn == BOPOMOFO_IGNORE ? SYMBOL_KEY_ERROR : SYMBOL_KEY_OK); } int SymbolChoice(ChewingData *pgdata, int sel_i) { int kbtype; int i; int symbol_type; int key; if (!pgdata->static_data.symbol_table && pgdata->choiceInfo.isSymbol != SYMBOL_CHOICE_UPDATE) return BOPOMOFO_ABSORB; if (pgdata->choiceInfo.isSymbol == SYMBOL_CATEGORY_CHOICE && 0 == pgdata->static_data.symbol_table[sel_i]->nSymbols) symbol_type = SYMBOL_CHOICE_INSERT; else symbol_type = pgdata->choiceInfo.isSymbol; /* level one, symbol category */ if (symbol_type == SYMBOL_CATEGORY_CHOICE) { ChoiceInfo *pci = &pgdata->choiceInfo; AvailInfo *pai = &pgdata->availInfo; /* Display all symbols in this category */ pci->nTotalChoice = 0; for (i = 0; i < pgdata->static_data.symbol_table[sel_i]->nSymbols; i++) { ueStrNCpy(pci->totalChoiceStr[pci->nTotalChoice], pgdata->static_data.symbol_table[sel_i]->symbols[i], 1, 1); pci->nTotalChoice++; } pai->avail[0].len = 1; pai->avail[0].id = NULL; pai->nAvail = 1; pai->currentAvail = 0; pci->nChoicePerPage = pgdata->config.candPerPage; assert(pci->nTotalChoice > 0); pci->nPage = CEIL_DIV(pci->nTotalChoice, pci->nChoicePerPage); pci->pageNo = 0; pci->isSymbol = SYMBOL_CHOICE_INSERT; } else { /* level 2 symbol or OpenSymbolChoice */ /* TODO: FIXME, this part is buggy! */ PreeditBuf *buf = &pgdata->preeditBuf[pgdata->chiSymbolCursor]; if (symbol_type == SYMBOL_CHOICE_INSERT) { assert(pgdata->chiSymbolCursor <= pgdata->chiSymbolBufLen); if (pgdata->chiSymbolCursor == pgdata->chiSymbolBufLen || pgdata->symbolKeyBuf[pgdata->chiSymbolCursor] != NO_SYM_KEY) { memmove(&pgdata->preeditBuf[pgdata->chiSymbolCursor + 1], &pgdata->preeditBuf[pgdata->chiSymbolCursor], sizeof(pgdata->preeditBuf[0]) * (pgdata->chiSymbolBufLen - pgdata->chiSymbolCursor)); } else { symbol_type = SYMBOL_CHOICE_UPDATE; } } strncpy(buf->char_, pgdata->choiceInfo.totalChoiceStr[sel_i], sizeof(buf->char_) - 1); buf->category = CHEWING_SYMBOL; /* This is very strange */ key = FindSymbolKey(pgdata->choiceInfo.totalChoiceStr[sel_i]); pgdata->symbolKeyBuf[pgdata->chiSymbolCursor] = key ? key : NO_SYM_KEY; pgdata->bUserArrCnnct[PhoneSeqCursor(pgdata)] = 0; ChoiceEndChoice(pgdata); /* Don't forget the kbtype */ kbtype = pgdata->bopomofoData.kbtype; memset(&(pgdata->bopomofoData), 0, sizeof(BopomofoData)); pgdata->bopomofoData.kbtype = kbtype; if (symbol_type == SYMBOL_CHOICE_INSERT) { pgdata->chiSymbolBufLen++; pgdata->chiSymbolCursor++; } pgdata->choiceInfo.isSymbol = WORD_CHOICE; } return BOPOMOFO_ABSORB; } int SymbolInput(int key, ChewingData *pgdata) { if (isprint((char) key) && /* other character was ignored */ (pgdata->chiSymbolBufLen < MAX_PHONE_SEQ_LEN)) { /* protect the buffer */ PreeditBuf *buf = &pgdata->preeditBuf[pgdata->chiSymbolCursor]; assert(pgdata->chiSymbolCursor <= pgdata->chiSymbolBufLen); memmove(&pgdata->preeditBuf[pgdata->chiSymbolCursor + 1], &pgdata->preeditBuf[pgdata->chiSymbolCursor], sizeof(pgdata->preeditBuf[0]) * (pgdata->chiSymbolBufLen - pgdata->chiSymbolCursor)); buf->char_[0] = (char) key; buf->char_[1] = 0; buf->category = CHEWING_SYMBOL; /* Save Symbol Key */ memmove(&(pgdata->symbolKeyBuf[pgdata->chiSymbolCursor + 1]), &(pgdata->symbolKeyBuf[pgdata->chiSymbolCursor]), sizeof(pgdata->symbolKeyBuf[0]) * (pgdata->chiSymbolBufLen - pgdata->chiSymbolCursor)); pgdata->symbolKeyBuf[pgdata->chiSymbolCursor] = toupper(key); pgdata->bUserArrCnnct[PhoneSeqCursor(pgdata)] = 0; pgdata->chiSymbolCursor++; pgdata->chiSymbolBufLen++; return SYMBOL_KEY_OK; } return SYMBOL_KEY_ERROR; } static int CompInterval(const IntervalType * a, const IntervalType * b) { int cmp = a->from - b->from; if (cmp) return cmp; return (a->to - b->to); } static int FindIntervalFrom(int from, IntervalType inte[], int nInte) { int i; for (i = 0; i < nInte; i++) if (inte[i].from == from) return i; return -1; } void WriteChiSymbolToCommitBuf(ChewingData *pgdata, ChewingOutput *pgo, int len) { int i; char *pos; assert(pgdata); assert(pgo); pgo->commitBufLen = len; pos = pgo->commitBuf; for (i = 0; i < pgo->commitBufLen; ++i) { assert(pos + MAX_UTF8_SIZE + 1 < pgo->commitBuf + sizeof(pgo->commitBuf)); strcpy(pos, pgdata->preeditBuf[i].char_); pos += strlen(pgdata->preeditBuf[i].char_); } *pos = 0; } static int CountReleaseNum(ChewingData *pgdata) { int remain, i; remain = pgdata->config.maxChiSymbolLen - pgdata->chiSymbolBufLen; if (remain >= 0) return 0; qsort(pgdata->preferInterval, pgdata->nPrefer, sizeof(IntervalType), (CompFuncType) CompInterval); if (!ChewingIsChiAt(0, pgdata)) { for (i = 0; i < pgdata->chiSymbolCursor; ++i) { if (ChewingIsChiAt(i, pgdata)) { break; } } return i; } i = FindIntervalFrom(0, pgdata->preferInterval, pgdata->nPrefer); if (i >= 0) { return (pgdata->preferInterval[i].to - pgdata->preferInterval[i].from); } return 1; } static void KillFromLeft(ChewingData *pgdata, int nKill) { int i; for (i = 0; i < nKill; i++) ChewingKillChar(pgdata, 0, DECREASE_CURSOR); } void CleanAllBuf(ChewingData *pgdata) { /* 1 */ pgdata->nPhoneSeq = 0; memset(pgdata->phoneSeq, 0, sizeof(pgdata->phoneSeq)); /* 2 */ pgdata->chiSymbolBufLen = 0; memset(pgdata->preeditBuf, 0, sizeof(pgdata->preeditBuf)); /* 3 */ memset(pgdata->bUserArrBrkpt, 0, sizeof(pgdata->bUserArrBrkpt)); /* 4 */ pgdata->nSelect = 0; /* 5 */ pgdata->chiSymbolCursor = 0; /* 6 */ memset(pgdata->bUserArrCnnct, 0, sizeof(pgdata->bUserArrCnnct)); pgdata->phrOut.nNumCut = 0; memset(pgdata->symbolKeyBuf, 0, sizeof(pgdata->symbolKeyBuf)); pgdata->nPrefer = 0; } int ReleaseChiSymbolBuf(ChewingData *pgdata, ChewingOutput *pgo) { int throwEnd; throwEnd = CountReleaseNum(pgdata); /* * When current buffer size exceeds maxChiSymbolLen, * we need to throw some of the characters at the head of the buffer and * commit them. */ if (throwEnd) { /* * count how many chinese words in "chiSymbolBuf[ 0 .. (throwEnd - 1)]" * And release from "chiSymbolBuf" && "phoneSeq" */ WriteChiSymbolToCommitBuf(pgdata, pgo, throwEnd); KillFromLeft(pgdata, throwEnd); } return throwEnd; } static int ChewingIsBreakPoint(int cursor, ChewingData *pgdata) { static const char *const BREAK_WORD[] = { "\xE6\x98\xAF", "\xE7\x9A\x84", "\xE4\xBA\x86", "\xE4\xB8\x8D", /* 是 的 了 不 */ "\xE4\xB9\x9F", "\xE8\x80\x8C", "\xE4\xBD\xA0", "\xE6\x88\x91", /* 也 而 你 我 */ "\xE4\xBB\x96", "\xE8\x88\x87", "\xE5\xAE\x83", "\xE5\xA5\xB9", /* 他 與 它 她 */ "\xE5\x85\xB6", "\xE5\xB0\xB1", "\xE5\x92\x8C", "\xE6\x88\x96", /* 其 就 和 或 */ "\xE5\x80\x91", "\xE6\x80\xA7", "\xE5\x93\xA1", "\xE5\xAD\x90", /* 們 性 員 子 */ "\xE4\xB8\x8A", "\xE4\xB8\x8B", "\xE4\xB8\xAD", "\xE5\x85\xA7", /* 上 下 中 內 */ "\xE5\xA4\x96", "\xE5\x8C\x96", "\xE8\x80\x85", "\xE5\xAE\xB6", /* 外 化 者 家 */ "\xE5\x85\x92", "\xE5\xB9\xB4", "\xE6\x9C\x88", "\xE6\x97\xA5", /* 兒 年 月 日 */ "\xE6\x99\x82", "\xE5\x88\x86", "\xE7\xA7\x92", "\xE8\xA1\x97", /* 時 分 秒 街 */ "\xE8\xB7\xAF", "\xE6\x9D\x91", /* 路 村 */ "\xE5\x9C\xA8", /* 在 */ }; size_t i; if (!ChewingIsChiAt(cursor, pgdata)) return 1; for (i = 0; i < ARRAY_SIZE(BREAK_WORD); ++i) if (!strcmp(pgdata->preeditBuf[cursor].char_, BREAK_WORD[i])) return 1; return 0; } void AutoLearnPhrase(ChewingData *pgdata) { uint16_t bufPhoneSeq[MAX_PHONE_SEQ_LEN + 1]; char bufWordSeq[MAX_PHONE_SEQ_LEN * MAX_UTF8_SIZE + 1] = { 0 }; char *pos; int i; int from; int fromPreeditBuf; int len; int prev_pos = 0; int pending_pos = 0; /* * FIXME: pgdata->preferInterval does not consider symbol, so we need to * do translate when using APIs that considering symbol. */ UserUpdatePhraseBegin(pgdata); for (i = 0; i < pgdata->nPrefer; i++) { from = pgdata->preferInterval[i].from; len = pgdata->preferInterval[i].to - from; fromPreeditBuf = toPreeditBufIndex(pgdata, from); LOG_VERBOSE("interval from = %d, fromPreeditBuf = %d, len = %d, pending_pos = %d", from, fromPreeditBuf, len, pending_pos); if (pending_pos != 0 && pending_pos < fromPreeditBuf) { /* * There is a pending phrase in buffer and it is not * connected to current phrase. We store it as * userphrase here. */ UserUpdatePhrase(pgdata, bufPhoneSeq, bufWordSeq); prev_pos = 0; pending_pos = 0; } if (len == 1 && !ChewingIsBreakPoint(fromPreeditBuf, pgdata)) { /* * There is a length one phrase and it is not a break * point. We store it and try to connect to other length * one phrase if possible. */ memcpy(bufPhoneSeq + prev_pos, &pgdata->phoneSeq[from], sizeof(uint16_t) * len); bufPhoneSeq[prev_pos + len] = (uint16_t) 0; pos = ueStrSeek(bufWordSeq, prev_pos); copyStringFromPreeditBuf(pgdata, fromPreeditBuf, len, pos, bufWordSeq + sizeof(bufWordSeq) - pos); prev_pos += len; pending_pos = fromPreeditBuf + len; } else { if (pending_pos) { /* * Clean pending phrase because we cannot join * it with current phrase. */ UserUpdatePhrase(pgdata, bufPhoneSeq, bufWordSeq); prev_pos = 0; pending_pos = 0; } memcpy(bufPhoneSeq, &pgdata->phoneSeq[from], sizeof(uint16_t) * len); bufPhoneSeq[len] = (uint16_t) 0; copyStringFromPreeditBuf(pgdata, fromPreeditBuf, len, bufWordSeq, sizeof(bufWordSeq)); UserUpdatePhrase(pgdata, bufPhoneSeq, bufWordSeq); } } if (pending_pos) { UserUpdatePhrase(pgdata, bufPhoneSeq, bufWordSeq); } UserUpdatePhraseEnd(pgdata); } int AddChi(uint16_t phone, uint16_t phoneAlt, ChewingData *pgdata) { int i; int cursor = PhoneSeqCursor(pgdata); /* shift the selectInterval */ for (i = 0; i < pgdata->nSelect; i++) { if (pgdata->selectInterval[i].from >= cursor) { pgdata->selectInterval[i].from++; pgdata->selectInterval[i].to++; } } /* shift the Brkpt */ assert(pgdata->nPhoneSeq >= cursor); memmove(&(pgdata->bUserArrBrkpt[cursor + 2]), &(pgdata->bUserArrBrkpt[cursor + 1]), sizeof(int) * (pgdata->nPhoneSeq - cursor)); memmove(&(pgdata->bUserArrCnnct[cursor + 2]), &(pgdata->bUserArrCnnct[cursor + 1]), sizeof(int) * (pgdata->nPhoneSeq - cursor)); /* add to phoneSeq */ memmove(&(pgdata->phoneSeq[cursor + 1]), &(pgdata->phoneSeq[cursor]), sizeof(uint16_t) * (pgdata->nPhoneSeq - cursor)); pgdata->phoneSeq[cursor] = phone; memmove(&(pgdata->phoneSeqAlt[cursor + 1]), &(pgdata->phoneSeqAlt[cursor]), sizeof(uint16_t) * (pgdata->nPhoneSeq - cursor)); pgdata->phoneSeqAlt[cursor] = phoneAlt; pgdata->nPhoneSeq++; /* add to chiSymbolBuf */ assert(pgdata->chiSymbolBufLen >= pgdata->chiSymbolCursor); memmove(&(pgdata->preeditBuf[pgdata->chiSymbolCursor + 1]), &(pgdata->preeditBuf[pgdata->chiSymbolCursor]), sizeof(pgdata->preeditBuf[0]) * (pgdata->chiSymbolBufLen - pgdata->chiSymbolCursor)); /* "0" means Chinese word */ pgdata->preeditBuf[pgdata->chiSymbolCursor].category = CHEWING_CHINESE; pgdata->chiSymbolBufLen++; pgdata->chiSymbolCursor++; return 0; } static void ShowChewingData(ChewingData *pgdata) { int i; DEBUG_OUT("nPhoneSeq : %d\n" "phoneSeq : ", pgdata->nPhoneSeq); for (i = 0; i < pgdata->nPhoneSeq; i++) DEBUG_OUT("%hu ", pgdata->phoneSeq[i]); DEBUG_OUT("[cursor : %d]\n" "nSelect : %d\n" "selectStr selectInterval\n", PhoneSeqCursor(pgdata), pgdata->nSelect); for (i = 0; i < pgdata->nSelect; i++) { DEBUG_OUT(" %14s%4d%4d\n", pgdata->selectStr[i], pgdata->selectInterval[i].from, pgdata->selectInterval[i].to); } DEBUG_OUT("bUserArrCnnct : "); for (i = 0; i <= pgdata->nPhoneSeq; i++) DEBUG_OUT("%d ", pgdata->bUserArrCnnct[i]); DEBUG_OUT("\n"); DEBUG_OUT("bUserArrBrkpt : "); for (i = 0; i <= pgdata->nPhoneSeq; i++) DEBUG_OUT("%d ", pgdata->bUserArrBrkpt[i]); DEBUG_OUT("\n"); DEBUG_OUT("bArrBrkpt : "); for (i = 0; i <= pgdata->nPhoneSeq; i++) DEBUG_OUT("%d ", pgdata->bArrBrkpt[i]); DEBUG_OUT("\n"); DEBUG_OUT("bChiSym : %d , bSelect : %d\n", pgdata->bChiSym, pgdata->bSelect); } int CallPhrasing(ChewingData *pgdata, int all_phrasing) { /* set "bSymbolArrBrkpt" && "bArrBrkpt" */ int i, ch_count = 0; memcpy(pgdata->bArrBrkpt, pgdata->bUserArrBrkpt, (MAX_PHONE_SEQ_LEN + 1) * sizeof(int)); memset(pgdata->bSymbolArrBrkpt, 0, (MAX_PHONE_SEQ_LEN + 1) * sizeof(int)); for (i = 0; i < pgdata->chiSymbolBufLen; i++) { if (ChewingIsChiAt(i, pgdata)) ch_count++; else { pgdata->bArrBrkpt[ch_count] = 1; pgdata->bSymbolArrBrkpt[ch_count] = 1; } } /* kill select interval */ for (i = 0; i < pgdata->nPhoneSeq; i++) { if (pgdata->bArrBrkpt[i]) { ChewingKillSelectIntervalAcross(i, pgdata); } } ShowChewingData(pgdata); /* then phrasing */ Phrasing(pgdata, all_phrasing); /* and then make prefer interval */ MakePreferInterval(pgdata); return 0; } static void Union(int set1, int set2, int parent[]) { if (set1 != set2) parent[max(set1, set2)] = min(set1, set2); } static int SameSet(int set1, int set2, int parent[]) { while (parent[set1] != 0) { set1 = parent[set1]; } while (parent[set2] != 0) { set2 = parent[set2]; } return (set1 == set2); } /* make prefer interval from phrOut->dispInterval */ static void MakePreferInterval(ChewingData *pgdata) { int i, j, set_no; int belong_set[MAX_PHONE_SEQ_LEN + 1]; int parent[MAX_PHONE_SEQ_LEN + 1]; memset(belong_set, 0, sizeof(int) * (MAX_PHONE_SEQ_LEN + 1)); memset(parent, 0, sizeof(int) * (MAX_PHONE_SEQ_LEN + 1)); /* for each interval */ for (i = 0; i < pgdata->phrOut.nDispInterval; i++) { for (j = pgdata->phrOut.dispInterval[i].from; j < pgdata->phrOut.dispInterval[i].to; j++) { belong_set[j] = i + 1; } } set_no = i + 1; for (i = 0; i < pgdata->nPhoneSeq; i++) if (belong_set[i] == 0) belong_set[i] = set_no++; /* for each connect point */ for (i = 1; i < pgdata->nPhoneSeq; i++) { if (pgdata->bUserArrCnnct[i]) { Union(belong_set[i - 1], belong_set[i], parent); } } /* generate new intervals */ pgdata->nPrefer = 0; i = 0; while (i < pgdata->nPhoneSeq) { for (j = i + 1; j < pgdata->nPhoneSeq; j++) if (!SameSet(belong_set[i], belong_set[j], parent)) break; pgdata->preferInterval[pgdata->nPrefer].from = i; pgdata->preferInterval[pgdata->nPrefer].to = j; pgdata->nPrefer++; i = j; } } /* for MakeOutput */ static void ShiftInterval(ChewingOutput *pgo, ChewingData *pgdata) { int i, arrPos[MAX_PHONE_SEQ_LEN], k = 0, from, len; for (i = 0; i < pgdata->chiSymbolBufLen; i++) { if (ChewingIsChiAt(i, pgdata)) { arrPos[k++] = i; } } arrPos[k] = i; pgo->nDispInterval = pgdata->nPrefer; for (i = 0; i < pgdata->nPrefer; i++) { from = pgdata->preferInterval[i].from; len = pgdata->preferInterval[i].to - from; pgo->dispInterval[i].from = arrPos[from]; pgo->dispInterval[i].to = arrPos[from] + len; } } int MakeOutput(ChewingOutput *pgo, ChewingData *pgdata) { int i; int inx; char *pos; /* fill zero to chiSymbolBuf first */ pgo->preeditBuf[0] = 0; pgo->bopomofoBuf[0] = 0; pos = pgo->preeditBuf; for (i = 0; i < pgdata->chiSymbolBufLen && pos < pgo->preeditBuf + sizeof(pgo->preeditBuf) + MAX_UTF8_SIZE + 1; ++i) { strncpy(pos, pgdata->preeditBuf[i].char_, MAX_UTF8_SIZE + 1); pos += strlen(pgdata->preeditBuf[i].char_); } /* fill point */ pgo->PointStart = pgdata->PointStart; pgo->PointEnd = pgdata->PointEnd; /* fill other fields */ pgo->chiSymbolBufLen = pgdata->chiSymbolBufLen; pgo->chiSymbolCursor = pgdata->chiSymbolCursor; /* fill bopomofoBuf */ if (pgdata->bopomofoData.kbtype >= KB_HANYU_PINYIN) { strcpy(pgo->bopomofoBuf, pgdata->bopomofoData.pinYinData.keySeq); } else { for (i = 0; i < BOPOMOFO_SIZE; i++) { inx = pgdata->bopomofoData.pho_inx[i]; if (inx != 0) { ueStrNCpy(pgo->bopomofoBuf + strlen(pgo->bopomofoBuf), ueConstStrSeek(zhuin_tab[i], inx - 1), 1, STRNCPY_CLOSE); } } } ShiftInterval(pgo, pgdata); memcpy(pgo->dispBrkpt, pgdata->bUserArrBrkpt, sizeof(pgo->dispBrkpt[0]) * (MAX_PHONE_SEQ_LEN + 1)); pgo->pci = &(pgdata->choiceInfo); pgo->bChiSym = pgdata->bChiSym; memcpy(pgo->selKey, pgdata->config.selKey, sizeof(pgdata->config.selKey)); pgdata->bShowMsg = 0; return 0; } int MakeOutputWithRtn(ChewingOutput *pgo, ChewingData *pgdata, int keystrokeRtn) { pgo->keystrokeRtn = keystrokeRtn; return MakeOutput(pgo, pgdata); } void MakeOutputAddMsgAndCleanInterval(ChewingOutput *pgo, ChewingData *pgdata) { pgdata->bShowMsg = 1; pgo->nDispInterval = 0; } int AddSelect(ChewingData *pgdata, int sel_i) { int length, nSelect, cursor; /* save the typing time */ length = pgdata->availInfo.avail[pgdata->availInfo.currentAvail].len; nSelect = pgdata->nSelect; /* change "selectStr" , "selectInterval" , and "nSelect" of ChewingData */ ueStrNCpy(pgdata->selectStr[nSelect], pgdata->choiceInfo.totalChoiceStr[sel_i], length, 1); cursor = PhoneSeqCursor(pgdata); pgdata->selectInterval[nSelect].from = cursor; pgdata->selectInterval[nSelect].to = cursor + length; pgdata->nSelect++; return 0; } int CountSelKeyNum(int key, const ChewingData *pgdata) /* return value starts from 0. If less than zero : error key */ { int i; for (i = 0; i < MAX_SELKEY; i++) if (pgdata->config.selKey[i] == key) return i; return -1; } int CountSymbols(ChewingData *pgdata, int to) { int chi; int i; for (chi = i = 0; i < to; i++) { if (ChewingIsChiAt(i, pgdata)) chi++; } return to - chi; } int PhoneSeqCursor(ChewingData *pgdata) { int cursor = pgdata->chiSymbolCursor - CountSymbols(pgdata, pgdata->chiSymbolCursor); return cursor > 0 ? cursor : 0; } int ChewingIsChiAt(int chiSymbolCursor, ChewingData *pgdata) { return pgdata->preeditBuf[chiSymbolCursor].category == CHEWING_CHINESE; } void RemoveSelectElement(int i, ChewingData *pgdata) { if (--pgdata->nSelect == i) return; pgdata->selectInterval[i] = pgdata->selectInterval[pgdata->nSelect]; strcpy(pgdata->selectStr[i], pgdata->selectStr[pgdata->nSelect]); } static int ChewingKillSelectIntervalAcross(int cursor, ChewingData *pgdata) { int i; for (i = 0; i < pgdata->nSelect; i++) { if (pgdata->selectInterval[i].from < cursor && pgdata->selectInterval[i].to > cursor) { RemoveSelectElement(i, pgdata); i--; } } return 0; } static int KillCharInSelectIntervalAndBrkpt(ChewingData *pgdata, int cursorToKill) { int i; for (i = 0; i < pgdata->nSelect; i++) { if (pgdata->selectInterval[i].from <= cursorToKill && pgdata->selectInterval[i].to > cursorToKill) { RemoveSelectElement(i, pgdata); i--; /* the last one was swap to i, we need to recheck i */ } else if (pgdata->selectInterval[i].from > cursorToKill) { pgdata->selectInterval[i].from--; pgdata->selectInterval[i].to--; } } assert(pgdata->nPhoneSeq >= cursorToKill); memmove(&(pgdata->bUserArrBrkpt[cursorToKill]), &(pgdata->bUserArrBrkpt[cursorToKill + 1]), sizeof(int) * (pgdata->nPhoneSeq - cursorToKill)); memmove(&(pgdata->bUserArrCnnct[cursorToKill]), &(pgdata->bUserArrCnnct[cursorToKill + 1]), sizeof(int) * (pgdata->nPhoneSeq - cursorToKill)); return 0; } int ChewingKillChar(ChewingData *pgdata, int chiSymbolCursorToKill, int minus) { int tmp, cursorToKill; tmp = pgdata->chiSymbolCursor; pgdata->chiSymbolCursor = chiSymbolCursorToKill; cursorToKill = PhoneSeqCursor(pgdata); pgdata->chiSymbolCursor = tmp; if (ChewingIsChiAt(chiSymbolCursorToKill, pgdata)) { KillCharInSelectIntervalAndBrkpt(pgdata, cursorToKill); assert(pgdata->nPhoneSeq - cursorToKill - 1 >= 0); memmove(&(pgdata->phoneSeq[cursorToKill]), &(pgdata->phoneSeq[cursorToKill + 1]), (pgdata->nPhoneSeq - cursorToKill - 1) * sizeof(uint16_t)); pgdata->nPhoneSeq--; } pgdata->symbolKeyBuf[chiSymbolCursorToKill] = 0; assert(pgdata->chiSymbolBufLen - chiSymbolCursorToKill); memmove(&pgdata->symbolKeyBuf[chiSymbolCursorToKill], &pgdata->symbolKeyBuf[chiSymbolCursorToKill + 1], sizeof(pgdata->symbolKeyBuf[0]) * (pgdata->chiSymbolBufLen - chiSymbolCursorToKill)); memmove(&pgdata->preeditBuf[chiSymbolCursorToKill], &pgdata->preeditBuf[chiSymbolCursorToKill + 1], sizeof(pgdata->preeditBuf[0]) * (pgdata->chiSymbolBufLen - chiSymbolCursorToKill)); pgdata->chiSymbolBufLen--; pgdata->chiSymbolCursor -= minus; if (pgdata->chiSymbolCursor < 0) pgdata->chiSymbolCursor = 0; return 0; } int IsPreferIntervalConnted(int cursor, ChewingData *pgdata) { int i; for (i = 0; i < pgdata->nPrefer; i++) { if (pgdata->preferInterval[i].from < cursor && pgdata->preferInterval[i].to > cursor) return 1; } return 0; } static const char *const symbol_buf[][50] = { {"0", "\xC3\xB8", 0}, /* "ø" */ {"[", "\xE3\x80\x8C", "\xE3\x80\x8E", "\xE3\x80\x8A", "\xE3\x80\x88", "\xE3\x80\x90", "\xE3\x80\x94", 0}, /* "「", "『", "《", "〈", "【", "〔" */ {"]", "\xE3\x80\x8D", "\xE3\x80\x8F", "\xE3\x80\x8B", "\xE3\x80\x89", "\xE3\x80\x91", "\xE3\x80\x95", 0}, /* "」", "』", "》", "〉", "】", "〕" */ {"{", "\xEF\xBD\x9B", 0}, /* "{" */ {"}", "\xEF\xBD\x9D", 0}, /* "}" */ {"<", "\xEF\xBC\x8C", "\xE2\x86\x90", 0}, /* ",", "←" */ {">", "\xE3\x80\x82", "\xE2\x86\x92", "\xEF\xBC\x8E", 0}, /* "。", "→", "." */ {"?", "\xEF\xBC\x9F", "\xC2\xBF", 0}, /* "?", "¿" */ {"!", "\xEF\xBC\x81", "\xE2\x85\xA0", "\xC2\xA1", 0}, /* "!", "Ⅰ","¡" */ {"@", "\xEF\xBC\xA0", "\xE2\x85\xA1", "\xE2\x8A\x95", "\xE2\x8A\x99", "\xE3\x8A\xA3", "\xEF\xB9\xAB", 0}, /* "@", "Ⅱ", "⊕", "⊙", "㊣", "﹫" */ {"#", "\xEF\xBC\x83", "\xE2\x85\xA2", "\xEF\xB9\x9F", 0}, /* "#", "Ⅲ", "﹟" */ {"$", "\xEF\xBC\x84", "\xE2\x85\xA3", "\xE2\x82\xAC", "\xEF\xB9\xA9", "\xEF\xBF\xA0", "\xE2\x88\xAE", "\xEF\xBF\xA1", "\xEF\xBF\xA5", 0}, /* "$", "Ⅳ", "€", "﹩", "¢", "∮","£", "¥" */ {"%", "\xEF\xBC\x85", "\xE2\x85\xA4", 0}, /* "%", "Ⅴ" */ {"^", "\xEF\xB8\xBF", "\xE2\x85\xA5", "\xEF\xB9\x80", "\xEF\xB8\xBD", "\xEF\xB8\xBE", 0}, /* "︿", "Ⅵ", "﹀", "︽", "︾" */ {"&", "\xEF\xBC\x86", "\xE2\x85\xA6", "\xEF\xB9\xA0", 0}, /* "&", "Ⅶ", "﹠" */ {"*", "\xEF\xBC\x8A", "\xE2\x85\xA7", "\xC3\x97", "\xE2\x80\xBB", "\xE2\x95\xB3", "\xEF\xB9\xA1", "\xE2\x98\xAF", "\xE2\x98\x86", "\xE2\x98\x85", 0}, /* "*", "Ⅷ", "×", "※", "╳", "﹡", "☯", "☆", "★" */ {"(", "\xEF\xBC\x88", "\xE2\x85\xA8", 0}, /* "(", "Ⅸ" */ {")", "\xEF\xBC\x89", "\xE2\x85\xA9", 0}, /* ")", "Ⅹ" */ {"_", "\xE2\x80\x94", "\xEF\xBC\x8D", "\xE2\x80\x95", "\xE2\x80\x93", "\xE2\x86\x90", "\xE2\x86\x92", "\xEF\xBC\xBF", "\xEF\xBF\xA3", "\xEF\xB9\x8D", "\xEF\xB9\x89", "\xEF\xB9\x8E", "\xEF\xB9\x8A", "\xEF\xB9\x8F", "\xef\xb9\x8b", "\xE2\x80\xA6", "\xE2\x80\xA5", "\xC2\xAF", 0}, /* "—", "-", "―", "–" * "←", "→", "_", " ̄" * "﹍", "﹉", "﹎", "﹊" * "﹏", "﹋", "…", "‥" * "¯" */ {"+", "\xEF\xBC\x8B", "\xC2\xB1", "\xEF\xB9\xA2", 0}, /* "+", "±", "﹢" */ {"=", "\xEF\xBC\x9D", "\xE2\x89\x92", "\xE2\x89\xA0", "\xE2\x89\xA1", "\xE2\x89\xA6", "\xE2\x89\xA7", "\xEF\xB9\xA6", 0}, /* "=", "≒", "≠", "≡", "≦", "≧", "﹦" */ {"`", "\xE3\x80\x8F", "\xE3\x80\x8E", "\xE2\x80\xB2", "\xE2\x80\xB5", 0}, /* "』", "『", "′", "‵" */ {"~", "\xEF\xBD\x9E", 0}, /* "~" */ {":", "\xEF\xBC\x9A", "\xEF\xBC\x9B", "\xEF\xB8\xB0", "\xEF\xB9\x95", 0}, /* ":", ";", "︰", "﹕" */ {"\"", "\xEF\xBC\x9B", 0}, /* ";" */ {"\'", "\xE3\x80\x81", "\xE2\x80\xA6", "\xE2\x80\xA5", 0}, /* "、", "…", "‥" */ {"\\", "\xEF\xBC\xBC", "\xE2\x86\x96", "\xE2\x86\x98", "\xEF\xB9\xA8", 0}, /* "\", "↖", "↘", "﹨" */ {"-", "\xE2\x80\x94", "\xEF\xBC\x8D", "\xE2\x80\x95", "\xE2\x80\x93", "\xE2\x86\x90", "\xE2\x86\x92", "\xEF\xBC\xBF", "\xEF\xBF\xA3", "\xEF\xB9\x8D", "\xEF\xB9\x89", "\xEF\xB9\x8E", "\xEF\xB9\x8A", "\xEF\xB9\x8F", "\xef\xb9\x8b", "\xE2\x80\xA6", "\xE2\x80\xA5", "\xC2\xAF", 0}, /* "—", "-", "―", "–" * "←", "→", "_", " ̄" * "﹍", "﹉", "﹎", "﹊" * "﹏", "﹋", "…", "‥" * "¯" */ {"/", "\xEF\xBC\x8F", "\xC3\xB7", "\xE2\x86\x97", "\xE2\x86\x99", "\xE2\x88\x95", 0}, /* "/","÷","↗","↙","∕" */ {"|", "\xE2\x86\x91", "\xE2\x86\x93", "\xE2\x88\xA3", "\xE2\x88\xA5", "\xEF\xB8\xB1", "\xEF\xB8\xB3", "\xEF\xB8\xB4", 0}, /* "↑", "↓", "∣", "∥", "︱", "︳", "︴" */ {"A", "\xC3\x85", "\xCE\x91", "\xCE\xB1", "\xE2\x94\x9C", "\xE2\x95\xA0", "\xE2\x95\x9F", "\xE2\x95\x9E", 0}, /* "Å","Α", "α", "├", "╠", "╟", "╞" */ {"B", "\xCE\x92", "\xCE\xB2", "\xE2\x88\xB5", 0}, /* "Β", "β","∵" */ {"C", "\xCE\xA7", "\xCF\x87", "\xE2\x94\x98", "\xE2\x95\xAF", "\xE2\x95\x9D", "\xE2\x95\x9C", "\xE2\x95\x9B", "\xE3\x8F\x84", "\xE2\x84\x83", "\xE3\x8E\x9D", "\xE2\x99\xA3", "\xC2\xA9", 0}, /* "Χ", "χ", "┘", "╯", "╝", "╜", "╛" * "㏄", "℃", "㎝", "♣", "©" */ {"D", "\xCE\x94", "\xCE\xB4", "\xE2\x97\x87", "\xE2\x97\x86", "\xE2\x94\xA4", "\xE2\x95\xA3", "\xE2\x95\xA2", "\xE2\x95\xA1", "\xE2\x99\xA6", 0}, /* "Δ", "δ", "◇", "◆", "┤", "╣", "╢", "╡","♦" */ {"E", "\xCE\x95", "\xCE\xB5", "\xE2\x94\x90", "\xE2\x95\xAE", "\xE2\x95\x97", "\xE2\x95\x93", "\xE2\x95\x95", 0}, /* "Ε", "ε", "┐", "╮", "╗", "╓", "╕" */ {"F", "\xCE\xA6", "\xCF\x88", "\xE2\x94\x82", "\xE2\x95\x91", "\xE2\x99\x80", 0}, /* "Φ", "ψ", "│", "║", "♀" */ {"G", "\xCE\x93", "\xCE\xB3", 0}, /* "Γ", "γ" */ {"H", "\xCE\x97", "\xCE\xB7", "\xE2\x99\xA5", 0}, /* "Η", "η","♥" */ {"I", "\xCE\x99", "\xCE\xB9", 0}, /* "Ι", "ι" */ {"J", "\xCF\x86", 0}, /* "φ" */ {"K", "\xCE\x9A", "\xCE\xBA", "\xE3\x8E\x9E", "\xE3\x8F\x8E", 0}, /* "Κ", "κ","㎞", "㏎" */ {"L", "\xCE\x9B", "\xCE\xBB", "\xE3\x8F\x92", "\xE3\x8F\x91", 0}, /* "Λ", "λ","㏒", "㏑" */ {"M", "\xCE\x9C", "\xCE\xBC", "\xE2\x99\x82", "\xE2\x84\x93", "\xE3\x8E\x8E", "\xE3\x8F\x95", "\xE3\x8E\x9C", "\xE3\x8E\xA1", 0}, /* "Μ", "μ", "♂", "ℓ", "㎎", "㏕", "㎜","㎡" */ {"N", "\xCE\x9D", "\xCE\xBD", "\xE2\x84\x96", 0}, /* "Ν", "ν","№" */ {"O", "\xCE\x9F", "\xCE\xBF", 0}, /* "Ο", "ο" */ {"P", "\xCE\xA0", "\xCF\x80", 0}, /* "Π", "π" */ {"Q", "\xCE\x98", "\xCE\xB8", "\xD0\x94", "\xE2\x94\x8C", "\xE2\x95\xAD", "\xE2\x95\x94", "\xE2\x95\x93", "\xE2\x95\x92", 0}, /* "Θ", "θ","Д","┌", "╭", "╔", "╓", "╒" */ {"R", "\xCE\xA1", "\xCF\x81", "\xE2\x94\x80", "\xE2\x95\x90", "\xC2\xAE", 0}, /* "Ρ", "ρ", "─", "═" ,"®" */ {"S", "\xCE\xA3", "\xCF\x83", "\xE2\x88\xB4", "\xE2\x96\xA1", "\xE2\x96\xA0", "\xE2\x94\xBC", "\xE2\x95\xAC", "\xE2\x95\xAA", "\xE2\x95\xAB", "\xE2\x88\xAB", "\xC2\xA7", "\xE2\x99\xA0", 0}, /* "Σ", "σ", "∴", "□", "■", "┼", "╬", "╪", "╫" * "∫", "§", "♠" */ {"T", "\xCE\xA4", "\xCF\x84", "\xCE\xB8", "\xE2\x96\xB3", "\xE2\x96\xB2", "\xE2\x96\xBD", "\xE2\x96\xBC", "\xE2\x84\xA2", "\xE2\x8A\xBF", "\xE2\x84\xA2", 0}, /* "Τ", "τ","θ","△","▲","▽","▼","™","⊿", "™" */ {"U", "\xCE\xA5", "\xCF\x85", "\xCE\xBC", "\xE2\x88\xAA", "\xE2\x88\xA9", 0}, /* "Υ", "υ","μ","∪", "∩" */ {"V", "\xCE\xBD", 0}, {"W", "\xE2\x84\xA6", "\xCF\x89", "\xE2\x94\xAC", "\xE2\x95\xA6", "\xE2\x95\xA4", "\xE2\x95\xA5", 0}, /* "Ω", "ω", "┬", "╦", "╤", "╥" */ {"X", "\xCE\x9E", "\xCE\xBE", "\xE2\x94\xB4", "\xE2\x95\xA9", "\xE2\x95\xA7", "\xE2\x95\xA8", 0}, /* "Ξ", "ξ", "┴", "╩", "╧", "╨" */ {"Y", "\xCE\xA8", 0}, /* "Ψ" */ {"Z", "\xCE\x96", "\xCE\xB6", "\xE2\x94\x94", "\xE2\x95\xB0", "\xE2\x95\x9A", "\xE2\x95\x99", "\xE2\x95\x98", 0}, /* "Ζ", "ζ", "└", "╰", "╚", "╙", "╘" */ }; static int FindSymbolKey(const char *symbol) { unsigned int i; const char *const *buf; for (i = 0; i < ARRAY_SIZE(symbol_buf); ++i) { for (buf = symbol_buf[i]; *buf; ++buf) { if (0 == strcmp(*buf, symbol)) return *symbol_buf[i][0]; } } return 0; } int OpenSymbolChoice(ChewingData *pgdata) { int i, symbol_buf_len = ARRAY_SIZE(symbol_buf); const char *const *pBuf; ChoiceInfo *pci = &(pgdata->choiceInfo); pci->oldChiSymbolCursor = pgdata->chiSymbolCursor; /* see if there is some word in the cursor position */ if (pgdata->chiSymbolCursor == pgdata->chiSymbolBufLen) pgdata->chiSymbolCursor--; if (pgdata->symbolKeyBuf[pgdata->chiSymbolCursor] == NO_SYM_KEY) { pgdata->bSelect = 1; HaninSymbolInput(pgdata); return 0; } for (i = 0; i < symbol_buf_len; i++) { if (symbol_buf[i][0][0] == pgdata->symbolKeyBuf[pgdata->chiSymbolCursor]) { pBuf = symbol_buf[i]; break; } } if (i == symbol_buf_len) { ChoiceEndChoice(pgdata); return 0; } pci->nTotalChoice = 0; for (i = 1; pBuf[i]; i++) { ueStrNCpy(pci->totalChoiceStr[pci->nTotalChoice], pBuf[i], ueStrLen(pBuf[i]), 1); pci->nTotalChoice++; } pci->nChoicePerPage = pgdata->config.candPerPage; assert(pci->nTotalChoice > 0); pci->nPage = CEIL_DIV(pci->nTotalChoice, pci->nChoicePerPage); pci->pageNo = 0; pci->isSymbol = SYMBOL_CHOICE_UPDATE; pgdata->bSelect = 1; pgdata->availInfo.nAvail = 1; pgdata->availInfo.currentAvail = 0; pgdata->availInfo.avail[0].id = NULL; pgdata->availInfo.avail[0].len = 1; return 0; } int InitSymbolTable(ChewingData *pgdata, const char *prefix) { static const unsigned int MAX_SYMBOL_ENTRY = 100; static const size_t LINE_LEN = 512; // shall be long enough? char *filename = NULL; FILE *file = NULL; char *line = NULL; SymbolEntry **entry = NULL; char *category_end; const char *symbols; char *symbols_end; const char *symbol; size_t i; size_t len; size_t size; int ret = -1; pgdata->static_data.n_symbol_entry = 0; pgdata->static_data.symbol_table = NULL; ret = asprintf(&filename, "%s" PLAT_SEPARATOR "%s", prefix, SYMBOL_TABLE_FILE); if (ret == -1) goto error; file = fopen(filename, "r"); if (!file) goto error; line = ALC(char, LINE_LEN); if (!line) goto error; entry = ALC(SymbolEntry *, MAX_SYMBOL_ENTRY); if (!entry) goto error; while (fgets(line, LINE_LEN, file) && pgdata->static_data.n_symbol_entry < MAX_SYMBOL_ENTRY) { category_end = strpbrk(line, "=\r\n"); if (!category_end) goto error; symbols = category_end + 1; symbols_end = strpbrk(symbols, "\r\n"); if (symbols_end) { *symbols_end = 0; len = ueStrLen(symbols); entry[pgdata->static_data.n_symbol_entry] = (SymbolEntry *) malloc(sizeof(entry[0][0]) + sizeof(entry[0][0].symbols[0]) * len); if (!entry[pgdata->static_data.n_symbol_entry]) goto error; entry[pgdata->static_data.n_symbol_entry] ->nSymbols = len; symbol = symbols; for (i = 0; i < len; ++i) { ueStrNCpy(entry[pgdata->static_data.n_symbol_entry]->symbols[i], symbol, 1, 1); // FIXME: What if symbol is combining sequences. symbol += ueBytesFromChar(symbol[0]); } } else { entry[pgdata->static_data.n_symbol_entry] = (SymbolEntry *) malloc(sizeof(entry[0][0])); if (!entry[pgdata->static_data.n_symbol_entry]) goto error; entry[pgdata->static_data.n_symbol_entry] ->nSymbols = 0; } *category_end = 0; ueStrNCpy(entry[pgdata->static_data.n_symbol_entry]->category, line, MAX_PHRASE_LEN, 1); ++pgdata->static_data.n_symbol_entry; } size = sizeof(*pgdata->static_data.symbol_table) * pgdata->static_data.n_symbol_entry; if (!size) goto end; pgdata->static_data.symbol_table = (SymbolEntry **) malloc(size); if (!pgdata->static_data.symbol_table) goto error; memcpy(pgdata->static_data.symbol_table, entry, size); ret = 0; end: free(entry); free(line); fclose(file); free(filename); return ret; error: for (i = 0; i < pgdata->static_data.n_symbol_entry; ++i) { free(entry[i]); } goto end; } void TerminateSymbolTable(ChewingData *pgdata) { unsigned int i; if (pgdata->static_data.symbol_table) { for (i = 0; i < pgdata->static_data.n_symbol_entry; ++i) free(pgdata->static_data.symbol_table[i]); free(pgdata->static_data.symbol_table); pgdata->static_data.n_symbol_entry = 0; pgdata->static_data.symbol_table = NULL; } } int InitEasySymbolInput(ChewingData *pgdata, const char *prefix) { static const size_t LINE_LEN = 512; // shall be long enough? FILE *file = NULL; char *filename = NULL; char *line = NULL; int len; int _index; char *symbol; int ret = -1; ret = asprintf(&filename, "%s" PLAT_SEPARATOR "%s", prefix, SOFTKBD_TABLE_FILE); if (ret == -1) goto filenamefail; file = fopen(filename, "r"); if (!file) goto fileopenfail; line = ALC(char, LINE_LEN); if (!line) goto linefail; while (fgets(line, LINE_LEN, file)) { if (' ' != line[1]) continue; // Remove tailing \n len = strcspn(line, "\r\n"); line[len] = '\0'; _index = FindEasySymbolIndex(line[0]); if (-1 == _index) continue; len = ueStrLen(&line[2]); if (0 == len || len > MAX_PHRASE_LEN) continue; symbol = ALC(char, strlen(&line[2]) + 1); if (!symbol) goto end; ueStrNCpy(symbol, &line[2], len, 1); free(pgdata->static_data.g_easy_symbol_value[_index]); pgdata->static_data.g_easy_symbol_value[_index] = symbol; pgdata->static_data.g_easy_symbol_num[_index] = len; } ret = 0; end: free(line); linefail: fclose(file); fileopenfail: free(filename); filenamefail: return ret; } void TerminateEasySymbolTable(ChewingData *pgdata) { unsigned int i; for (i = 0; i < EASY_SYMBOL_KEY_TAB_LEN; ++i) { if (NULL != pgdata->static_data.g_easy_symbol_value[i]) { free(pgdata->static_data.g_easy_symbol_value[i]); pgdata->static_data.g_easy_symbol_value[i] = NULL; } pgdata->static_data.g_easy_symbol_num[i] = 0; } } void copyStringFromPreeditBuf(ChewingData *pgdata, int pos, int len, char *output, int output_len) { int i; int x; assert(pgdata); assert(0 <= pos && (size_t) (pos + len) < ARRAY_SIZE(pgdata->preeditBuf)); assert(output); assert(output_len); LOG_VERBOSE("Copy pos %d, len %d from preeditBuf", pos, len); for (i = pos; i < pos + len; ++i) { x = strlen(pgdata->preeditBuf[i].char_); if (x >= output_len) // overflow return; memcpy(output, pgdata->preeditBuf[i].char_, x); output += x; output_len -= x; } output[0] = 0; } /* * This function converts phoneSeq index (which does not count symbol) to * preeditBuf index (which does count symbol). */ int toPreeditBufIndex(ChewingData *pgdata, int pos) { int word_count; int i; assert(pgdata); assert(0 <= pos && pos <= MAX_CHI_SYMBOL_LEN); for (i = 0, word_count = 0; i < MAX_CHI_SYMBOL_LEN; ++i) { if (ChewingIsChiAt(i, pgdata)) ++word_count; /* * pos = 0 means finding the first word, so we need to add one * here. */ if (word_count == pos + 1) break; } LOG_VERBOSE("translate phoneSeq index %d to preeditBuf index %d", pos, i); return i; }
lgpl-2.1
tibogens/OpenThreads
examples/workcrew/ThreadObserver.cpp
4
1413
// // OpenThread library, Copyright (C) 2002 - 2003 The Open Thread Group // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #include <cstdio> #include "ThreadObserver.h" void ThreadObserver::threadStarted(const int threadId) { printf("Thread %d started.\n", threadId); } void ThreadObserver::threadFinished(const int threadId) { printf("Thread %d finished.\n", threadId); } void ThreadObserver::threadMessage(const int threadId, const char *message) { printf("Thread Message (%d) : %s\n", threadId, message); } void ThreadObserver::threadError(const int threadId, const char *errorMessage) { printf("Thread Message (%d) : %s\n", threadId, errorMessage); }
lgpl-2.1
sunblithe/qt-everywhere-opensource-src-4.7.1
src/3rdparty/webkit/WebCore/platform/MIMETypeRegistry.cpp
5
15940
/* * Copyright (C) 2006, 2008, 2009 Apple Inc. All rights reserved. * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/) * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "MIMETypeRegistry.h" #include "ArchiveFactory.h" #include "MediaPlayer.h" #include "StringHash.h" #include <wtf/HashMap.h> #include <wtf/HashSet.h> #include <wtf/StdLibExtras.h> #if PLATFORM(CG) #include "ImageSourceCG.h" #include <ApplicationServices/ApplicationServices.h> #include <wtf/RetainPtr.h> #endif #if PLATFORM(QT) #include <qimagereader.h> #include <qimagewriter.h> #endif namespace WebCore { static HashSet<String>* supportedImageResourceMIMETypes; static HashSet<String>* supportedImageMIMETypes; static HashSet<String>* supportedImageMIMETypesForEncoding; static HashSet<String>* supportedJavaScriptMIMETypes; static HashSet<String>* supportedNonImageMIMETypes; static HashSet<String>* supportedMediaMIMETypes; static HashMap<String, String, CaseFoldingHash>* mediaMIMETypeForExtensionMap; static void initializeSupportedImageMIMETypes() { #if PLATFORM(CG) RetainPtr<CFArrayRef> supportedTypes(AdoptCF, CGImageSourceCopyTypeIdentifiers()); CFIndex count = CFArrayGetCount(supportedTypes.get()); for (CFIndex i = 0; i < count; i++) { RetainPtr<CFStringRef> supportedType(AdoptCF, reinterpret_cast<CFStringRef>(CFArrayGetValueAtIndex(supportedTypes.get(), i))); String mimeType = MIMETypeForImageSourceType(supportedType.get()); if (!mimeType.isEmpty()) { supportedImageMIMETypes->add(mimeType); supportedImageResourceMIMETypes->add(mimeType); } } // On Tiger and Leopard, com.microsoft.bmp doesn't have a MIME type in the registry. supportedImageMIMETypes->add("image/bmp"); supportedImageResourceMIMETypes->add("image/bmp"); // Favicons don't have a MIME type in the registry either. supportedImageMIMETypes->add("image/vnd.microsoft.icon"); supportedImageMIMETypes->add("image/x-icon"); supportedImageResourceMIMETypes->add("image/vnd.microsoft.icon"); supportedImageResourceMIMETypes->add("image/x-icon"); // We only get one MIME type per UTI, hence our need to add these manually supportedImageMIMETypes->add("image/pjpeg"); supportedImageResourceMIMETypes->add("image/pjpeg"); // We don't want to try to treat all binary data as an image supportedImageMIMETypes->remove("application/octet-stream"); supportedImageResourceMIMETypes->remove("application/octet-stream"); // Don't treat pdf/postscript as images directly supportedImageMIMETypes->remove("application/pdf"); supportedImageMIMETypes->remove("application/postscript"); #elif PLATFORM(QT) QList<QByteArray> formats = QImageReader::supportedImageFormats(); for (size_t i = 0; i < static_cast<size_t>(formats.size()); ++i) { #if ENABLE(SVG) /* * Qt has support for SVG, but we want to use KSVG2 */ if (formats.at(i).toLower().startsWith("svg")) continue; #endif String mimeType = MIMETypeRegistry::getMIMETypeForExtension(formats.at(i).constData()); supportedImageMIMETypes->add(mimeType); supportedImageResourceMIMETypes->add(mimeType); } supportedImageMIMETypes->remove("application/octet-stream"); supportedImageResourceMIMETypes->remove("application/octet-stream"); #else // assume that all implementations at least support the following standard // image types: static const char* types[] = { "image/jpeg", "image/png", "image/gif", "image/bmp", "image/vnd.microsoft.icon", // ico "image/x-icon", // ico "image/x-xbitmap" // xbm }; for (size_t i = 0; i < sizeof(types) / sizeof(types[0]); ++i) { supportedImageMIMETypes->add(types[i]); supportedImageResourceMIMETypes->add(types[i]); } #endif } static void initializeSupportedImageMIMETypesForEncoding() { supportedImageMIMETypesForEncoding = new HashSet<String>; #if PLATFORM(CG) #if PLATFORM(MAC) RetainPtr<CFArrayRef> supportedTypes(AdoptCF, CGImageDestinationCopyTypeIdentifiers()); CFIndex count = CFArrayGetCount(supportedTypes.get()); for (CFIndex i = 0; i < count; i++) { RetainPtr<CFStringRef> supportedType(AdoptCF, reinterpret_cast<CFStringRef>(CFArrayGetValueAtIndex(supportedTypes.get(), i))); String mimeType = MIMETypeForImageSourceType(supportedType.get()); if (!mimeType.isEmpty()) supportedImageMIMETypesForEncoding->add(mimeType); } #else // FIXME: Add Windows support for all the supported UTI's when a way to convert from MIMEType to UTI reliably is found. // For now, only support PNG, JPEG and GIF. See <rdar://problem/6095286>. supportedImageMIMETypesForEncoding->add("image/png"); supportedImageMIMETypesForEncoding->add("image/jpeg"); supportedImageMIMETypesForEncoding->add("image/gif"); #endif #elif PLATFORM(QT) QList<QByteArray> formats = QImageWriter::supportedImageFormats(); for (int i = 0; i < formats.size(); ++i) { String mimeType = MIMETypeRegistry::getMIMETypeForExtension(formats.at(i).constData()); supportedImageMIMETypesForEncoding->add(mimeType); } supportedImageMIMETypesForEncoding->remove("application/octet-stream"); #elif PLATFORM(CAIRO) supportedImageMIMETypesForEncoding->add("image/png"); #endif } static void initializeSupportedJavaScriptMIMETypes() { /* Mozilla 1.8 and WinIE 7 both accept text/javascript and text/ecmascript. Mozilla 1.8 accepts application/javascript, application/ecmascript, and application/x-javascript, but WinIE 7 doesn't. WinIE 7 accepts text/javascript1.1 - text/javascript1.3, text/jscript, and text/livescript, but Mozilla 1.8 doesn't. Mozilla 1.8 allows leading and trailing whitespace, but WinIE 7 doesn't. Mozilla 1.8 and WinIE 7 both accept the empty string, but neither accept a whitespace-only string. We want to accept all the values that either of these browsers accept, but not other values. */ static const char* types[] = { "text/javascript", "text/ecmascript", "application/javascript", "application/ecmascript", "application/x-javascript", "text/javascript1.1", "text/javascript1.2", "text/javascript1.3", "text/jscript", "text/livescript", }; for (size_t i = 0; i < sizeof(types) / sizeof(types[0]); ++i) supportedJavaScriptMIMETypes->add(types[i]); } static void initializeSupportedNonImageMimeTypes() { static const char* types[] = { #if ENABLE(WML) "text/vnd.wap.wml", "application/vnd.wap.wmlc", #endif "text/html", "text/xml", "text/xsl", "text/plain", "text/", "application/xml", "application/xhtml+xml", "application/vnd.wap.xhtml+xml", "application/rss+xml", "application/atom+xml", #if ENABLE(SVG) "image/svg+xml", #endif #if ENABLE(FTPDIR) "application/x-ftp-directory", #endif "multipart/x-mixed-replace" }; for (size_t i = 0; i < sizeof(types)/sizeof(types[0]); ++i) supportedNonImageMIMETypes->add(types[i]); ArchiveFactory::registerKnownArchiveMIMETypes(); } static void initializeMediaTypeMaps() { struct TypeExtensionPair { const char* type; const char* extension; }; // A table of common media MIME types and file extenstions used when a platform's // specific MIME type lookup doens't have a match for a media file extension. While some // file extensions are claimed by multiple MIME types, this table only includes one // for each because it is currently only used by getMediaMIMETypeForExtension. If we // ever add a MIME type -> file extension mapping, the alternate MIME types will need // to be added. static const TypeExtensionPair pairs[] = { // Ogg { "application/ogg", "ogx" }, { "audio/ogg", "ogg" }, { "audio/ogg", "oga" }, { "video/ogg", "ogv" }, // Annodex { "application/annodex", "anx" }, { "audio/annodex", "axa" }, { "video/annodex", "axv" }, { "audio/speex", "spx" }, // MPEG { "audio/mpeg", "m1a" }, { "audio/mpeg", "m2a" }, { "audio/mpeg", "m1s" }, { "audio/mpeg", "mpa" }, { "video/mpeg", "mpg" }, { "video/mpeg", "m15" }, { "video/mpeg", "m1s" }, { "video/mpeg", "m1v" }, { "video/mpeg", "m75" }, { "video/mpeg", "mpa" }, { "video/mpeg", "mpeg" }, { "video/mpeg", "mpm" }, { "video/mpeg", "mpv" }, // MPEG playlist { "audio/x-mpegurl", "m3url" }, { "application/x-mpegurl", "m3u8" }, // MPEG-4 { "video/x-m4v", "m4v" }, { "audio/x-m4a", "m4a" }, { "audio/x-m4b", "m4b" }, { "audio/x-m4p", "m4p" }, // MP3 { "audio/mp3", "mp3" }, // MPEG-2 { "video/x-mpeg2", "mp2" }, { "video/mpeg2", "vob" }, { "video/mpeg2", "mod" }, { "video/m2ts", "m2ts" }, { "video/x-m2ts", "m2t" }, { "video/x-m2ts", "ts" }, // 3GP/3GP2 { "audio/3gpp", "3gpp" }, { "audio/3gpp2", "3g2" }, { "application/x-mpeg", "amc" }, // AAC { "audio/aac", "aac" }, { "audio/aac", "adts" }, { "audio/x-aac", "m4r" }, // CoreAudio File { "audio/x-caf", "caf" }, { "audio/x-gsm", "gsm" } }; mediaMIMETypeForExtensionMap = new HashMap<String, String, CaseFoldingHash>; const unsigned numPairs = sizeof(pairs) / sizeof(pairs[0]); for (unsigned ndx = 0; ndx < numPairs; ++ndx) mediaMIMETypeForExtensionMap->set(pairs[ndx].extension, pairs[ndx].type); } String MIMETypeRegistry::getMediaMIMETypeForExtension(const String& ext) { // Check with system specific implementation first. String mimeType = getMIMETypeForExtension(ext); if (!mimeType.isEmpty()) return mimeType; // No match, look in the static mapping. if (!mediaMIMETypeForExtensionMap) initializeMediaTypeMaps(); return mediaMIMETypeForExtensionMap->get(ext); } static void initializeSupportedMediaMIMETypes() { supportedMediaMIMETypes = new HashSet<String>; #if ENABLE(VIDEO) MediaPlayer::getSupportedTypes(*supportedMediaMIMETypes); #endif } static void initializeMIMETypeRegistry() { supportedJavaScriptMIMETypes = new HashSet<String>; initializeSupportedJavaScriptMIMETypes(); supportedNonImageMIMETypes = new HashSet<String>(*supportedJavaScriptMIMETypes); initializeSupportedNonImageMimeTypes(); supportedImageResourceMIMETypes = new HashSet<String>; supportedImageMIMETypes = new HashSet<String>; initializeSupportedImageMIMETypes(); } String MIMETypeRegistry::getMIMETypeForPath(const String& path) { int pos = path.reverseFind('.'); if (pos >= 0) { String extension = path.substring(pos + 1); String result = getMIMETypeForExtension(extension); if (result.length()) return result; } return "application/octet-stream"; } bool MIMETypeRegistry::isSupportedImageMIMEType(const String& mimeType) { if (mimeType.isEmpty()) return false; if (!supportedImageMIMETypes) initializeMIMETypeRegistry(); return supportedImageMIMETypes->contains(mimeType); } bool MIMETypeRegistry::isSupportedImageResourceMIMEType(const String& mimeType) { if (mimeType.isEmpty()) return false; if (!supportedImageResourceMIMETypes) initializeMIMETypeRegistry(); return supportedImageResourceMIMETypes->contains(mimeType); } bool MIMETypeRegistry::isSupportedImageMIMETypeForEncoding(const String& mimeType) { if (mimeType.isEmpty()) return false; if (!supportedImageMIMETypesForEncoding) initializeSupportedImageMIMETypesForEncoding(); return supportedImageMIMETypesForEncoding->contains(mimeType); } bool MIMETypeRegistry::isSupportedJavaScriptMIMEType(const String& mimeType) { if (mimeType.isEmpty()) return false; if (!supportedJavaScriptMIMETypes) initializeMIMETypeRegistry(); return supportedJavaScriptMIMETypes->contains(mimeType); } bool MIMETypeRegistry::isSupportedNonImageMIMEType(const String& mimeType) { if (mimeType.isEmpty()) return false; if (!supportedNonImageMIMETypes) initializeMIMETypeRegistry(); return supportedNonImageMIMETypes->contains(mimeType); } bool MIMETypeRegistry::isSupportedMediaMIMEType(const String& mimeType) { if (mimeType.isEmpty()) return false; if (!supportedMediaMIMETypes) initializeSupportedMediaMIMETypes(); return supportedMediaMIMETypes->contains(mimeType); } bool MIMETypeRegistry::isJavaAppletMIMEType(const String& mimeType) { // Since this set is very limited and is likely to remain so we won't bother with the overhead // of using a hash set. // Any of the MIME types below may be followed by any number of specific versions of the JVM, // which is why we use startsWith() return mimeType.startsWith("application/x-java-applet", false) || mimeType.startsWith("application/x-java-bean", false) || mimeType.startsWith("application/x-java-vm", false); } HashSet<String>& MIMETypeRegistry::getSupportedImageMIMETypes() { if (!supportedImageMIMETypes) initializeMIMETypeRegistry(); return *supportedImageMIMETypes; } HashSet<String>& MIMETypeRegistry::getSupportedImageResourceMIMETypes() { if (!supportedImageResourceMIMETypes) initializeMIMETypeRegistry(); return *supportedImageResourceMIMETypes; } HashSet<String>& MIMETypeRegistry::getSupportedImageMIMETypesForEncoding() { if (!supportedImageMIMETypesForEncoding) initializeSupportedImageMIMETypesForEncoding(); return *supportedImageMIMETypesForEncoding; } HashSet<String>& MIMETypeRegistry::getSupportedNonImageMIMETypes() { if (!supportedNonImageMIMETypes) initializeMIMETypeRegistry(); return *supportedNonImageMIMETypes; } HashSet<String>& MIMETypeRegistry::getSupportedMediaMIMETypes() { if (!supportedMediaMIMETypes) initializeSupportedMediaMIMETypes(); return *supportedMediaMIMETypes; } const String& defaultMIMEType() { DEFINE_STATIC_LOCAL(const String, defaultMIMEType, ("application/octet-stream")); return defaultMIMEType; } } // namespace WebCore
lgpl-2.1
vrjuggler/vrjuggler
modules/vrjuggler/test/Draw/OGL/texture/cubeGeometry.cpp
6
2839
/*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998-2011 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * *************** <auto-copyright.pl END do not edit this line> ***************/ #include "cubeGeometry.h" // number of verticies // this can be passed to opengl's glDrawArrays( .., .. ); const unsigned int cubeGeometry::mSize( 36 ); // format is: T2F_C4F_N3F_V3F const float cubeGeometry::mData[432] = { 0, 0, 1, 0, 0, 1, 0, 0, 1, -1, -1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, -1, 1, 1, 0, 0.3f, 0.3f, 0.3f, 1, 0, 0, 1, -1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, -1, 1, 1, 0, 0.3f, 0.3f, 0.3f, 1, 0, 0, 1, -1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1, -1, 0, 0, -1, -1, 1, 0, 1, 0.3f, 0.3f, 0.3f, 1, -1, 0, 0, -1, 1, 1, 1, 0, 1, 1, 1, 1, -1, 0, 0, -1, -1, -1, 0, 1, 0.3f, 0.3f, 0.3f, 1, -1, 0, 0, -1, 1, 1, 1, 0, 1, 1, 1, 1, -1, 0, 0, -1, -1, -1, 1, 1, 0.5f, 0, 0.5f, 1, -1, 0, 0, -1, 1, -1, 0, 0, 1, 1, 1, 1, 0, 0, -1, -1, -1, -1, 0, 1, 0.5f, 0, 0.5f, 1, 0, 0, -1, -1, 1, -1, 1, 0, 0, 0.5f, 1.5f, 1, 0, 0, -1, 1, -1, -1, 0, 1, 0.5f, 0, 0.5f, 1, 0, 0, -1, -1, 1, -1, 1, 0, 0, 0.5f, 1.5f, 1, 0, 0, -1, 1, -1, -1, 1, 1, 0.5f, 0.5f, 0, 1, 0, 0, -1, 1, 1, -1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, -1, 1, 0, 1, 0, 0.5, 1.5f, 1, 1, 0, 0, 1, -1, -1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0.5f, 1.5f, 1, 1, 0, 0, 1, -1, -1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0.5f, 0.5f, 0, 1, 1, 0, 0, 1, 1, -1, 0, 0, 0.3f, 0.3f, 0.3f, 1, 0, 1, 0, -1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0.5f, 0, 0.5f, 1, 0, 1, 0, -1, 1, -1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0.5f, 0, 0.5f, 1, 0, 1, 0, -1, 1, -1, 1, 1, 0.5f, 0.5f, 0, 1, 0, 1, 0, 1, 1, -1, 0, 0, 1, 0, 0, 1, 0, -1, 0, -1, -1, 1, 0, 1, 1, 1, 1, 1, 0, -1, 0, -1, -1, -1, 1, 0, 0, 0, 1, 1, 0, -1, 0, 1, -1, 1, 0, 1, 1, 1, 1, 1, 0, -1, 0, -1, -1, -1, 1, 0, 0, 0, 1, 1, 0, -1, 0, 1, -1, 1, 1, 1, 0, 0.5f, 1.5f, 1, 0, -1, 0, 1, -1, -1 };
lgpl-2.1
DanielNoteboom/MyFecLibrary
decode_rs.c
7
6863
/* Reed-Solomon decoder * Copyright 2002 Phil Karn, KA9Q * May be used under the terms of the GNU Lesser General Public License (LGPL) */ #ifdef DEBUG #include <stdio.h> #endif #include <string.h> #define NULL ((void *)0) #define min(a,b) ((a) < (b) ? (a) : (b)) #ifdef FIXED #include "fixed.h" #elif defined(BIGSYM) #include "int.h" #else #include "char.h" #endif int DECODE_RS( #ifdef FIXED data_t *data, int *eras_pos, int no_eras,int pad){ #else void *p,data_t *data, int *eras_pos, int no_eras){ struct rs *rs = (struct rs *)p; #endif int deg_lambda, el, deg_omega; int i, j, r,k; data_t u,q,tmp,num1,num2,den,discr_r; data_t lambda[NROOTS+1], s[NROOTS]; /* Err+Eras Locator poly * and syndrome poly */ data_t b[NROOTS+1], t[NROOTS+1], omega[NROOTS+1]; data_t root[NROOTS], reg[NROOTS+1], loc[NROOTS]; int syn_error, count; #ifdef FIXED /* Check pad parameter for validity */ if(pad < 0 || pad >= NN) return -1; #endif /* form the syndromes; i.e., evaluate data(x) at roots of g(x) */ for(i=0;i<NROOTS;i++) s[i] = data[0]; for(j=1;j<NN-PAD;j++){ for(i=0;i<NROOTS;i++){ if(s[i] == 0){ s[i] = data[j]; } else { s[i] = data[j] ^ ALPHA_TO[MODNN(INDEX_OF[s[i]] + (FCR+i)*PRIM)]; } } } /* Convert syndromes to index form, checking for nonzero condition */ syn_error = 0; for(i=0;i<NROOTS;i++){ syn_error |= s[i]; s[i] = INDEX_OF[s[i]]; } if (!syn_error) { /* if syndrome is zero, data[] is a codeword and there are no * errors to correct. So return data[] unmodified */ count = 0; goto finish; } memset(&lambda[1],0,NROOTS*sizeof(lambda[0])); lambda[0] = 1; if (no_eras > 0) { /* Init lambda to be the erasure locator polynomial */ lambda[1] = ALPHA_TO[MODNN(PRIM*(NN-1-eras_pos[0]))]; for (i = 1; i < no_eras; i++) { u = MODNN(PRIM*(NN-1-eras_pos[i])); for (j = i+1; j > 0; j--) { tmp = INDEX_OF[lambda[j - 1]]; if(tmp != A0) lambda[j] ^= ALPHA_TO[MODNN(u + tmp)]; } } #if DEBUG >= 1 /* Test code that verifies the erasure locator polynomial just constructed Needed only for decoder debugging. */ /* find roots of the erasure location polynomial */ for(i=1;i<=no_eras;i++) reg[i] = INDEX_OF[lambda[i]]; count = 0; for (i = 1,k=IPRIM-1; i <= NN; i++,k = MODNN(k+IPRIM)) { q = 1; for (j = 1; j <= no_eras; j++) if (reg[j] != A0) { reg[j] = MODNN(reg[j] + j); q ^= ALPHA_TO[reg[j]]; } if (q != 0) continue; /* store root and error location number indices */ root[count] = i; loc[count] = k; count++; } if (count != no_eras) { printf("count = %d no_eras = %d\n lambda(x) is WRONG\n",count,no_eras); count = -1; goto finish; } #if DEBUG >= 2 printf("\n Erasure positions as determined by roots of Eras Loc Poly:\n"); for (i = 0; i < count; i++) printf("%d ", loc[i]); printf("\n"); #endif #endif } for(i=0;i<NROOTS+1;i++) b[i] = INDEX_OF[lambda[i]]; /* * Begin Berlekamp-Massey algorithm to determine error+erasure * locator polynomial */ r = no_eras; el = no_eras; while (++r <= NROOTS) { /* r is the step number */ /* Compute discrepancy at the r-th step in poly-form */ discr_r = 0; for (i = 0; i < r; i++){ if ((lambda[i] != 0) && (s[r-i-1] != A0)) { discr_r ^= ALPHA_TO[MODNN(INDEX_OF[lambda[i]] + s[r-i-1])]; } } discr_r = INDEX_OF[discr_r]; /* Index form */ if (discr_r == A0) { /* 2 lines below: B(x) <-- x*B(x) */ memmove(&b[1],b,NROOTS*sizeof(b[0])); b[0] = A0; } else { /* 7 lines below: T(x) <-- lambda(x) - discr_r*x*b(x) */ t[0] = lambda[0]; for (i = 0 ; i < NROOTS; i++) { if(b[i] != A0) t[i+1] = lambda[i+1] ^ ALPHA_TO[MODNN(discr_r + b[i])]; else t[i+1] = lambda[i+1]; } if (2 * el <= r + no_eras - 1) { el = r + no_eras - el; /* * 2 lines below: B(x) <-- inv(discr_r) * * lambda(x) */ for (i = 0; i <= NROOTS; i++) b[i] = (lambda[i] == 0) ? A0 : MODNN(INDEX_OF[lambda[i]] - discr_r + NN); } else { /* 2 lines below: B(x) <-- x*B(x) */ memmove(&b[1],b,NROOTS*sizeof(b[0])); b[0] = A0; } memcpy(lambda,t,(NROOTS+1)*sizeof(t[0])); } } /* Convert lambda to index form and compute deg(lambda(x)) */ deg_lambda = 0; for(i=0;i<NROOTS+1;i++){ lambda[i] = INDEX_OF[lambda[i]]; if(lambda[i] != A0) deg_lambda = i; } /* Find roots of the error+erasure locator polynomial by Chien search */ memcpy(&reg[1],&lambda[1],NROOTS*sizeof(reg[0])); count = 0; /* Number of roots of lambda(x) */ for (i = 1,k=IPRIM-1; i <= NN; i++,k = MODNN(k+IPRIM)) { q = 1; /* lambda[0] is always 0 */ for (j = deg_lambda; j > 0; j--){ if (reg[j] != A0) { reg[j] = MODNN(reg[j] + j); q ^= ALPHA_TO[reg[j]]; } } if (q != 0) continue; /* Not a root */ /* store root (index-form) and error location number */ #if DEBUG>=2 printf("count %d root %d loc %d\n",count,i,k); #endif root[count] = i; loc[count] = k; /* If we've already found max possible roots, * abort the search to save time */ if(++count == deg_lambda) break; } if (deg_lambda != count) { /* * deg(lambda) unequal to number of roots => uncorrectable * error detected */ count = -1; goto finish; } /* * Compute err+eras evaluator poly omega(x) = s(x)*lambda(x) (modulo * x**NROOTS). in index form. Also find deg(omega). */ deg_omega = deg_lambda-1; for (i = 0; i <= deg_omega;i++){ tmp = 0; for(j=i;j >= 0; j--){ if ((s[i - j] != A0) && (lambda[j] != A0)) tmp ^= ALPHA_TO[MODNN(s[i - j] + lambda[j])]; } omega[i] = INDEX_OF[tmp]; } /* * Compute error values in poly-form. num1 = omega(inv(X(l))), num2 = * inv(X(l))**(FCR-1) and den = lambda_pr(inv(X(l))) all in poly-form */ for (j = count-1; j >=0; j--) { num1 = 0; for (i = deg_omega; i >= 0; i--) { if (omega[i] != A0) num1 ^= ALPHA_TO[MODNN(omega[i] + i * root[j])]; } num2 = ALPHA_TO[MODNN(root[j] * (FCR - 1) + NN)]; den = 0; /* lambda[i+1] for i even is the formal derivative lambda_pr of lambda[i] */ for (i = min(deg_lambda,NROOTS-1) & ~1; i >= 0; i -=2) { if(lambda[i+1] != A0) den ^= ALPHA_TO[MODNN(lambda[i+1] + i * root[j])]; } #if DEBUG >= 1 if (den == 0) { printf("\n ERROR: denominator = 0\n"); count = -1; goto finish; } #endif /* Apply error to data */ if (num1 != 0 && loc[j] >= PAD) { data[loc[j]-PAD] ^= ALPHA_TO[MODNN(INDEX_OF[num1] + INDEX_OF[num2] + NN - INDEX_OF[den])]; } } finish: if(eras_pos != NULL){ for(i=0;i<count;i++) eras_pos[i] = loc[i]; } return count; }
lgpl-2.1
okyfirmansyah/sofia-sip
libsofia-sip-ua/su/su_log.c
8
6699
/* * This file is part of the Sofia-SIP package * * Copyright (C) 2005 Nokia Corporation. * * Contact: Pekka Pessi <pekka.pessi@nokia.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * */ /**@ingroup su_log * @CFILE su_log.c * * Implementation of generic logging interface. * * @author Pekka Pessi <Pekka.Pessi@nokia.com> * * @date Created: Fri Feb 23 17:30:13 2001 ppessi */ #include "config.h" #include <sofia-sip/su_log.h> #include <sofia-sip/su_errno.h> #include <stdio.h> #include <stdarg.h> #include <stdlib.h> #include <assert.h> #if SU_HAVE_PTHREADS #include <pthread.h> #define SU_LOG_IS_INIT(log) pthread_mutex_trylock((log)->log_init) #define SU_LOG_DO_INIT(log) #define SU_LOG_LOCK(log) pthread_mutex_lock((log)->log_lock) #define SU_LOG_UNLOCK(log) pthread_mutex_unlock((log)->log_lock) #else #define SU_LOG_IS_INIT(log) ((log)->log_init) #define SU_LOG_DO_INIT(log) ((log)->log_init = 1) #define SU_LOG_LOCK(log) #define SU_LOG_UNLOCK(log) #endif /**@defgroup su_log Logging Interface * * Generic logging interface. * * The @b su_log submodule contains a generic logging interface. The * interface provides means for redirecting the log and filtering log * messages based on message priority. * * @sa @ref debug_logs, <sofia-sip/su_log.h>, * su_llog(), su_vllog(), #su_log_t, #SU_DEBUG, * SU_DEBUG_0(), SU_DEBUG_1(), SU_DEBUG_2(), SU_DEBUG_3(), SU_DEBUG_5(), * SU_DEBUG_7(), SU_DEBUG_9() */ /** Log message of socket error @errcode at level 0. */ void su_perror2(const char *s, int errcode) { su_log("%s: %s\n", s, su_strerror(errcode)); } /** Log socket error message at level 0. */ void su_perror(const char *s) { su_perror2(s, su_errno()); } /** Log a message to default log. * * This function is a replacement for printf(). * * Messages are always logged to the default log. */ void su_log(char const *fmt, ...) { va_list ap; va_start(ap, fmt); su_vllog(su_log_default, 0, fmt, ap); va_end(ap); } /** Log a message with level. * * @note This function is used mainly by SU_DEBUG_n() macros. */ void su_llog(su_log_t *log, unsigned level, char const *fmt, ...) { va_list ap; va_start(ap, fmt); su_vllog(log, level, fmt, ap); va_end(ap); } /** Log a message with level (stdarg version). */ void su_vllog(su_log_t *log, unsigned level, char const *fmt, va_list ap) { su_logger_f *logger; void *stream; assert(log); if (!log->log_init) su_log_init(log); if (log->log_init > 1 ? level > log->log_level : level > su_log_default->log_level) return; logger = log->log_logger; stream = log->log_stream; if (!logger) { logger = su_log_default->log_logger; stream = su_log_default->log_stream; } if (logger) logger(stream, fmt, ap); } static char const not_initialized[1]; static char const *explicitly_initialized = not_initialized; /** Initialize a log */ void su_log_init(su_log_t *log) { char *env; if (log->log_init) return; if (explicitly_initialized == not_initialized) explicitly_initialized = getenv("SHOW_DEBUG_LEVELS"); if (log != su_log_default && !su_log_default->log_init) su_log_init(su_log_default); if (log->log_env && (env = getenv(log->log_env))) { int level = atoi(env); /* Why? */ /* if (level == 0) level = 1; */ log->log_level = level; log->log_init = 2; if (explicitly_initialized) su_llog(log, 0, "%s: initialized log to level %u (%s=%s)\n", log->log_name, log->log_level, log->log_env, env); } else { log->log_level = log->log_default; log->log_init = 1; if (explicitly_initialized) { if (log != su_log_default) su_llog(log, 0, "%s: logging at default level %u\n", log->log_name, su_log_default->log_level); else su_llog(log, 0, "%s: initialized log to level %u (default)\n", log->log_name, log->log_level); } } } /**Redirect a log. * * The function su_log_redirect() redirects the su_log() output to * @a logger function. The @a logger function has following prototype: * * @code * void logger(void *logarg, char const *format, va_list ap); * @endcode * * If @a logger is NULL, the default logger will be used. If @a log is NULL, * the default logger is changed. */ void su_log_redirect(su_log_t *log, su_logger_f *logger, void *logarg) { if (log == NULL) log = su_log_default; /* XXX - locking ? */ log->log_logger = logger; log->log_stream = logarg; } /** Set log level. * * The function su_log_set_level() sets the logging level. The log events * have certain level (0..9); if logging level is lower than the level of * the event, the log message is ignored. * * If @a log is NULL, the default log level is changed. */ void su_log_set_level(su_log_t *log, unsigned level) { if (log == NULL) log = su_log_default; log->log_level = level; log->log_init = 2; if (explicitly_initialized == not_initialized) explicitly_initialized = getenv("SHOW_DEBUG_LEVELS"); if (explicitly_initialized) su_llog(log, 0, "%s: set log to level %u\n", log->log_name, log->log_level); } /** Set log level. * * The function su_log_soft_set_level() sets the logging level if it is not * already set, or the environment variable controlling the log level is not * set. * * The log events have certain level (0..9); if logging level is lower than * the level of the event, the log message is ignored. * * If @a log is NULL, the default log level is changed. */ void su_log_soft_set_level(su_log_t *log, unsigned level) { if (log == NULL) log = su_log_default; if (log->log_init == 1) return; if (log->log_env && getenv(log->log_env)) { su_log_init(log); } else { log->log_level = level; log->log_init = 2; if (explicitly_initialized == not_initialized) explicitly_initialized = getenv("SHOW_DEBUG_LEVELS"); if (explicitly_initialized) su_llog(log, 0, "%s: soft set log to level %u\n", log->log_name, log->log_level); } }
lgpl-2.1
bbockelm/root-historical
interpreter/llvm/src/tools/clang/test/CodeGen/inline.c
8
3826
// RUN: echo "GNU89 tests:" // RUN: %clang %s -O1 -emit-llvm -S -o %t -std=gnu89 // RUN: grep "define available_externally i32 @ei()" %t // RUN: grep "define i32 @foo()" %t // RUN: grep "define i32 @bar()" %t // RUN: grep "define void @unreferenced1()" %t // RUN: not grep unreferenced2 %t // RUN: grep "define void @gnu_inline()" %t // RUN: grep "define available_externally void @gnu_ei_inline()" %t // RUN: grep "define i32 @test1" %t // RUN: grep "define i32 @test2" %t // RUN: grep "define void @test3()" %t // RUN: grep "define available_externally i32 @test4" %t // RUN: grep "define available_externally i32 @test5" %t // RUN: grep "define i32 @test6" %t // RUN: grep "define void @test7" %t // RUN: grep "define i.. @strlcpy" %t // RUN: not grep test9 %t // RUN: grep "define void @testA" %t // RUN: grep "define void @testB" %t // RUN: grep "define void @testC" %t // RUN: echo "C99 tests:" // RUN: %clang %s -O1 -emit-llvm -S -o %t -std=gnu99 // RUN: grep "define i32 @ei()" %t // RUN: grep "define available_externally i32 @foo()" %t // RUN: grep "define i32 @bar()" %t // RUN: not grep unreferenced1 %t // RUN: grep "define void @unreferenced2()" %t // RUN: grep "define void @gnu_inline()" %t // RUN: grep "define available_externally void @gnu_ei_inline()" %t // RUN: grep "define i32 @test1" %t // RUN: grep "define i32 @test2" %t // RUN: grep "define void @test3" %t // RUN: grep "define available_externally i32 @test4" %t // RUN: grep "define available_externally i32 @test5" %t // RUN: grep "define i32 @test6" %t // RUN: grep "define void @test7" %t // RUN: grep "define available_externally i.. @strlcpy" %t // RUN: grep "define void @test9" %t // RUN: grep "define void @testA" %t // RUN: grep "define void @testB" %t // RUN: grep "define void @testC" %t // RUN: echo "C++ tests:" // RUN: %clang -x c++ %s -O1 -emit-llvm -S -o %t -std=c++98 // RUN: grep "define linkonce_odr i32 @_Z2eiv()" %t // RUN: grep "define linkonce_odr i32 @_Z3foov()" %t // RUN: grep "define i32 @_Z3barv()" %t // RUN: not grep unreferenced %t // RUN: grep "define void @_Z10gnu_inlinev()" %t // RUN: grep "define available_externally void @_Z13gnu_ei_inlinev()" %t extern __inline int ei() { return 123; } __inline int foo() { return ei(); } int bar() { return foo(); } __inline void unreferenced1() {} extern __inline void unreferenced2() {} __inline __attribute((__gnu_inline__)) void gnu_inline() {} // PR3988 extern __inline __attribute__((gnu_inline)) void gnu_ei_inline() {} void (*P)() = gnu_ei_inline; // <rdar://problem/6818429> int test1(); __inline int test1() { return 4; } __inline int test2() { return 5; } __inline int test2(); int test2(); void test_test1() { test1(); } void test_test2() { test2(); } // PR3989 extern __inline void test3() __attribute__((gnu_inline)); __inline void __attribute__((gnu_inline)) test3() {} extern int test4(void); extern __inline __attribute__ ((__gnu_inline__)) int test4(void) { return 0; } void test_test4() { test4(); } extern __inline int test5(void) __attribute__ ((__gnu_inline__)); extern __inline int __attribute__ ((__gnu_inline__)) test5(void) { return 0; } void test_test5() { test5(); } // PR10233 __inline int test6() { return 0; } extern int test6(); // No PR#, but this once crashed clang in C99 mode due to buggy extern inline // redeclaration detection. void test7() { } void test7(); // PR11062; the fact that the function is named strlcpy matters here. inline __typeof(sizeof(int)) strlcpy(char *dest, const char *src, __typeof(sizeof(int)) size) { return 3; } void test8() { strlcpy(0,0,0); } // PR10657; the test crashed in C99 mode extern inline void test9() { } void test9(); inline void testA() {} void testA(); void testB(); inline void testB() {} extern void testB(); extern inline void testC() {} inline void testC();
lgpl-2.1
rversteegen/commandergenius
project/jni/lzo2/src/lzo1.c
8
19709
/* lzo1.c -- implementation of the LZO1 algorithm This file is part of the LZO real-time data compression library. Copyright (C) 2010 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2009 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2008 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2007 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2006 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2005 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2004 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2003 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2002 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2001 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2000 Markus Franz Xaver Johannes Oberhumer Copyright (C) 1999 Markus Franz Xaver Johannes Oberhumer Copyright (C) 1998 Markus Franz Xaver Johannes Oberhumer Copyright (C) 1997 Markus Franz Xaver Johannes Oberhumer Copyright (C) 1996 Markus Franz Xaver Johannes Oberhumer All Rights Reserved. The LZO library is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. The LZO library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with the LZO library; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Markus F.X.J. Oberhumer <markus@oberhumer.com> http://www.oberhumer.com/opensource/lzo/ */ #include "lzo_conf.h" #include "lzo/lzo1.h" /*********************************************************************** // The next two defines can be changed to customize LZO1. // The default version is LZO1-5/1. ************************************************************************/ /* run bits (3 - 5) - the compressor and the decompressor * must use the same value. */ #if !defined(RBITS) # define RBITS 5 #endif /* compression level (1 - 9) - this only affects the compressor. * 1 is fastest, 9 is best compression ratio */ #if !defined(CLEVEL) # define CLEVEL 1 /* fastest by default */ #endif /* check configuration */ #if (RBITS < 3 || RBITS > 5) # error "invalid RBITS" #endif #if (CLEVEL < 1 || CLEVEL > 9) # error "invalid CLEVEL" #endif /*********************************************************************** // You should not have to change anything below this line. ************************************************************************/ /* Format of the marker byte 76543210 -------- 00000000 a long run (a 'R0' run) - there are short and long R0 runs 000rrrrr a short run with len r mmmooooo a short match (len = 2+m, o = offset low bits) 111ooooo a long match (o = offset low bits) */ #define RSIZE (1 << RBITS) #define RMASK (RSIZE - 1) #define OBITS RBITS /* offset and run-length use same bits */ #define OSIZE (1 << OBITS) #define OMASK (OSIZE - 1) #define MBITS (8 - OBITS) #define MSIZE (1 << MBITS) #define MMASK (MSIZE - 1) /* sanity checks */ #if (OBITS < 3 || OBITS > 5) # error "invalid OBITS" #endif #if (MBITS < 3 || MBITS > 5) # error "invalid MBITS" #endif /*********************************************************************** // some macros to improve readability ************************************************************************/ /* Minimum len of a match */ #define MIN_MATCH 3 #define THRESHOLD (MIN_MATCH - 1) /* Minimum len of match coded in 2 bytes */ #define MIN_MATCH_SHORT MIN_MATCH /* Maximum len of match coded in 2 bytes */ #define MAX_MATCH_SHORT (THRESHOLD + (MSIZE - 2)) /* MSIZE - 2: 0 is used to indicate runs, * MSIZE-1 is used to indicate a long match */ /* Minimum len of match coded in 3 bytes */ #define MIN_MATCH_LONG (MAX_MATCH_SHORT + 1) /* Maximum len of match coded in 3 bytes */ #define MAX_MATCH_LONG (MIN_MATCH_LONG + 255) /* Maximum offset of a match */ #define MAX_OFFSET (1 << (8 + OBITS)) /* RBITS | MBITS MIN THR. MSIZE MAXS MINL MAXL MAXO R0MAX R0FAST ======+=============================================================== 3 | 5 3 2 32 32 33 288 2048 263 256 4 | 4 3 2 16 16 17 272 4096 271 264 5 | 3 3 2 8 8 9 264 8192 287 280 */ /*********************************************************************** // internal configuration // all of these affect compression only ************************************************************************/ /* choose the hashing strategy */ #ifndef LZO_HASH #define LZO_HASH LZO_HASH_LZO_INCREMENTAL_A #endif #define D_INDEX1(d,p) d = DM(DMUL(0x21,DX2(p,5,5)) >> 5) #define D_INDEX2(d,p) d = d ^ D_MASK #define DBITS (8 + RBITS) #include "lzo_dict.h" #define DVAL_LEN DVAL_LOOKAHEAD /*********************************************************************** // get algorithm info, return memory required for compression ************************************************************************/ LZO_EXTERN(lzo_uint) lzo1_info ( int *rbits, int *clevel ); LZO_PUBLIC(lzo_uint) lzo1_info ( int *rbits, int *clevel ) { if (rbits) *rbits = RBITS; if (clevel) *clevel = CLEVEL; return D_SIZE * lzo_sizeof(lzo_bytep); } /*********************************************************************** // decode a R0 literal run (a long run) ************************************************************************/ #define R0MIN (RSIZE) /* Minimum len of R0 run of literals */ #define R0MAX (R0MIN + 255) /* Maximum len of R0 run of literals */ #define R0FAST (R0MAX & ~7u) /* R0MAX aligned to 8 byte boundary */ #if (R0MAX - R0FAST != 7) || ((R0FAST & 7) != 0) # error "something went wrong" #endif /* 7 special codes from R0FAST+1 .. R0MAX * these codes mean long R0 runs with lengths * 512, 1024, 2048, 4096, 8192, 16384, 32768 */ /*********************************************************************** // LZO1 decompress a block of data. // // Could be easily translated into assembly code. ************************************************************************/ LZO_PUBLIC(int) lzo1_decompress ( const lzo_bytep in , lzo_uint in_len, lzo_bytep out, lzo_uintp out_len, lzo_voidp wrkmem ) { lzo_bytep op; const lzo_bytep ip; const lzo_bytep const ip_end = in + in_len; lzo_uint t; LZO_UNUSED(wrkmem); op = out; ip = in; while (ip < ip_end) { t = *ip++; /* get marker */ if (t < R0MIN) /* a literal run */ { if (t == 0) /* a R0 literal run */ { t = *ip++; if (t >= R0FAST - R0MIN) /* a long R0 run */ { t -= R0FAST - R0MIN; if (t == 0) t = R0FAST; else { #if 0 t = 256u << ((unsigned) t); #else /* help the optimizer */ lzo_uint tt = 256; do tt <<= 1; while (--t > 0); t = tt; #endif } MEMCPY8_DS(op,ip,t); continue; } t += R0MIN; } MEMCPY_DS(op,ip,t); } else /* a match */ { lzo_uint tt; /* get match offset */ const lzo_bytep m_pos = op - 1; m_pos -= (lzo_uint)(t & OMASK) | (((lzo_uint) *ip++) << OBITS); /* get match len */ if (t >= ((MSIZE - 1) << OBITS)) /* all m-bits set */ tt = (MIN_MATCH_LONG - THRESHOLD) + *ip++; /* a long match */ else tt = t >> OBITS; /* a short match */ assert(m_pos >= out); assert(m_pos < op); /* a half unrolled loop */ *op++ = *m_pos++; *op++ = *m_pos++; MEMCPY_DS(op,m_pos,tt); } } *out_len = pd(op, out); /* the next line is the only check in the decompressor ! */ return (ip == ip_end ? LZO_E_OK : (ip < ip_end ? LZO_E_INPUT_NOT_CONSUMED : LZO_E_INPUT_OVERRUN)); } /*********************************************************************** // code a literal run ************************************************************************/ static #if LZO_ARCH_AVR __lzo_noinline #endif lzo_bytep store_run(lzo_bytep op, const lzo_bytep ii, lzo_uint r_len) { assert(r_len > 0); /* code a long R0 run */ if (r_len >= 512) { unsigned r_bits = 7; /* 256 << 7 == 32768 */ do { while (r_len >= (256u << r_bits)) { r_len -= (256u << r_bits); *op++ = 0; *op++ = LZO_BYTE((R0FAST - R0MIN) + r_bits); MEMCPY8_DS(op, ii, (256u << r_bits)); } } while (--r_bits > 0); } while (r_len >= R0FAST) { r_len -= R0FAST; *op++ = 0; *op++ = R0FAST - R0MIN; MEMCPY8_DS(op, ii, R0FAST); } if (r_len >= R0MIN) { /* code a short R0 run */ *op++ = 0; *op++ = LZO_BYTE(r_len - R0MIN); MEMCPY_DS(op, ii, r_len); } else if (r_len > 0) { /* code a 'normal' run */ *op++ = LZO_BYTE(r_len); MEMCPY_DS(op, ii, r_len); } assert(r_len == 0); return op; } /*********************************************************************** // LZO1 compress a block of data. // // Could be translated into assembly code without too much effort. // // I apologize for the spaghetti code, but it really helps the optimizer. ************************************************************************/ static int do_compress ( const lzo_bytep in , lzo_uint in_len, lzo_bytep out, lzo_uintp out_len, lzo_voidp wrkmem ) { const lzo_bytep ip; #if defined(__LZO_HASH_INCREMENTAL) lzo_xint dv; #endif lzo_bytep op; const lzo_bytep m_pos; const lzo_bytep const ip_end = in+in_len - DVAL_LEN - MIN_MATCH_LONG; const lzo_bytep const in_end = in+in_len - DVAL_LEN; const lzo_bytep ii; lzo_dict_p const dict = (lzo_dict_p) wrkmem; #if !defined(NDEBUG) const lzo_bytep m_pos_sav; #endif op = out; ip = in; ii = ip; /* point to start of literal run */ if (in_len <= MIN_MATCH_LONG + DVAL_LEN + 1) goto the_end; /* init dictionary */ #if defined(LZO_DETERMINISTIC) BZERO8_PTR(wrkmem,sizeof(lzo_dict_t),D_SIZE); #endif DVAL_FIRST(dv,ip); UPDATE_D(dict,0,dv,ip,in); ip++; DVAL_NEXT(dv,ip); do { LZO_DEFINE_UNINITIALIZED_VAR(lzo_uint, m_off, 0); lzo_uint dindex; DINDEX1(dindex,ip); GINDEX(m_pos,m_off,dict,dindex,in); if (LZO_CHECK_MPOS(m_pos,m_off,in,ip,MAX_OFFSET)) goto literal; if (m_pos[0] == ip[0] && m_pos[1] == ip[1] && m_pos[2] == ip[2]) goto match; DINDEX2(dindex,ip); GINDEX(m_pos,m_off,dict,dindex,in); if (LZO_CHECK_MPOS(m_pos,m_off,in,ip,MAX_OFFSET)) goto literal; if (m_pos[0] == ip[0] && m_pos[1] == ip[1] && m_pos[2] == ip[2]) goto match; goto literal; literal: UPDATE_I(dict,0,dindex,ip,in); if (++ip >= ip_end) break; continue; match: UPDATE_I(dict,0,dindex,ip,in); #if !defined(NDEBUG) && defined(LZO_DICT_USE_PTR) m_pos_sav = m_pos; #endif m_pos += 3; { /* we have found a match (of at least length 3) */ #if !defined(NDEBUG) && !defined(LZO_DICT_USE_PTR) assert((m_pos_sav = ip - m_off) == (m_pos - 3)); #endif /* 1) store the current literal run */ if (pd(ip,ii) > 0) { lzo_uint t = pd(ip,ii); #if 1 /* OPTIMIZED: inline the copying of a short run */ if (t < R0MIN) { *op++ = LZO_BYTE(t); MEMCPY_DS(op, ii, t); } else #endif op = store_run(op,ii,t); } /* 2a) compute match len */ ii = ip; /* point to start of current match */ /* we already matched MIN_MATCH bytes, * m_pos also already advanced MIN_MATCH bytes */ ip += MIN_MATCH; assert(m_pos < ip); /* try to match another MIN_MATCH_LONG - MIN_MATCH bytes * to see if we get a long match */ #define PS *m_pos++ != *ip++ #if (MIN_MATCH_LONG - MIN_MATCH == 2) /* MBITS == 2 */ if (PS || PS) #elif (MIN_MATCH_LONG - MIN_MATCH == 6) /* MBITS == 3 */ if (PS || PS || PS || PS || PS || PS) #elif (MIN_MATCH_LONG - MIN_MATCH == 14) /* MBITS == 4 */ if (PS || PS || PS || PS || PS || PS || PS || PS || PS || PS || PS || PS || PS || PS) #elif (MIN_MATCH_LONG - MIN_MATCH == 30) /* MBITS == 5 */ if (PS || PS || PS || PS || PS || PS || PS || PS || PS || PS || PS || PS || PS || PS || PS || PS || PS || PS || PS || PS || PS || PS || PS || PS || PS || PS || PS || PS || PS || PS) #else # error "MBITS not yet implemented" #endif { lzo_uint m_len; /* 2b) code a short match */ assert(pd(ip,m_pos) == m_off); --ip; /* ran one too far, point back to non-match */ m_len = pd(ip, ii); assert(m_len >= MIN_MATCH_SHORT); assert(m_len <= MAX_MATCH_SHORT); assert(m_off > 0); assert(m_off <= MAX_OFFSET); assert(ii-m_off == m_pos_sav); assert(lzo_memcmp(m_pos_sav,ii,m_len) == 0); --m_off; /* code short match len + low offset bits */ *op++ = LZO_BYTE(((m_len - THRESHOLD) << OBITS) | (m_off & OMASK)); /* code high offset bits */ *op++ = LZO_BYTE(m_off >> OBITS); /* 2c) Insert phrases (beginning with ii+1) into the dictionary. */ #define SI /* nothing */ #define DI ++ii; DVAL_NEXT(dv,ii); UPDATE_D(dict,0,dv,ii,in); #define XI assert(ii < ip); ii = ip; DVAL_FIRST(dv,(ip)); #if (CLEVEL == 9) || (CLEVEL >= 7 && MBITS <= 4) || (CLEVEL >= 5 && MBITS <= 3) /* Insert the whole match (ii+1)..(ip-1) into dictionary. */ ++ii; do { DVAL_NEXT(dv,ii); UPDATE_D(dict,0,dv,ii,in); } while (++ii < ip); DVAL_NEXT(dv,ii); assert(ii == ip); DVAL_ASSERT(dv,ip); #elif (CLEVEL >= 3) SI DI DI XI #elif (CLEVEL >= 2) SI DI XI #else XI #endif } else { /* we've found a long match - see how far we can still go */ const lzo_bytep end; lzo_uint m_len; assert(ip <= in_end); assert(ii == ip - MIN_MATCH_LONG); if (pd(in_end,ip) <= (MAX_MATCH_LONG - MIN_MATCH_LONG)) end = in_end; else { end = ip + (MAX_MATCH_LONG - MIN_MATCH_LONG); assert(end < in_end); } while (ip < end && *m_pos == *ip) m_pos++, ip++; assert(ip <= in_end); /* 2b) code the long match */ m_len = pd(ip, ii); assert(m_len >= MIN_MATCH_LONG); assert(m_len <= MAX_MATCH_LONG); assert(m_off > 0); assert(m_off <= MAX_OFFSET); assert(ii-m_off == m_pos_sav); assert(lzo_memcmp(m_pos_sav,ii,m_len) == 0); assert(pd(ip,m_pos) == m_off); --m_off; /* code long match flag + low offset bits */ *op++ = LZO_BYTE(((MSIZE - 1) << OBITS) | (m_off & OMASK)); /* code high offset bits */ *op++ = LZO_BYTE(m_off >> OBITS); /* code match len */ *op++ = LZO_BYTE(m_len - MIN_MATCH_LONG); /* 2c) Insert phrases (beginning with ii+1) into the dictionary. */ #if (CLEVEL == 9) /* Insert the whole match (ii+1)..(ip-1) into dictionary. */ /* This is not recommended because it is slow. */ ++ii; do { DVAL_NEXT(dv,ii); UPDATE_D(dict,0,dv,ii,in); } while (++ii < ip); DVAL_NEXT(dv,ii); assert(ii == ip); DVAL_ASSERT(dv,ip); #elif (CLEVEL >= 8) SI DI DI DI DI DI DI DI DI XI #elif (CLEVEL >= 7) SI DI DI DI DI DI DI DI XI #elif (CLEVEL >= 6) SI DI DI DI DI DI DI XI #elif (CLEVEL >= 5) SI DI DI DI DI XI #elif (CLEVEL >= 4) SI DI DI DI XI #elif (CLEVEL >= 3) SI DI DI XI #elif (CLEVEL >= 2) SI DI XI #else XI #endif } /* ii now points to the start of next literal run */ assert(ii == ip); } } while (ip < ip_end); the_end: assert(ip <= in_end); #if defined(LZO_RETURN_IF_NOT_COMPRESSIBLE) /* return -1 if op == out to indicate that we * couldn't compress and didn't copy anything. */ if (op == out) { *out_len = 0; return LZO_E_NOT_COMPRESSIBLE; } #endif /* store the final literal run */ if (pd(in_end+DVAL_LEN,ii) > 0) op = store_run(op,ii,pd(in_end+DVAL_LEN,ii)); *out_len = pd(op, out); return 0; /* compression went ok */ } /*********************************************************************** // compress public entry point. ************************************************************************/ LZO_PUBLIC(int) lzo1_compress ( const lzo_bytep in , lzo_uint in_len, lzo_bytep out, lzo_uintp out_len, lzo_voidp wrkmem ) { int r = LZO_E_OK; /* don't try to compress a block that's too short */ if (in_len == 0) *out_len = 0; else if (in_len <= MIN_MATCH_LONG + DVAL_LEN + 1) { #if defined(LZO_RETURN_IF_NOT_COMPRESSIBLE) r = LZO_E_NOT_COMPRESSIBLE; #else *out_len = pd(store_run(out,in,in_len), out); #endif } else r = do_compress(in,in_len,out,out_len,wrkmem); return r; } /* vi:ts=4:et */
lgpl-2.1
RobertoMalatesta/libwebsockets
lib/client-handshake.c
11
12139
#include "private-libwebsockets.h" struct libwebsocket *libwebsocket_client_connect_2( struct libwebsocket_context *context, struct libwebsocket *wsi ) { struct libwebsocket_pollfd pfd; #ifdef LWS_USE_IPV6 struct sockaddr_in6 server_addr6; struct sockaddr_in6 client_addr6; struct addrinfo hints, *result; #endif struct sockaddr_in server_addr4; struct sockaddr_in client_addr4; struct sockaddr *v; int n; int plen = 0; const char *ads; lwsl_client("libwebsocket_client_connect_2\n"); /* * proxy? */ if (context->http_proxy_port) { plen = sprintf((char *)context->service_buffer, "CONNECT %s:%u HTTP/1.0\x0d\x0a" "User-agent: libwebsockets\x0d\x0a" /*Proxy-authorization: basic aGVsbG86d29ybGQ= */ "\x0d\x0a", lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_PEER_ADDRESS), wsi->u.hdr.ah->c_port); ads = context->http_proxy_address; #ifdef LWS_USE_IPV6 if (LWS_IPV6_ENABLED(context)) server_addr6.sin6_port = htons(context->http_proxy_port); else #endif server_addr4.sin_port = htons(context->http_proxy_port); } else { ads = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_PEER_ADDRESS); #ifdef LWS_USE_IPV6 if (LWS_IPV6_ENABLED(context)) server_addr6.sin6_port = htons(wsi->u.hdr.ah->c_port); else #endif server_addr4.sin_port = htons(wsi->u.hdr.ah->c_port); } /* * prepare the actual connection (to the proxy, if any) */ lwsl_client("libwebsocket_client_connect_2: address %s\n", ads); #ifdef LWS_USE_IPV6 if (LWS_IPV6_ENABLED(context)) { memset(&hints, 0, sizeof(struct addrinfo)); n = getaddrinfo(ads, NULL, &hints, &result); if (n) { #ifdef _WIN32 lwsl_err("getaddrinfo: %ls\n", gai_strerrorW(n)); #else lwsl_err("getaddrinfo: %s\n", gai_strerror(n)); #endif goto oom4; } server_addr6.sin6_family = AF_INET6; switch (result->ai_family) { case AF_INET: /* map IPv4 to IPv6 */ bzero((char *)&server_addr6.sin6_addr, sizeof(struct in6_addr)); server_addr6.sin6_addr.s6_addr[10] = 0xff; server_addr6.sin6_addr.s6_addr[11] = 0xff; memcpy(&server_addr6.sin6_addr.s6_addr[12], &((struct sockaddr_in *)result->ai_addr)->sin_addr, sizeof(struct in_addr)); break; case AF_INET6: memcpy(&server_addr6.sin6_addr, &((struct sockaddr_in6 *)result->ai_addr)->sin6_addr, sizeof(struct in6_addr)); break; default: lwsl_err("Unknown address family\n"); freeaddrinfo(result); goto oom4; } freeaddrinfo(result); } else #endif { struct addrinfo ai, *res, *result; void *p = NULL; memset (&ai, 0, sizeof ai); ai.ai_family = PF_UNSPEC; ai.ai_socktype = SOCK_STREAM; ai.ai_flags = AI_CANONNAME; if (getaddrinfo(ads, NULL, &ai, &result)) goto oom4; res = result; while (!p && res) { switch (res->ai_family) { case AF_INET: p = &((struct sockaddr_in *)res->ai_addr)->sin_addr; break; } res = res->ai_next; } if (!p) { freeaddrinfo(result); goto oom4; } server_addr4.sin_family = AF_INET; server_addr4.sin_addr = *((struct in_addr *)p); bzero(&server_addr4.sin_zero, 8); freeaddrinfo(result); } if (wsi->sock < 0) { #ifdef LWS_USE_IPV6 if (LWS_IPV6_ENABLED(context)) wsi->sock = socket(AF_INET6, SOCK_STREAM, 0); else #endif wsi->sock = socket(AF_INET, SOCK_STREAM, 0); if (wsi->sock < 0) { lwsl_warn("Unable to open socket\n"); goto oom4; } if (lws_plat_set_socket_options(context, wsi->sock)) { lwsl_err("Failed to set wsi socket options\n"); compatible_close(wsi->sock); goto oom4; } wsi->mode = LWS_CONNMODE_WS_CLIENT_WAITING_CONNECT; lws_libev_accept(context, wsi, wsi->sock); insert_wsi_socket_into_fds(context, wsi); libwebsocket_set_timeout(wsi, PENDING_TIMEOUT_AWAITING_CONNECT_RESPONSE, AWAITING_TIMEOUT); #ifdef LWS_USE_IPV6 if (LWS_IPV6_ENABLED(context)) { v = (struct sockaddr *)&client_addr6; n = sizeof(client_addr6); bzero((char *)v, n); client_addr6.sin6_family = AF_INET6; } else #endif { v = (struct sockaddr *)&client_addr4; n = sizeof(client_addr4); bzero((char *)v, n); client_addr4.sin_family = AF_INET; } if (context->iface) { if (interface_to_sa(context, context->iface, (struct sockaddr_in *)v, n) < 0) { lwsl_err("Unable to find interface %s\n", context->iface); compatible_close(wsi->sock); goto failed; } if (bind(wsi->sock, v, n) < 0) { lwsl_err("Error binding to interface %s", context->iface); compatible_close(wsi->sock); goto failed; } } } #ifdef LWS_USE_IPV6 if (LWS_IPV6_ENABLED(context)) { v = (struct sockaddr *)&server_addr6; n = sizeof(struct sockaddr_in6); } else #endif { v = (struct sockaddr *)&server_addr4; n = sizeof(struct sockaddr); } if (connect(wsi->sock, v, n) == -1 || LWS_ERRNO == LWS_EISCONN) { if (LWS_ERRNO == LWS_EALREADY || LWS_ERRNO == LWS_EINPROGRESS || LWS_ERRNO == LWS_EWOULDBLOCK) { lwsl_client("nonblocking connect retry\n"); /* * must do specifically a POLLOUT poll to hear * about the connect completion */ if (lws_change_pollfd(wsi, 0, LWS_POLLOUT)) goto oom4; lws_libev_io(context, wsi, LWS_EV_START | LWS_EV_WRITE); return wsi; } if (LWS_ERRNO != LWS_EISCONN) { lwsl_debug("Connect failed errno=%d\n", LWS_ERRNO); goto failed; } } lwsl_client("connected\n"); /* we are connected to server, or proxy */ if (context->http_proxy_port) { /* OK from now on we talk via the proxy, so connect to that */ /* * (will overwrite existing pointer, * leaving old string/frag there but unreferenced) */ if (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_PEER_ADDRESS, context->http_proxy_address)) goto failed; wsi->u.hdr.ah->c_port = context->http_proxy_port; n = send(wsi->sock, context->service_buffer, plen, MSG_NOSIGNAL); if (n < 0) { lwsl_debug("ERROR writing to proxy socket\n"); goto failed; } libwebsocket_set_timeout(wsi, PENDING_TIMEOUT_AWAITING_PROXY_RESPONSE, AWAITING_TIMEOUT); wsi->mode = LWS_CONNMODE_WS_CLIENT_WAITING_PROXY_REPLY; return wsi; } /* * provoke service to issue the handshake directly * we need to do it this way because in the proxy case, this is the * next state and executed only if and when we get a good proxy * response inside the state machine... but notice in SSL case this * may not have sent anything yet with 0 return, and won't until some * many retries from main loop. To stop that becoming endless, * cover with a timeout. */ libwebsocket_set_timeout(wsi, PENDING_TIMEOUT_SENT_CLIENT_HANDSHAKE, AWAITING_TIMEOUT); wsi->mode = LWS_CONNMODE_WS_CLIENT_ISSUE_HANDSHAKE; pfd.fd = wsi->sock; pfd.revents = LWS_POLLIN; n = libwebsocket_service_fd(context, &pfd); if (n < 0) goto failed; if (n) /* returns 1 on failure after closing wsi */ return NULL; return wsi; oom4: lws_free(wsi->u.hdr.ah); lws_free(wsi); return NULL; failed: libwebsocket_close_and_free_session(context, wsi, LWS_CLOSE_STATUS_NOSTATUS); return NULL; } /** * libwebsocket_client_connect() - Connect to another websocket server * @context: Websocket context * @address: Remote server address, eg, "myserver.com" * @port: Port to connect to on the remote server, eg, 80 * @ssl_connection: 0 = ws://, 1 = wss:// encrypted, 2 = wss:// allow self * signed certs * @path: Websocket path on server * @host: Hostname on server * @origin: Socket origin name * @protocol: Comma-separated list of protocols being asked for from * the server, or just one. The server will pick the one it * likes best. If you don't want to specify a protocol, which is * legal, use NULL here. * @ietf_version_or_minus_one: -1 to ask to connect using the default, latest * protocol supported, or the specific protocol ordinal * * This function creates a connection to a remote server */ LWS_VISIBLE struct libwebsocket * libwebsocket_client_connect(struct libwebsocket_context *context, const char *address, int port, int ssl_connection, const char *path, const char *host, const char *origin, const char *protocol, int ietf_version_or_minus_one) { struct libwebsocket *wsi; wsi = lws_zalloc(sizeof(struct libwebsocket)); if (wsi == NULL) goto bail; wsi->sock = -1; /* -1 means just use latest supported */ if (ietf_version_or_minus_one == -1) ietf_version_or_minus_one = SPEC_LATEST_SUPPORTED; wsi->ietf_spec_revision = ietf_version_or_minus_one; wsi->user_space = NULL; wsi->state = WSI_STATE_CLIENT_UNCONNECTED; wsi->protocol = NULL; wsi->pending_timeout = NO_PENDING_TIMEOUT; #ifdef LWS_OPENSSL_SUPPORT wsi->use_ssl = ssl_connection; #else if (ssl_connection) { lwsl_err("libwebsockets not configured for ssl\n"); goto bail; } #endif if (lws_allocate_header_table(wsi)) goto bail; /* * we're not necessarily in a position to action these right away, * stash them... we only need during connect phase so u.hdr is fine */ wsi->u.hdr.ah->c_port = port; if (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_PEER_ADDRESS, address)) goto bail1; /* these only need u.hdr lifetime as well */ if (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_URI, path)) goto bail1; if (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_HOST, host)) goto bail1; if (origin) if (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_ORIGIN, origin)) goto bail1; /* * this is a list of protocols we tell the server we're okay with * stash it for later when we compare server response with it */ if (protocol) if (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS, protocol)) goto bail1; wsi->protocol = &context->protocols[0]; /* * Check with each extension if it is able to route and proxy this * connection for us. For example, an extension like x-google-mux * can handle this and then we don't need an actual socket for this * connection. */ if (lws_ext_callback_for_each_extension_type(context, wsi, LWS_EXT_CALLBACK_CAN_PROXY_CLIENT_CONNECTION, (void *)address, port) > 0) { lwsl_client("libwebsocket_client_connect: ext handling conn\n"); libwebsocket_set_timeout(wsi, PENDING_TIMEOUT_AWAITING_EXTENSION_CONNECT_RESPONSE, AWAITING_TIMEOUT); wsi->mode = LWS_CONNMODE_WS_CLIENT_WAITING_EXTENSION_CONNECT; return wsi; } lwsl_client("libwebsocket_client_connect: direct conn\n"); return libwebsocket_client_connect_2(context, wsi); bail1: lws_free(wsi->u.hdr.ah); bail: lws_free(wsi); return NULL; } /** * libwebsocket_client_connect_extended() - Connect to another websocket server * @context: Websocket context * @address: Remote server address, eg, "myserver.com" * @port: Port to connect to on the remote server, eg, 80 * @ssl_connection: 0 = ws://, 1 = wss:// encrypted, 2 = wss:// allow self * signed certs * @path: Websocket path on server * @host: Hostname on server * @origin: Socket origin name * @protocol: Comma-separated list of protocols being asked for from * the server, or just one. The server will pick the one it * likes best. * @ietf_version_or_minus_one: -1 to ask to connect using the default, latest * protocol supported, or the specific protocol ordinal * @userdata: Pre-allocated user data * * This function creates a connection to a remote server */ LWS_VISIBLE struct libwebsocket * libwebsocket_client_connect_extended(struct libwebsocket_context *context, const char *address, int port, int ssl_connection, const char *path, const char *host, const char *origin, const char *protocol, int ietf_version_or_minus_one, void *userdata) { struct libwebsocket *ws = libwebsocket_client_connect(context, address, port, ssl_connection, path, host, origin, protocol, ietf_version_or_minus_one); if (ws && !ws->user_space && userdata) { ws->user_space_externally_allocated = 1; ws->user_space = userdata ; } return ws ; }
lgpl-2.1
lodle/SoapServer
third_party/poco-1.4.7p1/Foundation/testsuite/src/BinaryReaderWriterTest.cpp
13
6522
// // BinaryReaderWriterTest.cpp // // $Id: //poco/1.4/Foundation/testsuite/src/BinaryReaderWriterTest.cpp#2 $ // // Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "BinaryReaderWriterTest.h" #include "CppUnit/TestCaller.h" #include "CppUnit/TestSuite.h" #include "Poco/BinaryWriter.h" #include "Poco/BinaryReader.h" #include <sstream> using Poco::BinaryWriter; using Poco::BinaryReader; using Poco::Int32; using Poco::UInt32; using Poco::Int64; using Poco::UInt64; BinaryReaderWriterTest::BinaryReaderWriterTest(const std::string& name): CppUnit::TestCase(name) { } BinaryReaderWriterTest::~BinaryReaderWriterTest() { } void BinaryReaderWriterTest::testNative() { std::stringstream sstream; BinaryWriter writer(sstream); BinaryReader reader(sstream); write(writer); read(reader); } void BinaryReaderWriterTest::testBigEndian() { std::stringstream sstream; BinaryWriter writer(sstream, BinaryWriter::BIG_ENDIAN_BYTE_ORDER); BinaryReader reader(sstream, BinaryReader::UNSPECIFIED_BYTE_ORDER); assert (writer.byteOrder() == BinaryWriter::BIG_ENDIAN_BYTE_ORDER); writer.writeBOM(); write(writer); reader.readBOM(); assert (reader.byteOrder() == BinaryReader::BIG_ENDIAN_BYTE_ORDER); read(reader); } void BinaryReaderWriterTest::testLittleEndian() { std::stringstream sstream; BinaryWriter writer(sstream, BinaryWriter::LITTLE_ENDIAN_BYTE_ORDER); BinaryReader reader(sstream, BinaryReader::UNSPECIFIED_BYTE_ORDER); assert (writer.byteOrder() == BinaryWriter::LITTLE_ENDIAN_BYTE_ORDER); writer.writeBOM(); write(writer); reader.readBOM(); assert (reader.byteOrder() == BinaryReader::LITTLE_ENDIAN_BYTE_ORDER); read(reader); } void BinaryReaderWriterTest::write(BinaryWriter& writer) { writer << true; writer << false; writer << 'a'; writer << (short) -100; writer << (unsigned short) 50000; writer << -123456; writer << (unsigned) 123456; writer << (long) -1234567890; writer << (unsigned long) 1234567890; #if defined(POCO_HAVE_INT64) writer << (Int64) -1234567890; writer << (UInt64) 1234567890; #endif writer << (float) 1.5; writer << (double) -1.5; writer << "foo"; writer << ""; writer << std::string("bar"); writer << std::string(); writer.write7BitEncoded((UInt32) 100); writer.write7BitEncoded((UInt32) 1000); writer.write7BitEncoded((UInt32) 10000); writer.write7BitEncoded((UInt32) 100000); writer.write7BitEncoded((UInt32) 1000000); #if defined(POCO_HAVE_INT64) writer.write7BitEncoded((UInt64) 100); writer.write7BitEncoded((UInt64) 1000); writer.write7BitEncoded((UInt64) 10000); writer.write7BitEncoded((UInt64) 100000); writer.write7BitEncoded((UInt64) 1000000); #endif std::vector<int> vec; vec.push_back(1); vec.push_back(2); vec.push_back(3); writer << vec; writer.writeRaw("RAW"); } void BinaryReaderWriterTest::read(BinaryReader& reader) { bool b; reader >> b; assert (b); reader >> b; assert (!b); char c; reader >> c; assert (c == 'a'); short shortv; reader >> shortv; assert (shortv == -100); unsigned short ushortv; reader >> ushortv; assert (ushortv == 50000); int intv; reader >> intv; assert (intv == -123456); unsigned uintv; reader >> uintv; assert (uintv == 123456); long longv; reader >> longv; assert (longv == -1234567890); unsigned long ulongv; reader >> ulongv; assert (ulongv == 1234567890); #if defined(POCO_HAVE_INT64) Int64 int64v; reader >> int64v; assert (int64v == -1234567890); UInt64 uint64v; reader >> uint64v; assert (uint64v == 1234567890); #endif float floatv; reader >> floatv; assert (floatv == 1.5); double doublev; reader >> doublev; assert (doublev == -1.5); std::string str; reader >> str; assert (str == "foo"); reader >> str; assert (str == ""); reader >> str; assert (str == "bar"); reader >> str; assert (str == ""); UInt32 uint32v; reader.read7BitEncoded(uint32v); assert (uint32v == 100); reader.read7BitEncoded(uint32v); assert (uint32v == 1000); reader.read7BitEncoded(uint32v); assert (uint32v == 10000); reader.read7BitEncoded(uint32v); assert (uint32v == 100000); reader.read7BitEncoded(uint32v); assert (uint32v == 1000000); #if defined(POCO_HAVE_INT64) reader.read7BitEncoded(uint64v); assert (uint64v == 100); reader.read7BitEncoded(uint64v); assert (uint64v == 1000); reader.read7BitEncoded(uint64v); assert (uint64v == 10000); reader.read7BitEncoded(uint64v); assert (uint64v == 100000); reader.read7BitEncoded(uint64v); assert (uint64v == 1000000); #endif std::vector<int> vec; reader >> vec; assert (vec.size() == 3); assert (vec[0] == 1); assert (vec[1] == 2); assert (vec[2] == 3); reader.readRaw(3, str); assert (str == "RAW"); } void BinaryReaderWriterTest::setUp() { } void BinaryReaderWriterTest::tearDown() { } CppUnit::Test* BinaryReaderWriterTest::suite() { CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("BinaryReaderWriterTest"); CppUnit_addTest(pSuite, BinaryReaderWriterTest, testNative); CppUnit_addTest(pSuite, BinaryReaderWriterTest, testBigEndian); CppUnit_addTest(pSuite, BinaryReaderWriterTest, testLittleEndian); return pSuite; }
lgpl-2.1
cahaynes/libmesh
contrib/netcdf/4.3.1/ncgen/genchar.c
14
8601
/********************************************************************* * Copyright 2009, UCAR/Unidata * See netcdf/COPYRIGHT file for copying and redistribution conditions. *********************************************************************/ #include "includes.h" /******************************************************/ /* Code for generating char variables etc; mostly language independent */ /******************************************************/ static size_t gen_charconstant(NCConstant*, Bytebuffer*, int fillchar); static int getfillchar(Datalist* fillsrc); static void gen_chararrayr(Dimset*,int,int,Bytebuffer*,Datalist*,int,int,int); /* Matching strings to char variables, attributes, and vlen constants is challenging because it is desirable to mimic the original ncgen. The "algorithms" used there have no simple characterization (such as "abc" == {'a','b','c'}). So, this rather ugly code is kept in this file and a variety of heuristics are used to mimic ncgen. The core algorithm is as follows. 1. Assume we have a set of dimensions D1..Dn, where D1 may optionally be an Unlimited dimension. It is assumed that the sizes of the Di are all known. 2. Given a sequence of string or character constants C1..Cm, our goal is to construct a single string whose length is the cross product of D1 thru Dn. 3. For purposes of this algorithm, character constants are treated as strings of size 1. 4. Construct Dx = cross product of D1 thru D(n-1). 5. For each constant Ci, add fill characters, if necessary, so that its length is a multiple of Dn. 6. Concatenate the modified C1..Cm to produce string S. 7. Add fill characters to S to make its size be a multiple of Dn. 8. If S is longer than the Dx * Dn, then truncate and generate a warning. Two other cases: 1. character vlen: char(*) vlen_t. For this case, we simply concat all the elements. 2. character attribute. For this case, we simply concat all the elements. */ void gen_chararray(Dimset* dimset, Datalist* data, Bytebuffer* databuf, Datalist* fillsrc) { int ndims,lastunlim; int fillchar = getfillchar(fillsrc); size_t expectedsize,xproduct; size_t unitsize; ASSERT(bbLength(databuf) == 0); ndims = dimset->ndims; /* Find the last unlimited */ lastunlim = findlastunlimited(dimset); if(lastunlim < 0) lastunlim = 0; /* pretend */ /* Compute crossproduct upto the last dimension, starting at the last unlimited */ xproduct = crossproduct(dimset,lastunlim,ndims-1); if(ndims == 0) { unitsize = 1; } else if(lastunlim == ndims-1) {/* last dimension is unlimited */ unitsize = 1; } else { /* last dim is not unlimited */ unitsize = dimset->dimsyms[ndims-1]->dim.declsize; } expectedsize = (xproduct * unitsize); gen_chararrayr(dimset,0,lastunlim,databuf,data,fillchar,unitsize,expectedsize); } /* Recursive helper */ static void gen_chararrayr(Dimset* dimset, int dimindex, int lastunlimited, Bytebuffer* databuf, Datalist* data, int fillchar, int unitsize, int expectedsize) { int i; size_t dimsize = dimset->dimsyms[dimindex]->dim.declsize; if(dimindex < lastunlimited) { /* keep recursing */ for(i=0;i<dimsize;i++) { NCConstant* c = datalistith(data,i); ASSERT(islistconst(c)); gen_chararrayr(dimset,dimindex+1,lastunlimited,databuf, c->value.compoundv,fillchar,unitsize,expectedsize); } } else {/* we should be at a list of simple constants */ for(i=0;i<data->length;i++) { NCConstant* c = datalistith(data,i); ASSERT(!islistconst(c)); if(isstringable(c->nctype)) { int j; size_t constsize; constsize = gen_charconstant(c,databuf,fillchar); if(constsize % unitsize > 0) { size_t padsize = unitsize - (constsize % unitsize); for(j=0;j<padsize;j++) bbAppend(databuf,fillchar); } } else { semwarn(constline(c), "Encountered non-string and non-char constant in datalist; ignored"); } } } /* If |databuf| > expectedsize, complain: exception is zero length */ if(bbLength(databuf) == 0 && expectedsize == 1) { /* this is okay */ } else if(bbLength(databuf) > expectedsize) { semwarn(data->data[0].lineno,"character data list too long"); } else { size_t bufsize = bbLength(databuf); /* Pad to size dimproduct size */ if(bufsize % expectedsize > 0) { size_t padsize = expectedsize - (bufsize % expectedsize); for(i=0;i<padsize;i++) bbAppend(databuf,fillchar); } } } void gen_charattr(Datalist* data, Bytebuffer* databuf) { gen_charvlen(data,databuf); } void gen_charvlen(Datalist* data, Bytebuffer* databuf) { int i; NCConstant* c; ASSERT(bbLength(databuf) == 0); for(i=0;i<data->length;i++) { c = datalistith(data,i); if(isstringable(c->nctype)) { (void)gen_charconstant(c,databuf,NC_FILL_CHAR); } else { semerror(constline(c), "Encountered non-string and non-char constant in datalist"); return; } } } static size_t gen_charconstant(NCConstant* con, Bytebuffer* databuf, int fillchar) { /* Following cases should be consistent with isstringable */ size_t constsize = 1; switch (con->nctype) { case NC_CHAR: bbAppend(databuf,con->value.charv); break; case NC_BYTE: bbAppend(databuf,con->value.int8v); break; case NC_UBYTE: bbAppend(databuf,con->value.uint8v); break; case NC_STRING: constsize = con->value.stringv.len; bbAppendn(databuf,con->value.stringv.stringv, con->value.stringv.len); bbNull(databuf); break; case NC_FILL: bbAppend(databuf,fillchar); break; default: PANIC("unexpected constant type"); } return constsize; } static int getfillchar(Datalist* fillsrc) { /* Determine the fill char */ int fillchar = 0; if(fillsrc != NULL && fillsrc->length > 0) { NCConstant* ccon = fillsrc->data; if(ccon->nctype == NC_CHAR) { fillchar = ccon->value.charv; } else if(ccon->nctype == NC_STRING) { if(ccon->value.stringv.len > 0) { fillchar = ccon->value.stringv.stringv[0]; } } } if(fillchar == 0) fillchar = NC_FILL_CHAR; /* default */ return fillchar; } #ifndef CHARBUG void gen_leafchararray(Dimset* dimset, int lastunlim, Datalist* data, Bytebuffer* databuf, Datalist* fillsrc) { int i; size_t expectedsize,xproduct,unitsize; int ndims = dimset->ndims; int fillchar = getfillchar(fillsrc); ASSERT(bbLength(databuf) == 0); /* Assume dimindex is the last unlimited (or 0 if their are no unlimiteds => we should be at a list of simple constants */ /* Compute crossproduct upto the last dimension, starting at the last unlimited */ xproduct = crossproduct(dimset,lastunlim,ndims-1); /* Compute the required size (after padding) of each string constant */ /* expected size is the size of concat of the string constants after padding */ if(ndims == 0) { unitsize = 1; expectedsize = (xproduct * unitsize); } else if(lastunlim == ndims-1) {/* last dimension is unlimited */ unitsize = 1; expectedsize = (xproduct*dimset->dimsyms[lastunlim]->dim.declsize); } else { /* last dim is not unlimited */ unitsize = dimset->dimsyms[ndims-1]->dim.declsize; expectedsize = (xproduct * unitsize); } for(i=0;i<data->length;i++) { NCConstant* c = datalistith(data,i); ASSERT(!islistconst(c)); if(isstringable(c->nctype)) { int j; size_t constsize; constsize = gen_charconstant(c,databuf,fillchar); if(constsize == 0 || constsize % unitsize > 0) { size_t padsize = unitsize - (constsize % unitsize); for(j=0;j<padsize;j++) bbAppend(databuf,fillchar); } } else { semwarn(constline(c),"Encountered non-string and non-char constant in datalist; ignored"); } } /* If |databuf| > expectedsize, complain: exception is zero length */ if(bbLength(databuf) == 0 && expectedsize == 1) { /* this is okay */ } else if(bbLength(databuf) > expectedsize) { semwarn(data->data[0].lineno,"character data list too long"); } else { size_t bufsize = bbLength(databuf); /* Pad to size dimproduct size */ if(bufsize % expectedsize > 0) { size_t padsize = expectedsize - (bufsize % expectedsize); for(i=0;i<padsize;i++) bbAppend(databuf,fillchar); } } } #endif /*!CHARBUG*/
lgpl-2.1
marchelbling/osg
src/osgShadow/ShadowTexture.cpp
15
9555
/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * OpenSceneGraph Public License for more details. */ #include <osgShadow/ShadowTexture> #include <osgShadow/ShadowedScene> #include <osg/Notify> #include <osg/ComputeBoundsVisitor> #include <osg/io_utils> using namespace osgShadow; ShadowTexture::ShadowTexture(): _textureUnit(1) { } ShadowTexture::ShadowTexture(const ShadowTexture& copy, const osg::CopyOp& copyop): ShadowTechnique(copy,copyop), _textureUnit(copy._textureUnit) { } void ShadowTexture::resizeGLObjectBuffers(unsigned int maxSize) { osg::resizeGLObjectBuffers(_camera, maxSize); osg::resizeGLObjectBuffers(_texture, maxSize); osg::resizeGLObjectBuffers(_stateset, maxSize); } void ShadowTexture::releaseGLObjects(osg::State* state) const { osg::releaseGLObjects(_camera, state); osg::releaseGLObjects(_texture, state); osg::releaseGLObjects(_stateset, state); } void ShadowTexture::setTextureUnit(unsigned int unit) { _textureUnit = unit; } void ShadowTexture::init() { if (!_shadowedScene) return; unsigned int tex_width = 512; unsigned int tex_height = 512; _texture = new osg::Texture2D; _texture->setTextureSize(tex_width, tex_height); _texture->setInternalFormat(GL_RGB); _texture->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR); _texture->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR); _texture->setWrap(osg::Texture2D::WRAP_S,osg::Texture2D::CLAMP_TO_BORDER); _texture->setWrap(osg::Texture2D::WRAP_T,osg::Texture2D::CLAMP_TO_BORDER); _texture->setBorderColor(osg::Vec4(1.0f,1.0f,1.0f,1.0f)); // set up the render to texture camera. { // create the camera _camera = new osg::Camera; _camera->setClearColor(osg::Vec4(1.0f,1.0f,1.0f,1.0f)); _camera->setCullCallback(new CameraCullCallback(this)); // set viewport _camera->setViewport(0,0,tex_width,tex_height); // set the camera to render before the main camera. _camera->setRenderOrder(osg::Camera::PRE_RENDER); // tell the camera to use OpenGL frame buffer object where supported. _camera->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT); //_camera->setRenderTargetImplementation(osg::Camera::SEPERATE_WINDOW); // attach the texture and use it as the color buffer. _camera->attach(osg::Camera::COLOR_BUFFER, _texture.get()); _material = new osg::Material; _material->setAmbient(osg::Material::FRONT_AND_BACK,osg::Vec4(0.0f,0.0f,0.0f,1.0f)); _material->setDiffuse(osg::Material::FRONT_AND_BACK,osg::Vec4(0.0f,0.0f,0.0f,1.0f)); _material->setEmission(osg::Material::FRONT_AND_BACK,osg::Vec4(0.0f,0.0f,0.0f,1.0f)); _material->setShininess(osg::Material::FRONT_AND_BACK,0.0f); osg::StateSet* stateset = _camera->getOrCreateStateSet(); stateset->setAttribute(_material.get(),osg::StateAttribute::OVERRIDE); } { _stateset = new osg::StateSet; _stateset->setTextureAttributeAndModes(_textureUnit,_texture.get(),osg::StateAttribute::ON); _stateset->setTextureMode(_textureUnit,GL_TEXTURE_GEN_S,osg::StateAttribute::ON); _stateset->setTextureMode(_textureUnit,GL_TEXTURE_GEN_T,osg::StateAttribute::ON); _stateset->setTextureMode(_textureUnit,GL_TEXTURE_GEN_R,osg::StateAttribute::ON); _stateset->setTextureMode(_textureUnit,GL_TEXTURE_GEN_Q,osg::StateAttribute::ON); _texgen = new osg::TexGen; } _dirty = false; } void ShadowTexture::update(osg::NodeVisitor& nv) { _shadowedScene->osg::Group::traverse(nv); } void ShadowTexture::cull(osgUtil::CullVisitor& cv) { // record the traversal mask on entry so we can reapply it later. unsigned int traversalMask = cv.getTraversalMask(); osgUtil::RenderStage* orig_rs = cv.getRenderStage(); // do traversal of shadow casting scene which does not need to be decorated by the shadow texture { cv.setTraversalMask( traversalMask & getShadowedScene()->getCastsShadowTraversalMask() ); _shadowedScene->osg::Group::traverse(cv); } // do traversal of shadow receiving scene which does need to be decorated by the shadow texture { cv.pushStateSet(_stateset.get()); cv.setTraversalMask( traversalMask & getShadowedScene()->getReceivesShadowTraversalMask() ); _shadowedScene->osg::Group::traverse(cv); cv.popStateSet(); } // need to compute view frustum for RTT camera. // 1) get the light position // 2) get the center and extents of the view frustum const osg::Light* selectLight = 0; osg::Vec4 lightpos; osgUtil::PositionalStateContainer::AttrMatrixList& aml = orig_rs->getPositionalStateContainer()->getAttrMatrixList(); for(osgUtil::PositionalStateContainer::AttrMatrixList::iterator itr = aml.begin(); itr != aml.end(); ++itr) { const osg::Light* light = dynamic_cast<const osg::Light*>(itr->first.get()); if (light) { osg::RefMatrix* matrix = itr->second.get(); if (matrix) lightpos = light->getPosition() * (*matrix); else lightpos = light->getPosition(); selectLight = light; } } osg::Matrix eyeToWorld; eyeToWorld.invert(*cv.getModelViewMatrix()); lightpos = lightpos * eyeToWorld; if (selectLight) { // get the bounds of the model. osg::ComputeBoundsVisitor cbbv(osg::NodeVisitor::TRAVERSE_ACTIVE_CHILDREN); cbbv.setTraversalMask(getShadowedScene()->getCastsShadowTraversalMask()); _shadowedScene->osg::Group::traverse(cbbv); osg::BoundingBox bb = cbbv.getBoundingBox(); if (lightpos[3]!=0.0) { osg::Vec3 position(lightpos.x(), lightpos.y(), lightpos.z()); float centerDistance = (position-bb.center()).length(); float znear = centerDistance-bb.radius(); float zfar = centerDistance+bb.radius(); float zNearRatio = 0.001f; if (znear<zfar*zNearRatio) znear = zfar*zNearRatio; float top = (bb.radius()/centerDistance)*znear; float right = top; _camera->setReferenceFrame(osg::Camera::ABSOLUTE_RF); _camera->setProjectionMatrixAsFrustum(-right,right,-top,top,znear,zfar); _camera->setViewMatrixAsLookAt(position,bb.center(),computeOrthogonalVector(bb.center()-position)); // compute the matrix which takes a vertex from local coords into tex coords // will use this later to specify osg::TexGen.. osg::Matrix MVPT = _camera->getViewMatrix() * _camera->getProjectionMatrix() * osg::Matrix::translate(1.0,1.0,1.0) * osg::Matrix::scale(0.5f,0.5f,0.5f); _texgen->setMode(osg::TexGen::EYE_LINEAR); _texgen->setPlanesFromMatrix(MVPT); } else { // make an orthographic projection osg::Vec3 lightDir(lightpos.x(), lightpos.y(), lightpos.z()); lightDir.normalize(); // set the position far away along the light direction osg::Vec3 position = bb.center() + lightDir * bb.radius() * 2.0; float centerDistance = (position-bb.center()).length(); float znear = centerDistance-bb.radius(); float zfar = centerDistance+bb.radius(); float zNearRatio = 0.001f; if (znear<zfar*zNearRatio) znear = zfar*zNearRatio; float top = bb.radius(); float right = top; _camera->setReferenceFrame(osg::Camera::ABSOLUTE_RF); _camera->setProjectionMatrixAsOrtho(-right, right, -top, top, znear, zfar); _camera->setViewMatrixAsLookAt(position,bb.center(),computeOrthogonalVector(lightDir)); // compute the matrix which takes a vertex from local coords into tex coords // will use this later to specify osg::TexGen.. osg::Matrix MVPT = _camera->getViewMatrix() * _camera->getProjectionMatrix() * osg::Matrix::translate(1.0,1.0,1.0) * osg::Matrix::scale(0.5f,0.5f,0.5f); _texgen->setMode(osg::TexGen::EYE_LINEAR); _texgen->setPlanesFromMatrix(MVPT); } cv.setTraversalMask( traversalMask & getShadowedScene()->getCastsShadowTraversalMask() ); // do RTT camera traversal _camera->accept(cv); orig_rs->getPositionalStateContainer()->addPositionedTextureAttribute(_textureUnit, cv.getModelViewMatrix(), _texgen.get()); } // reapply the original traversal mask cv.setTraversalMask( traversalMask ); } void ShadowTexture::cleanSceneGraph() { }
lgpl-2.1
krichter722/gstreamer
tests/check/libs/sparsefile.c
16
6335
/* GStreamer * * unit test for cachefile helper * * Copyright (C) 2014 Wim Taymans <wtaymans@redhat.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <glib/gstdio.h> #include <gst/check/gstcheck.h> /* not public API for now */ #include "../../../plugins/elements/gstsparsefile.c" static void expect_range_before (GstSparseFile * file, gsize offset, gsize start, gsize stop) { gsize tstart, tstop; fail_unless (gst_sparse_file_get_range_before (file, offset, &tstart, &tstop) == TRUE); fail_unless (tstart == start); fail_unless (tstop == stop); } static void expect_range_after (GstSparseFile * file, gsize offset, gsize start, gsize stop) { gsize tstart, tstop; fail_unless (gst_sparse_file_get_range_after (file, offset, &tstart, &tstop) == TRUE); fail_unless (tstart == start); fail_unless (tstop == stop); } static gboolean expect_write (GstSparseFile * file, gsize offset, gsize count, gsize result, gsize avail) { GError *error = NULL; gchar buffer[200] = { 0, }; gsize res, a; res = gst_sparse_file_write (file, offset, buffer, count, &a, &error); if (res != result) return FALSE; if (res == 0) { if (error == NULL) return FALSE; g_clear_error (&error); } else if (a != avail) return FALSE; return TRUE; } static gboolean expect_read (GstSparseFile * file, gsize offset, gsize count, gsize result, gsize avail) { GError *error = NULL; gchar buffer[200]; gsize res, a; res = gst_sparse_file_read (file, offset, buffer, count, &a, &error); if (res != result) return FALSE; if (res == 0) { if (error == NULL) return FALSE; g_clear_error (&error); } else if (a != avail) return FALSE; return TRUE; } GST_START_TEST (test_write_read) { GstSparseFile *file; gint fd; gchar *name; gsize start, stop; name = g_strdup ("cachefile-testXXXXXX"); fd = g_mkstemp (name); fail_if (fd == -1); file = gst_sparse_file_new (); fail_unless (file != NULL); fail_unless (gst_sparse_file_set_fd (file, fd)); fail_unless (gst_sparse_file_n_ranges (file) == 0); /* should fail, we didn't write anything yet */ fail_unless (expect_read (file, 0, 100, 0, 0)); /* no ranges, searching for a range should fail */ fail_unless (gst_sparse_file_n_ranges (file) == 0); fail_unless (gst_sparse_file_get_range_before (file, 0, &start, &stop) == FALSE); fail_unless (gst_sparse_file_get_range_before (file, 10, &start, &stop) == FALSE); fail_unless (gst_sparse_file_get_range_after (file, 0, &start, &stop) == FALSE); fail_unless (gst_sparse_file_get_range_after (file, 10, &start, &stop) == FALSE); /* now write some data */ fail_unless (expect_write (file, 0, 100, 100, 0)); /* we have 1 range now */ fail_unless (gst_sparse_file_n_ranges (file) == 1); expect_range_before (file, 0, 0, 100); expect_range_after (file, 0, 0, 100); expect_range_before (file, 100, 0, 100); expect_range_before (file, 50, 0, 100); expect_range_before (file, 200, 0, 100); fail_unless (gst_sparse_file_get_range_after (file, 100, &start, &stop) == FALSE); expect_range_after (file, 50, 0, 100); /* we can read all data now */ fail_unless (expect_read (file, 0, 100, 100, 0)); /* we can read less */ fail_unless (expect_read (file, 0, 50, 50, 50)); /* but we can't read more than what is written */ fail_unless (expect_read (file, 0, 101, 0, 0)); g_unlink (name); gst_sparse_file_free (file); g_free (name); } GST_END_TEST; GST_START_TEST (test_write_merge) { GstSparseFile *file; gint fd; gchar *name; gsize start, stop; name = g_strdup ("cachefile-testXXXXXX"); fd = g_mkstemp (name); fail_if (fd == -1); file = gst_sparse_file_new (); gst_sparse_file_set_fd (file, fd); /* write something at offset 0 */ fail_unless (expect_write (file, 0, 100, 100, 0)); /* we have 1 range now */ fail_unless (gst_sparse_file_n_ranges (file) == 1); expect_range_before (file, 110, 0, 100); expect_range_after (file, 50, 0, 100); fail_unless (gst_sparse_file_get_range_after (file, 100, &start, &stop) == FALSE); /* read should fail */ fail_unless (expect_read (file, 50, 150, 0, 0)); /* write something at offset 150 */ fail_unless (expect_write (file, 150, 100, 100, 0)); /* we have 2 ranges now */ fail_unless (gst_sparse_file_n_ranges (file) == 2); expect_range_before (file, 110, 0, 100); expect_range_after (file, 50, 0, 100); expect_range_after (file, 100, 150, 250); expect_range_before (file, 150, 150, 250); /* read should still fail */ fail_unless (expect_read (file, 50, 150, 0, 0)); /* fill the hole */ fail_unless (expect_write (file, 100, 50, 50, 100)); /* we have 1 range now */ fail_unless (gst_sparse_file_n_ranges (file) == 1); expect_range_before (file, 110, 0, 250); expect_range_after (file, 50, 0, 250); expect_range_after (file, 100, 0, 250); expect_range_before (file, 150, 0, 250); fail_unless (gst_sparse_file_get_range_after (file, 250, &start, &stop) == FALSE); /* read work */ fail_unless (expect_read (file, 50, 150, 150, 50)); g_unlink (name); gst_sparse_file_free (file); g_free (name); } GST_END_TEST; static Suite * gst_cachefile_suite (void) { Suite *s = suite_create ("cachefile"); TCase *tc_chain = tcase_create ("general"); suite_add_tcase (s, tc_chain); tcase_add_test (tc_chain, test_write_read); tcase_add_test (tc_chain, test_write_merge); return s; } GST_CHECK_MAIN (gst_cachefile);
lgpl-2.1
ddcc/klee-uclibc-0.9.33.2
libc/sysdeps/linux/arm/aeabi_lcsts.c
17
3365
/* Link-time constants for ARM EABI. Copyright (C) 2005 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. In addition to the permissions in the GNU Lesser General Public License, the Free Software Foundation gives you unlimited permission to link the compiled version of this file with other programs, and to distribute those programs without any restriction coming from the use of this file. (The GNU Lesser General Public License restrictions do apply in other respects; for example, they cover modification of the file, and distribution when not linked into another program.) Note that people who make modified versions of this file are not obligated to grant this special exception for their modified versions; it is their choice whether to do so. The GNU Lesser General Public License gives permission to release a modified version without this exception; this exception also makes it possible to release a modified version which carries forward this exception. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ /* The ARM EABI requires that we provide ISO compile-time constants as link-time constants. Some portable applications may reference these. */ #include <errno.h> #include <limits.h> #include <locale.h> #include <setjmp.h> #include <signal.h> #include <stdio.h> #include <time.h> #define eabi_constant2(X,Y) const int __aeabi_##X attribute_hidden = Y #define eabi_constant(X) const int __aeabi_##X attribute_hidden = X eabi_constant (EDOM); eabi_constant (ERANGE); eabi_constant (EILSEQ); eabi_constant (MB_LEN_MAX); eabi_constant (LC_COLLATE); eabi_constant (LC_CTYPE); eabi_constant (LC_MONETARY); eabi_constant (LC_NUMERIC); eabi_constant (LC_TIME); eabi_constant (LC_ALL); /* The value of __aeabi_JMP_BUF_SIZE is the number of doublewords in a jmp_buf. */ eabi_constant2 (JMP_BUF_SIZE, sizeof (jmp_buf) / 8); eabi_constant (SIGABRT); eabi_constant (SIGFPE); eabi_constant (SIGILL); eabi_constant (SIGINT); eabi_constant (SIGSEGV); eabi_constant (SIGTERM); eabi_constant2 (IOFBF, _IOFBF); eabi_constant2 (IOLBF, _IOLBF); eabi_constant2 (IONBF, _IONBF); eabi_constant (BUFSIZ); eabi_constant (FOPEN_MAX); eabi_constant (TMP_MAX); eabi_constant (FILENAME_MAX); #ifdef __UCLIBC_SUSV4_LEGACY__ eabi_constant (L_tmpnam); #endif FILE *__aeabi_stdin attribute_hidden; FILE *__aeabi_stdout attribute_hidden; FILE *__aeabi_stderr attribute_hidden; static void __attribute__ ((used)) setup_aeabi_stdio (void) { __aeabi_stdin = stdin; __aeabi_stdout = stdout; __aeabi_stderr = stderr; } static void (*fp) (void) __attribute__ ((used, section (".preinit_array"))) = setup_aeabi_stdio; eabi_constant (CLOCKS_PER_SEC);
lgpl-2.1
aupeo/log4cpp
src/SyslogAppender.cpp
18
2378
/* * SyslogAppender.cpp * * Copyright 2000, LifeLine Networks BV (www.lifeline.nl). All rights reserved. * Copyright 2000, Bastiaan Bakker. All rights reserved. * * See the COPYING file for the terms of usage and distribution. */ #include "PortabilityImpl.hh" #if LOG4CPP_HAVE_SYSLOG #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <log4cpp/SyslogAppender.hh> #include <log4cpp/FactoryParams.hh> #include <memory> namespace log4cpp { int SyslogAppender::toSyslogPriority(Priority::Value priority) { static int priorities[8] = { LOG_EMERG, LOG_ALERT, LOG_CRIT, LOG_ERR, LOG_WARNING, LOG_NOTICE, LOG_INFO, LOG_DEBUG }; int result; priority++; priority /= 100; if (priority < 0) { result = LOG_EMERG; } else if (priority > 7) { result = LOG_DEBUG; } else { result = priorities[priority]; } return result; } SyslogAppender::SyslogAppender(const std::string& name, const std::string& syslogName, int facility) : LayoutAppender(name), _syslogName(syslogName), _facility(facility) { open(); } SyslogAppender::~SyslogAppender() { close(); } void SyslogAppender::open() { openlog(_syslogName.c_str(), 0, _facility); } void SyslogAppender::close() { ::closelog(); } void SyslogAppender::_append(const LoggingEvent& event) { std::string message(_getLayout().format(event)); int priority = toSyslogPriority(event.priority); ::syslog(priority | _facility, "%s", message.c_str()); } bool SyslogAppender::reopen() { close(); open(); return true; } std::auto_ptr<Appender> create_syslog_appender(const FactoryParams& params) { std::string name, syslog_name; int facility = 0; params.get_for("syslog appender").required("name", name)("syslog_name", syslog_name) .optional("facility", facility); return std::auto_ptr<Appender>(new SyslogAppender(name, syslog_name, facility)); } } #endif // LOG4CPP_HAVE_SYSLOG
lgpl-2.1
lgiommi/root
interpreter/llvm/src/lib/Object/SymbolicFile.cpp
21
3172
//===- SymbolicFile.cpp - Interface that only provides symbols --*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines a file format independent SymbolicFile class. // //===----------------------------------------------------------------------===// #include "llvm/Object/COFF.h" #include "llvm/Object/COFFImportFile.h" #include "llvm/Object/IRObjectFile.h" #include "llvm/Object/ObjectFile.h" #include "llvm/Object/SymbolicFile.h" #include "llvm/Support/MemoryBuffer.h" using namespace llvm; using namespace object; SymbolicFile::SymbolicFile(unsigned int Type, MemoryBufferRef Source) : Binary(Type, Source) {} SymbolicFile::~SymbolicFile() {} Expected<std::unique_ptr<SymbolicFile>> SymbolicFile::createSymbolicFile( MemoryBufferRef Object, sys::fs::file_magic Type, LLVMContext *Context) { StringRef Data = Object.getBuffer(); if (Type == sys::fs::file_magic::unknown) Type = sys::fs::identify_magic(Data); switch (Type) { case sys::fs::file_magic::bitcode: if (Context) return errorOrToExpected(IRObjectFile::create(Object, *Context)); // Fallthrough case sys::fs::file_magic::unknown: case sys::fs::file_magic::archive: case sys::fs::file_magic::macho_universal_binary: case sys::fs::file_magic::windows_resource: return errorCodeToError(object_error::invalid_file_type); case sys::fs::file_magic::elf: case sys::fs::file_magic::elf_executable: case sys::fs::file_magic::elf_shared_object: case sys::fs::file_magic::elf_core: case sys::fs::file_magic::macho_executable: case sys::fs::file_magic::macho_fixed_virtual_memory_shared_lib: case sys::fs::file_magic::macho_core: case sys::fs::file_magic::macho_preload_executable: case sys::fs::file_magic::macho_dynamically_linked_shared_lib: case sys::fs::file_magic::macho_dynamic_linker: case sys::fs::file_magic::macho_bundle: case sys::fs::file_magic::macho_dynamically_linked_shared_lib_stub: case sys::fs::file_magic::macho_dsym_companion: case sys::fs::file_magic::macho_kext_bundle: case sys::fs::file_magic::pecoff_executable: return ObjectFile::createObjectFile(Object, Type); case sys::fs::file_magic::coff_import_library: return std::unique_ptr<SymbolicFile>(new COFFImportFile(Object)); case sys::fs::file_magic::elf_relocatable: case sys::fs::file_magic::macho_object: case sys::fs::file_magic::coff_object: { Expected<std::unique_ptr<ObjectFile>> Obj = ObjectFile::createObjectFile(Object, Type); if (!Obj || !Context) return std::move(Obj); ErrorOr<MemoryBufferRef> BCData = IRObjectFile::findBitcodeInObject(*Obj->get()); if (!BCData) return std::move(Obj); return errorOrToExpected(IRObjectFile::create( MemoryBufferRef(BCData->getBuffer(), Object.getBufferIdentifier()), *Context)); } } llvm_unreachable("Unexpected Binary File Type"); }
lgpl-2.1
ktd2004/live555
liveMedia/MP3InternalsHuffman.cpp
22
29045
/********** This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.) This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********/ // "liveMedia" // Copyright (c) 1996-2015 Live Networks, Inc. All rights reserved. // MP3 internal implementation details (Huffman encoding) // Implementation #include "MP3InternalsHuffman.hh" #include <stdio.h> #include <string.h> #include <stdlib.h> MP3HuffmanEncodingInfo ::MP3HuffmanEncodingInfo(Boolean includeDecodedValues) { if (includeDecodedValues) { decodedValues = new unsigned[(SBLIMIT*SSLIMIT + 1)*4]; } else { decodedValues = NULL; } } MP3HuffmanEncodingInfo::~MP3HuffmanEncodingInfo() { delete[] decodedValues; } // This is crufty old code that needs to be cleaned up ##### static unsigned debugCount = 0; /* for debugging */ #define TRUNC_FAVORa void updateSideInfoForHuffman(MP3SideInfo& sideInfo, Boolean isMPEG2, unsigned char const* mainDataPtr, unsigned p23L0, unsigned p23L1, unsigned& part23Length0a, unsigned& part23Length0aTruncation, unsigned& part23Length0b, unsigned& part23Length0bTruncation, unsigned& part23Length1a, unsigned& part23Length1aTruncation, unsigned& part23Length1b, unsigned& part23Length1bTruncation) { int i, j; unsigned sfLength, origTotABsize, adjustment; MP3SideInfo::gr_info_s_t* gr; /* First, Huffman-decode each part of the segment's main data, to see at which bit-boundaries the samples appear: */ MP3HuffmanEncodingInfo hei; ++debugCount; #ifdef DEBUG fprintf(stderr, "usifh-start: p23L0: %d, p23L1: %d\n", p23L0, p23L1); #endif /* Process granule 0 */ { gr = &(sideInfo.ch[0].gr[0]); origTotABsize = gr->part2_3_length; MP3HuffmanDecode(gr, isMPEG2, mainDataPtr, 0, origTotABsize, sfLength, hei); /* Begin by computing new sizes for parts a & b (& their truncations) */ #ifdef DEBUG fprintf(stderr, "usifh-0: %d, %d:%d, %d:%d, %d:%d, %d:%d, %d:%d\n", hei.numSamples, sfLength/8, sfLength%8, hei.reg1Start/8, hei.reg1Start%8, hei.reg2Start/8, hei.reg2Start%8, hei.bigvalStart/8, hei.bigvalStart%8, origTotABsize/8, origTotABsize%8); #endif if (p23L0 < sfLength) { /* We can't use this, so give it all to the next granule: */ p23L1 += p23L0; p23L0 = 0; } part23Length0a = hei.bigvalStart; part23Length0b = origTotABsize - hei.bigvalStart; part23Length0aTruncation = part23Length0bTruncation = 0; if (origTotABsize > p23L0) { /* We need to shorten one or both of fields a & b */ unsigned truncation = origTotABsize - p23L0; #ifdef TRUNC_FAIRLY part23Length0aTruncation = (truncation*(part23Length0a-sfLength)) /(origTotABsize-sfLength); part23Length0bTruncation = truncation - part23Length0aTruncation; #endif #ifdef TRUNC_FAVORa part23Length0bTruncation = (truncation > part23Length0b) ? part23Length0b : truncation; part23Length0aTruncation = truncation - part23Length0bTruncation; #endif #ifdef TRUNC_FAVORb part23Length0aTruncation = (truncation > part23Length0a-sfLength) ? (part23Length0a-sfLength) : truncation; part23Length0bTruncation = truncation - part23Length0aTruncation; #endif } /* ASSERT: part23Length0xTruncation <= part23Length0x */ part23Length0a -= part23Length0aTruncation; part23Length0b -= part23Length0bTruncation; #ifdef DEBUG fprintf(stderr, "usifh-0: interim sizes: %d (%d), %d (%d)\n", part23Length0a, part23Length0aTruncation, part23Length0b, part23Length0bTruncation); #endif /* Adjust these new lengths so they end on sample bit boundaries: */ for (i = 0; i < (int)hei.numSamples; ++i) { if (hei.allBitOffsets[i] == part23Length0a) break; else if (hei.allBitOffsets[i] > part23Length0a) {--i; break;} } if (i < 0) { /* should happen only if we couldn't fit sfLength */ i = 0; adjustment = 0; } else { adjustment = part23Length0a - hei.allBitOffsets[i]; } #ifdef DEBUG fprintf(stderr, "%d usifh-0: adjustment 1: %d\n", debugCount, adjustment); #endif part23Length0a -= adjustment; part23Length0aTruncation += adjustment; /* Assign the bits we just shaved to field b and granule 1: */ if (part23Length0bTruncation < adjustment) { p23L1 += (adjustment - part23Length0bTruncation); adjustment = part23Length0bTruncation; } part23Length0b += adjustment; part23Length0bTruncation -= adjustment; for (j = i; j < (int)hei.numSamples; ++j) { if (hei.allBitOffsets[j] == part23Length0a + part23Length0aTruncation + part23Length0b) break; else if (hei.allBitOffsets[j] > part23Length0a + part23Length0aTruncation + part23Length0b) {--j; break;} } if (j < 0) { /* should happen only if we couldn't fit sfLength */ j = 0; adjustment = 0; } else { adjustment = part23Length0a+part23Length0aTruncation+part23Length0b - hei.allBitOffsets[j]; } #ifdef DEBUG fprintf(stderr, "%d usifh-0: adjustment 2: %d\n", debugCount, adjustment); #endif if (adjustment > part23Length0b) adjustment = part23Length0b; /*sanity*/ part23Length0b -= adjustment; part23Length0bTruncation += adjustment; /* Assign the bits we just shaved to granule 1 */ p23L1 += adjustment; if (part23Length0aTruncation > 0) { /* Change the granule's 'big_values' field to reflect the truncation */ gr->big_values = i; } } /* Process granule 1 (MPEG-1 only) */ if (isMPEG2) { part23Length1a = part23Length1b = 0; part23Length1aTruncation = part23Length1bTruncation = 0; } else { unsigned granule1Offset = origTotABsize + sideInfo.ch[1].gr[0].part2_3_length; gr = &(sideInfo.ch[0].gr[1]); origTotABsize = gr->part2_3_length; MP3HuffmanDecode(gr, isMPEG2, mainDataPtr, granule1Offset, origTotABsize, sfLength, hei); /* Begin by computing new sizes for parts a & b (& their truncations) */ #ifdef DEBUG fprintf(stderr, "usifh-1: %d, %d:%d, %d:%d, %d:%d, %d:%d, %d:%d\n", hei.numSamples, sfLength/8, sfLength%8, hei.reg1Start/8, hei.reg1Start%8, hei.reg2Start/8, hei.reg2Start%8, hei.bigvalStart/8, hei.bigvalStart%8, origTotABsize/8, origTotABsize%8); #endif if (p23L1 < sfLength) { /* We can't use this, so give up on this granule: */ p23L1 = 0; } part23Length1a = hei.bigvalStart; part23Length1b = origTotABsize - hei.bigvalStart; part23Length1aTruncation = part23Length1bTruncation = 0; if (origTotABsize > p23L1) { /* We need to shorten one or both of fields a & b */ unsigned truncation = origTotABsize - p23L1; #ifdef TRUNC_FAIRLY part23Length1aTruncation = (truncation*(part23Length1a-sfLength)) /(origTotABsize-sfLength); part23Length1bTruncation = truncation - part23Length1aTruncation; #endif #ifdef TRUNC_FAVORa part23Length1bTruncation = (truncation > part23Length1b) ? part23Length1b : truncation; part23Length1aTruncation = truncation - part23Length1bTruncation; #endif #ifdef TRUNC_FAVORb part23Length1aTruncation = (truncation > part23Length1a-sfLength) ? (part23Length1a-sfLength) : truncation; part23Length1bTruncation = truncation - part23Length1aTruncation; #endif } /* ASSERT: part23Length1xTruncation <= part23Length1x */ part23Length1a -= part23Length1aTruncation; part23Length1b -= part23Length1bTruncation; #ifdef DEBUG fprintf(stderr, "usifh-1: interim sizes: %d (%d), %d (%d)\n", part23Length1a, part23Length1aTruncation, part23Length1b, part23Length1bTruncation); #endif /* Adjust these new lengths so they end on sample bit boundaries: */ for (i = 0; i < (int)hei.numSamples; ++i) { if (hei.allBitOffsets[i] == part23Length1a) break; else if (hei.allBitOffsets[i] > part23Length1a) {--i; break;} } if (i < 0) { /* should happen only if we couldn't fit sfLength */ i = 0; adjustment = 0; } else { adjustment = part23Length1a - hei.allBitOffsets[i]; } #ifdef DEBUG fprintf(stderr, "%d usifh-1: adjustment 0: %d\n", debugCount, adjustment); #endif part23Length1a -= adjustment; part23Length1aTruncation += adjustment; /* Assign the bits we just shaved to field b: */ if (part23Length1bTruncation < adjustment) { adjustment = part23Length1bTruncation; } part23Length1b += adjustment; part23Length1bTruncation -= adjustment; for (j = i; j < (int)hei.numSamples; ++j) { if (hei.allBitOffsets[j] == part23Length1a + part23Length1aTruncation + part23Length1b) break; else if (hei.allBitOffsets[j] > part23Length1a + part23Length1aTruncation + part23Length1b) {--j; break;} } if (j < 0) { /* should happen only if we couldn't fit sfLength */ j = 0; adjustment = 0; } else { adjustment = part23Length1a+part23Length1aTruncation+part23Length1b - hei.allBitOffsets[j]; } #ifdef DEBUG fprintf(stderr, "%d usifh-1: adjustment 1: %d\n", debugCount, adjustment); #endif if (adjustment > part23Length1b) adjustment = part23Length1b; /*sanity*/ part23Length1b -= adjustment; part23Length1bTruncation += adjustment; if (part23Length1aTruncation > 0) { /* Change the granule's 'big_values' field to reflect the truncation */ gr->big_values = i; } } #ifdef DEBUG fprintf(stderr, "usifh-end, new vals: %d (%d), %d (%d), %d (%d), %d (%d)\n", part23Length0a, part23Length0aTruncation, part23Length0b, part23Length0bTruncation, part23Length1a, part23Length1aTruncation, part23Length1b, part23Length1bTruncation); #endif } static void rsf_getline(char* line, unsigned max, unsigned char**fi) { unsigned i; for (i = 0; i < max; ++i) { line[i] = *(*fi)++; if (line[i] == '\n') { line[i++] = '\0'; return; } } line[i] = '\0'; } static void rsfscanf(unsigned char **fi, unsigned int* v) { while (sscanf((char*)*fi, "%x", v) == 0) { /* skip past the next '\0' */ while (*(*fi)++ != '\0') {} } /* skip past any white-space before the value: */ while (*(*fi) <= ' ') ++(*fi); /* skip past the value: */ while (*(*fi) > ' ') ++(*fi); } #define HUFFBITS unsigned long int #define SIZEOF_HUFFBITS 4 #define HTN 34 #define MXOFF 250 struct huffcodetab { char tablename[3]; /*string, containing table_description */ unsigned int xlen; /*max. x-index+ */ unsigned int ylen; /*max. y-index+ */ unsigned int linbits; /*number of linbits */ unsigned int linmax; /*max number to be stored in linbits */ int ref; /*a positive value indicates a reference*/ HUFFBITS *table; /*pointer to array[xlen][ylen] */ unsigned char *hlen; /*pointer to array[xlen][ylen] */ unsigned char(*val)[2];/*decoder tree */ unsigned int treelen; /*length of decoder tree */ }; static struct huffcodetab rsf_ht[HTN]; // array of all huffcodetable headers /* 0..31 Huffman code table 0..31 */ /* 32,33 count1-tables */ /* read the huffman decoder table */ static int read_decoder_table(unsigned char* fi) { int n,i,nn,t; unsigned int v0,v1; char command[100],line[100]; for (n=0;n<HTN;n++) { rsf_ht[n].table = NULL; rsf_ht[n].hlen = NULL; /* .table number treelen xlen ylen linbits */ do { rsf_getline(line,99,&fi); } while ((line[0] == '#') || (line[0] < ' ')); sscanf(line,"%s %s %u %u %u %u",command,rsf_ht[n].tablename, &rsf_ht[n].treelen, &rsf_ht[n].xlen, &rsf_ht[n].ylen, &rsf_ht[n].linbits); if (strcmp(command,".end")==0) return n; else if (strcmp(command,".table")!=0) { #ifdef DEBUG fprintf(stderr,"huffman table %u data corrupted\n",n); #endif return -1; } rsf_ht[n].linmax = (1<<rsf_ht[n].linbits)-1; sscanf(rsf_ht[n].tablename,"%u",&nn); if (nn != n) { #ifdef DEBUG fprintf(stderr,"wrong table number %u\n",n); #endif return(-2); } do { rsf_getline(line,99,&fi); } while ((line[0] == '#') || (line[0] < ' ')); sscanf(line,"%s %u",command,&t); if (strcmp(command,".reference")==0) { rsf_ht[n].ref = t; rsf_ht[n].val = rsf_ht[t].val; rsf_ht[n].treelen = rsf_ht[t].treelen; if ( (rsf_ht[n].xlen != rsf_ht[t].xlen) || (rsf_ht[n].ylen != rsf_ht[t].ylen) ) { #ifdef DEBUG fprintf(stderr,"wrong table %u reference\n",n); #endif return (-3); }; while ((line[0] == '#') || (line[0] < ' ') ) { rsf_getline(line,99,&fi); } } else if (strcmp(command,".treedata")==0) { rsf_ht[n].ref = -1; rsf_ht[n].val = (unsigned char (*)[2]) new unsigned char[2*(rsf_ht[n].treelen)]; if ((rsf_ht[n].val == NULL) && ( rsf_ht[n].treelen != 0 )){ #ifdef DEBUG fprintf(stderr, "heaperror at table %d\n",n); #endif return -1; } for (i=0;(unsigned)i<rsf_ht[n].treelen; i++) { rsfscanf(&fi, &v0); rsfscanf(&fi, &v1); /*replaces fscanf(fi,"%x %x",&v0, &v1);*/ rsf_ht[n].val[i][0]=(unsigned char)v0; rsf_ht[n].val[i][1]=(unsigned char)v1; } rsf_getline(line,99,&fi); /* read the rest of the line */ } else { #ifdef DEBUG fprintf(stderr,"huffman decodertable error at table %d\n",n); #endif } } return n; } static void initialize_huffman() { static Boolean huffman_initialized = False; if (huffman_initialized) return; if (read_decoder_table(huffdec) != HTN) { #ifdef DEBUG fprintf(stderr,"decoder table read error\n"); #endif return; } huffman_initialized = True; } static unsigned char const slen[2][16] = { {0, 0, 0, 0, 3, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4}, {0, 1, 2, 3, 0, 1, 2, 3, 1, 2, 3, 1, 2, 3, 2, 3} }; static unsigned char const stab[3][6][4] = { { { 6, 5, 5,5 } , { 6, 5, 7,3 } , { 11,10,0,0} , { 7, 7, 7,0 } , { 6, 6, 6,3 } , { 8, 8,5,0} } , { { 9, 9, 9,9 } , { 9, 9,12,6 } , { 18,18,0,0} , {12,12,12,0 } , {12, 9, 9,6 } , { 15,12,9,0} } , { { 6, 9, 9,9 } , { 6, 9,12,6 } , { 15,18,0,0} , { 6,15,12,0 } , { 6,12, 9,6 } , { 6,18,9,0} } }; static unsigned rsf_get_scale_factors_1(MP3SideInfo::gr_info_s_t *gr_info) { int numbits; int num0 = slen[0][gr_info->scalefac_compress]; int num1 = slen[1][gr_info->scalefac_compress]; if (gr_info->block_type == 2) { numbits = (num0 + num1) * 18; if (gr_info->mixed_block_flag) { numbits -= num0; /* num0 * 17 + num1 * 18 */ } } else { int scfsi = gr_info->scfsi; if(scfsi < 0) { /* scfsi < 0 => granule == 0 */ numbits = (num0 + num1) * 10 + num0; } else { numbits = 0; if(!(scfsi & 0x8)) { numbits += num0 * 6; } else { } if(!(scfsi & 0x4)) { numbits += num0 * 5; } else { } if(!(scfsi & 0x2)) { numbits += num1 * 5; } else { } if(!(scfsi & 0x1)) { numbits += num1 * 5; } else { } } } return numbits; } extern unsigned n_slen2[]; extern unsigned i_slen2[]; static unsigned rsf_get_scale_factors_2(MP3SideInfo::gr_info_s_t *gr_info) { unsigned char const* pnt; int i; unsigned int slen; int n = 0; int numbits = 0; slen = n_slen2[gr_info->scalefac_compress]; gr_info->preflag = (slen>>15) & 0x1; n = 0; if( gr_info->block_type == 2 ) { n++; if(gr_info->mixed_block_flag) n++; } pnt = stab[n][(slen>>12)&0x7]; for(i=0;i<4;i++) { int num = slen & 0x7; slen >>= 3; numbits += pnt[i] * num; } return numbits; } static unsigned getScaleFactorsLength(MP3SideInfo::gr_info_s_t* gr, Boolean isMPEG2) { return isMPEG2 ? rsf_get_scale_factors_2(gr) : rsf_get_scale_factors_1(gr); } static int rsf_huffman_decoder(BitVector& bv, struct huffcodetab const* h, int* x, int* y, int* v, int* w); // forward void MP3HuffmanDecode(MP3SideInfo::gr_info_s_t* gr, Boolean isMPEG2, unsigned char const* fromBasePtr, unsigned fromBitOffset, unsigned fromLength, unsigned& scaleFactorsLength, MP3HuffmanEncodingInfo& hei) { unsigned i; int x, y, v, w; struct huffcodetab *h; BitVector bv((unsigned char*)fromBasePtr, fromBitOffset, fromLength); /* Compute the size of the scale factors (& also advance bv): */ scaleFactorsLength = getScaleFactorsLength(gr, isMPEG2); bv.skipBits(scaleFactorsLength); initialize_huffman(); hei.reg1Start = hei.reg2Start = hei.numSamples = 0; /* Read bigvalues area. */ if (gr->big_values < gr->region1start + gr->region2start) { gr->big_values = gr->region1start + gr->region2start; /* sanity check */ } for (i = 0; i < gr->big_values; ++i) { if (i < gr->region1start) { /* in region 0 */ h = &rsf_ht[gr->table_select[0]]; } else if (i < gr->region2start) { /* in region 1 */ h = &rsf_ht[gr->table_select[1]]; if (hei.reg1Start == 0) { hei.reg1Start = bv.curBitIndex(); } } else { /* in region 2 */ h = &rsf_ht[gr->table_select[2]]; if (hei.reg2Start == 0) { hei.reg2Start = bv.curBitIndex(); } } hei.allBitOffsets[i] = bv.curBitIndex(); rsf_huffman_decoder(bv, h, &x, &y, &v, &w); if (hei.decodedValues != NULL) { // Record the decoded values: unsigned* ptr = &hei.decodedValues[4*i]; ptr[0] = x; ptr[1] = y; ptr[2] = v; ptr[3] = w; } } hei.bigvalStart = bv.curBitIndex(); /* Read count1 area. */ h = &rsf_ht[gr->count1table_select+32]; while (bv.curBitIndex() < bv.totNumBits() && i < SSLIMIT*SBLIMIT) { hei.allBitOffsets[i] = bv.curBitIndex(); rsf_huffman_decoder(bv, h, &x, &y, &v, &w); if (hei.decodedValues != NULL) { // Record the decoded values: unsigned* ptr = &hei.decodedValues[4*i]; ptr[0] = x; ptr[1] = y; ptr[2] = v; ptr[3] = w; } ++i; } hei.allBitOffsets[i] = bv.curBitIndex(); hei.numSamples = i; } HUFFBITS dmask = 1 << (SIZEOF_HUFFBITS*8-1); unsigned int hs = SIZEOF_HUFFBITS*8; /* do the huffman-decoding */ static int rsf_huffman_decoder(BitVector& bv, struct huffcodetab const* h, // ptr to huffman code record /* unsigned */ int *x, // returns decoded x value /* unsigned */ int *y, // returns decoded y value int* v, int* w) { HUFFBITS level; unsigned point = 0; int error = 1; level = dmask; *x = *y = *v = *w = 0; if (h->val == NULL) return 2; /* table 0 needs no bits */ if (h->treelen == 0) return 0; /* Lookup in Huffman table. */ do { if (h->val[point][0]==0) { /*end of tree*/ *x = h->val[point][1] >> 4; *y = h->val[point][1] & 0xf; error = 0; break; } if (bv.get1Bit()) { while (h->val[point][1] >= MXOFF) point += h->val[point][1]; point += h->val[point][1]; } else { while (h->val[point][0] >= MXOFF) point += h->val[point][0]; point += h->val[point][0]; } level >>= 1; } while (level || (point < h->treelen) ); ///// } while (level || (point < rsf_ht->treelen) ); /* Check for error. */ if (error) { /* set x and y to a medium value as a simple concealment */ printf("Illegal Huffman code in data.\n"); *x = ((h->xlen-1) << 1); *y = ((h->ylen-1) << 1); } /* Process sign encodings for quadruples tables. */ if (h->tablename[0] == '3' && (h->tablename[1] == '2' || h->tablename[1] == '3')) { *v = (*y>>3) & 1; *w = (*y>>2) & 1; *x = (*y>>1) & 1; *y = *y & 1; if (*v) if (bv.get1Bit() == 1) *v = -*v; if (*w) if (bv.get1Bit() == 1) *w = -*w; if (*x) if (bv.get1Bit() == 1) *x = -*x; if (*y) if (bv.get1Bit() == 1) *y = -*y; } /* Process sign and escape encodings for dual tables. */ else { if (h->linbits) if ((h->xlen-1) == (unsigned)*x) *x += bv.getBits(h->linbits); if (*x) if (bv.get1Bit() == 1) *x = -*x; if (h->linbits) if ((h->ylen-1) == (unsigned)*y) *y += bv.getBits(h->linbits); if (*y) if (bv.get1Bit() == 1) *y = -*y; } return error; } #ifdef DO_HUFFMAN_ENCODING inline int getNextSample(unsigned char const*& fromPtr) { int sample #ifdef FOUR_BYTE_SAMPLES = (fromPtr[0]<<24) | (fromPtr[1]<<16) | (fromPtr[2]<<8) | fromPtr[3]; #else #ifdef TWO_BYTE_SAMPLES = (fromPtr[0]<<8) | fromPtr[1]; #else // ONE_BYTE_SAMPLES = fromPtr[0]; #endif #endif fromPtr += BYTES_PER_SAMPLE_VALUE; return sample; } static void rsf_huffman_encoder(BitVector& bv, struct huffcodetab* h, int x, int y, int v, int w); // forward unsigned MP3HuffmanEncode(MP3SideInfo::gr_info_s_t const* gr, unsigned char const* fromPtr, unsigned char* toPtr, unsigned toBitOffset, unsigned numHuffBits) { unsigned i; struct huffcodetab *h; int x, y, v, w; BitVector bv(toPtr, toBitOffset, numHuffBits); initialize_huffman(); // Encode big_values area: unsigned big_values = gr->big_values; if (big_values < gr->region1start + gr->region2start) { big_values = gr->region1start + gr->region2start; /* sanity check */ } for (i = 0; i < big_values; ++i) { if (i < gr->region1start) { /* in region 0 */ h = &rsf_ht[gr->table_select[0]]; } else if (i < gr->region2start) { /* in region 1 */ h = &rsf_ht[gr->table_select[1]]; } else { /* in region 2 */ h = &rsf_ht[gr->table_select[2]]; } x = getNextSample(fromPtr); y = getNextSample(fromPtr); v = getNextSample(fromPtr); w = getNextSample(fromPtr); rsf_huffman_encoder(bv, h, x, y, v, w); } // Encode count1 area: h = &rsf_ht[gr->count1table_select+32]; while (bv.curBitIndex() < bv.totNumBits() && i < SSLIMIT*SBLIMIT) { x = getNextSample(fromPtr); y = getNextSample(fromPtr); v = getNextSample(fromPtr); w = getNextSample(fromPtr); rsf_huffman_encoder(bv, h, x, y, v, w); ++i; } return i; } static Boolean lookupHuffmanTableEntry(struct huffcodetab const* h, HUFFBITS bits, unsigned bitsLength, unsigned char& xy) { unsigned point = 0; unsigned mask = 1; unsigned numBitsTestedSoFar = 0; do { if (h->val[point][0]==0) { // end of tree xy = h->val[point][1]; if (h->hlen[xy] == 0) { // this entry hasn't already been used h->table[xy] = bits; h->hlen[xy] = bitsLength; return True; } else { // this entry has already been seen return False; } } if (numBitsTestedSoFar++ == bitsLength) { // We don't yet have enough bits for this prefix return False; } if (bits&mask) { while (h->val[point][1] >= MXOFF) point += h->val[point][1]; point += h->val[point][1]; } else { while (h->val[point][0] >= MXOFF) point += h->val[point][0]; point += h->val[point][0]; } mask <<= 1; } while (mask || (point < h->treelen)); return False; } static void buildHuffmanEncodingTable(struct huffcodetab* h) { h->table = new unsigned long[256]; h->hlen = new unsigned char[256]; if (h->table == NULL || h->hlen == NULL) { h->table = NULL; return; } for (unsigned i = 0; i < 256; ++i) { h->table[i] = 0; h->hlen[i] = 0; } // Look up entries for each possible bit sequence length: unsigned maxNumEntries = h->xlen * h->ylen; unsigned numEntries = 0; unsigned powerOf2 = 1; for (unsigned bitsLength = 1; bitsLength <= 8*SIZEOF_HUFFBITS; ++bitsLength) { powerOf2 *= 2; for (HUFFBITS bits = 0; bits < powerOf2; ++bits) { // Find the table value - if any - for 'bits' (length 'bitsLength'): unsigned char xy; if (lookupHuffmanTableEntry(h, bits, bitsLength, xy)) { ++numEntries; if (numEntries == maxNumEntries) return; // we're done } } } #ifdef DEBUG fprintf(stderr, "Didn't find enough entries!\n"); // shouldn't happen #endif } static void lookupXYandPutBits(BitVector& bv, struct huffcodetab const* h, unsigned char xy) { HUFFBITS bits = h->table[xy]; unsigned bitsLength = h->hlen[xy]; // Note that "bits" is in reverse order, so read them from right-to-left: while (bitsLength-- > 0) { bv.put1Bit(bits&0x00000001); bits >>= 1; } } static void putLinbits(BitVector& bv, struct huffcodetab const* h, HUFFBITS bits) { bv.putBits(bits, h->linbits); } static void rsf_huffman_encoder(BitVector& bv, struct huffcodetab* h, int x, int y, int v, int w) { if (h->val == NULL) return; /* table 0 produces no bits */ if (h->treelen == 0) return; if (h->table == NULL) { // We haven't yet built the encoding array for this table; do it now: buildHuffmanEncodingTable(h); if (h->table == NULL) return; } Boolean xIsNeg = False, yIsNeg = False, vIsNeg = False, wIsNeg = False; unsigned char xy; #ifdef FOUR_BYTE_SAMPLES #else #ifdef TWO_BYTE_SAMPLES // Convert 2-byte negative numbers to their 4-byte equivalents: if (x&0x8000) x |= 0xFFFF0000; if (y&0x8000) y |= 0xFFFF0000; if (v&0x8000) v |= 0xFFFF0000; if (w&0x8000) w |= 0xFFFF0000; #else // ONE_BYTE_SAMPLES // Convert 1-byte negative numbers to their 4-byte equivalents: if (x&0x80) x |= 0xFFFFFF00; if (y&0x80) y |= 0xFFFFFF00; if (v&0x80) v |= 0xFFFFFF00; if (w&0x80) w |= 0xFFFFFF00; #endif #endif if (h->tablename[0] == '3' && (h->tablename[1] == '2' || h->tablename[1] == '3')) {// quad tables if (x < 0) { xIsNeg = True; x = -x; } if (y < 0) { yIsNeg = True; y = -y; } if (v < 0) { vIsNeg = True; v = -v; } if (w < 0) { wIsNeg = True; w = -w; } // Sanity check: x,y,v,w must all be 0 or 1: if (x>1 || y>1 || v>1 || w>1) { #ifdef DEBUG fprintf(stderr, "rsf_huffman_encoder quad sanity check fails: %x,%x,%x,%x\n", x, y, v, w); #endif } xy = (v<<3)|(w<<2)|(x<<1)|y; lookupXYandPutBits(bv, h, xy); if (v) bv.put1Bit(vIsNeg); if (w) bv.put1Bit(wIsNeg); if (x) bv.put1Bit(xIsNeg); if (y) bv.put1Bit(yIsNeg); } else { // dual tables // Sanity check: v and w must be 0: if (v != 0 || w != 0) { #ifdef DEBUG fprintf(stderr, "rsf_huffman_encoder dual sanity check 1 fails: %x,%x,%x,%x\n", x, y, v, w); #endif } if (x < 0) { xIsNeg = True; x = -x; } if (y < 0) { yIsNeg = True; y = -y; } // Sanity check: x and y must be <= 255: if (x > 255 || y > 255) { #ifdef DEBUG fprintf(stderr, "rsf_huffman_encoder dual sanity check 2 fails: %x,%x,%x,%x\n", x, y, v, w); #endif } int xl1 = h->xlen-1; int yl1 = h->ylen-1; unsigned linbitsX = 0; unsigned linbitsY = 0; if (((x < xl1) || (xl1 == 0)) && (y < yl1)) { // normal case xy = (x<<4)|y; lookupXYandPutBits(bv, h, xy); if (x) bv.put1Bit(xIsNeg); if (y) bv.put1Bit(yIsNeg); } else if (x >= xl1) { linbitsX = (unsigned)(x - xl1); if (linbitsX > h->linmax) { #ifdef DEBUG fprintf(stderr,"warning: Huffman X table overflow\n"); #endif linbitsX = h->linmax; }; if (y >= yl1) { xy = (xl1<<4)|yl1; lookupXYandPutBits(bv, h, xy); linbitsY = (unsigned)(y - yl1); if (linbitsY > h->linmax) { #ifdef DEBUG fprintf(stderr,"warning: Huffman Y table overflow\n"); #endif linbitsY = h->linmax; }; if (h->linbits) putLinbits(bv, h, linbitsX); if (x) bv.put1Bit(xIsNeg); if (h->linbits) putLinbits(bv, h, linbitsY); if (y) bv.put1Bit(yIsNeg); } else { /* x >= h->xlen, y < h->ylen */ xy = (xl1<<4)|y; lookupXYandPutBits(bv, h, xy); if (h->linbits) putLinbits(bv, h, linbitsX); if (x) bv.put1Bit(xIsNeg); if (y) bv.put1Bit(yIsNeg); } } else { /* ((x < h->xlen) && (y >= h->ylen)) */ xy = (x<<4)|yl1; lookupXYandPutBits(bv, h, xy); linbitsY = y-yl1; if (linbitsY > h->linmax) { #ifdef DEBUG fprintf(stderr,"warning: Huffman Y table overflow\n"); #endif linbitsY = h->linmax; }; if (x) bv.put1Bit(xIsNeg); if (h->linbits) putLinbits(bv, h, linbitsY); if (y) bv.put1Bit(yIsNeg); } } } #endif
lgpl-2.1
bblacey/FreeCAD-MacOS-CI
src/Mod/PartDesign/Gui/ViewProviderThickness.cpp
26
2168
/*************************************************************************** * Copyright (c) 2015 Stefan Tröger <stefantroeger@gmx.net> * * * * This file is part of the FreeCAD CAx development system. * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ #endif #include "TaskThicknessParameters.h" #include "ViewProviderThickness.h" using namespace PartDesignGui; PROPERTY_SOURCE(PartDesignGui::ViewProviderThickness,PartDesignGui::ViewProviderDressUp) const std::string & ViewProviderThickness::featureName() const { static const std::string name = "Thickness"; return name; } TaskDlgFeatureParameters *ViewProviderThickness::getEditDialog() { return new TaskDlgThicknessParameters (this); }
lgpl-2.1
tomasthoresen/osg
src/osgPlugins/ive/BlinkSequence.cpp
26
2819
/********************************************************************** * * FILE: BlinkSequence.cpp * * DESCRIPTION: Read/Write osgSim::BlinkSequence in binary format to disk. * * CREATED BY: Auto generated by iveGenerator * and later modified by Rune Schmidt Jensen. * * HISTORY: Created 5.9.2003 * **********************************************************************/ #include "Exception.h" #include "BlinkSequence.h" #include "Object.h" using namespace ive; void BlinkSequence::write(DataOutputStream* out){ // Write BlinkSequence's identification. out->writeInt(IVEBLINKSEQUENCE); // If the osgSim class is inherited by any other class we should also write this to file. osg::Object* obj = dynamic_cast<osg::Object*>(this); if(obj){ ((ive::Object*)(obj))->write(out); } else out_THROW_EXCEPTION("BlinkSequence::write(): Could not cast this osgSim::BlinkSequence to an osg::Object."); // Write BlinkSequence's properties. // Write out pulse data. unsigned int size = getNumPulses(); out->writeInt(size); for(unsigned int i=0; i<size; i++){ double length; osg::Vec4 color; getPulse(i, length, color); out->writeDouble(length); out->writeVec4(color); } // Write out phase shift. out->writeDouble(getPhaseShift()); // Write out SequenceGroup. if( getSequenceGroup() ) out->writeDouble(getSequenceGroup()->_baseTime); else out->writeDouble( 0.0 ); } void BlinkSequence::read(DataInputStream* in){ // Peek on BlinkSequence's identification. int id = in->peekInt(); if(id == IVEBLINKSEQUENCE){ // Read BlinkSequence's identification. id = in->readInt(); // If the osgSim class is inherited by any other class we should also read this from file. osg::Object* obj = dynamic_cast<osg::Object*>(this); if(obj){ ((ive::Object*)(obj))->read(in); } else in_THROW_EXCEPTION("BlinkSequence::read(): Could not cast this osgSim::BlinkSequence to an osg::Object."); // Read BlinkSequence's properties // Read in pulse data. unsigned int size = in->readInt(); for(unsigned int i=0; i<size; i++){ double length = in->readDouble(); osg::Vec4 color = in->readVec4(); addPulse(length,color); } // Read in phase shift. setPhaseShift(in->readDouble()); // Read in SequenceGroup double baseTime = in->readDouble(); if (baseTime!=0.0) setSequenceGroup(new osgSim::SequenceGroup(baseTime)); } else{ in_THROW_EXCEPTION("BlinkSequence::read(): Expected BlinkSequence identification."); } }
lgpl-2.1
nicolacavallini/dealii
bundled/tbb41_20130401oss/src/rml/test/test_thread_monitor.cpp
38
4508
/* Copyright 2005-2013 Intel Corporation. All Rights Reserved. This file is part of Threading Building Blocks. Threading Building Blocks is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. Threading Building Blocks is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Threading Building Blocks; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA As a special exception, you may use this file as part of a free software library without restriction. Specifically, if other files instantiate templates or use macros or inline functions from this file, or you compile this file and link it with other files to produce an executable, this file does not by itself cause the resulting executable to be covered by the GNU General Public License. This exception does not however invalidate any other reasons why the executable file might be covered by the GNU General Public License. */ #include "harness.h" #if __TBB_MIC_OFFLOAD int TestMain () { return Harness::Skipped; } #else #include "thread_monitor.h" #include "harness_memory.h" #include "tbb/semaphore.cpp" class ThreadState { void loop(); public: static __RML_DECL_THREAD_ROUTINE routine( void* arg ) { static_cast<ThreadState*>(arg)->loop(); return 0; } typedef rml::internal::thread_monitor thread_monitor; thread_monitor monitor; volatile int request; volatile int ack; volatile unsigned clock; volatile unsigned stamp; ThreadState() : request(-1), ack(-1), clock(0) {} }; void ThreadState::loop() { for(;;) { ++clock; if( ack==request ) { thread_monitor::cookie c; monitor.prepare_wait(c); if( ack==request ) { REMARK("%p: request=%d ack=%d\n", this, request, ack ); monitor.commit_wait(c); } else monitor.cancel_wait(); } else { // Throw in delay occasionally switch( request%8 ) { case 0: case 1: case 5: rml::internal::thread_monitor::yield(); } int r = request; ack = request; if( !r ) return; } } } // Linux on IA-64 seems to require at least 1<<18 bytes per stack. const size_t MinStackSize = 1<<18; const size_t MaxStackSize = 1<<22; int TestMain () { for( int p=MinThread; p<=MaxThread; ++p ) { ThreadState* t = new ThreadState[p]; for( size_t stack_size = MinStackSize; stack_size<=MaxStackSize; stack_size*=2 ) { REMARK("launching %d threads\n",p); for( int i=0; i<p; ++i ) rml::internal::thread_monitor::launch( ThreadState::routine, t+i, stack_size ); for( int k=1000; k>=0; --k ) { if( k%8==0 ) { // Wait for threads to wait. for( int i=0; i<p; ++i ) { unsigned count = 0; do { t[i].stamp = t[i].clock; rml::internal::thread_monitor::yield(); if( ++count>=1000 ) { REPORT("Warning: thread %d not waiting\n",i); break; } } while( t[i].stamp!=t[i].clock ); } } REMARK("notifying threads\n"); for( int i=0; i<p; ++i ) { // Change state visible to launched thread t[i].request = k; t[i].monitor.notify(); } REMARK("waiting for threads to respond\n"); for( int i=0; i<p; ++i ) // Wait for thread to respond while( t[i].ack!=k ) rml::internal::thread_monitor::yield(); } } delete[] t; } return Harness::Done; } #endif /* __TBB_MIC_OFFLOAD */
lgpl-2.1
dennis-sheil/commandergenius
project/jni/freetype/src/gxvalid/gxvmort0.c
306
5011
/***************************************************************************/ /* */ /* gxvmort0.c */ /* */ /* TrueTypeGX/AAT mort table validation */ /* body for type0 (Indic Script Rearrangement) subtable. */ /* */ /* Copyright 2005 by suzuki toshiya, Masatake YAMATO, Red Hat K.K., */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /***************************************************************************/ /* */ /* gxvalid is derived from both gxlayout module and otvalid module. */ /* Development of gxlayout is supported by the Information-technology */ /* Promotion Agency(IPA), Japan. */ /* */ /***************************************************************************/ #include "gxvmort.h" /*************************************************************************/ /* */ /* The macro FT_COMPONENT is used in trace mode. It is an implicit */ /* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */ /* messages during execution. */ /* */ #undef FT_COMPONENT #define FT_COMPONENT trace_gxvmort static const char* GXV_Mort_IndicScript_Msg[] = { "no change", "Ax => xA", "xD => Dx", "AxD => DxA", "ABx => xAB", "ABx => xBA", "xCD => CDx", "xCD => DCx", "AxCD => CDxA", "AxCD => DCxA", "ABxD => DxAB", "ABxD => DxBA", "ABxCD => CDxAB", "ABxCD => CDxBA", "ABxCD => DCxAB", "ABxCD => DCxBA", }; static void gxv_mort_subtable_type0_entry_validate( FT_Byte state, FT_UShort flags, GXV_StateTable_GlyphOffsetCPtr glyphOffset_p, FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_UShort markFirst; FT_UShort dontAdvance; FT_UShort markLast; FT_UShort reserved; FT_UShort verb = 0; FT_UNUSED( state ); FT_UNUSED( table ); FT_UNUSED( limit ); FT_UNUSED( GXV_Mort_IndicScript_Msg[verb] ); /* for the non-debugging */ FT_UNUSED( glyphOffset_p ); /* case */ markFirst = (FT_UShort)( ( flags >> 15 ) & 1 ); dontAdvance = (FT_UShort)( ( flags >> 14 ) & 1 ); markLast = (FT_UShort)( ( flags >> 13 ) & 1 ); reserved = (FT_UShort)( flags & 0x1FF0 ); verb = (FT_UShort)( flags & 0x000F ); GXV_TRACE(( " IndicScript MorphRule for glyphOffset 0x%04x", glyphOffset_p->u )); GXV_TRACE(( " markFirst=%01d", markFirst )); GXV_TRACE(( " dontAdvance=%01d", dontAdvance )); GXV_TRACE(( " markLast=%01d", markLast )); GXV_TRACE(( " %02d", verb )); GXV_TRACE(( " %s\n", GXV_Mort_IndicScript_Msg[verb] )); if ( 0 < reserved ) { GXV_TRACE(( " non-zero bits found in reserved range\n" )); FT_INVALID_DATA; } else GXV_TRACE(( "\n" )); } FT_LOCAL_DEF( void ) gxv_mort_subtable_type0_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = table; GXV_NAME_ENTER( "mort chain subtable type0 (Indic-Script Rearrangement)" ); GXV_LIMIT_CHECK( GXV_STATETABLE_HEADER_SIZE ); valid->statetable.optdata = NULL; valid->statetable.optdata_load_func = NULL; valid->statetable.subtable_setup_func = NULL; valid->statetable.entry_glyphoffset_fmt = GXV_GLYPHOFFSET_NONE; valid->statetable.entry_validate_func = gxv_mort_subtable_type0_entry_validate; gxv_StateTable_validate( p, limit, valid ); GXV_EXIT; } /* END */
lgpl-2.1
mitake/tinycc
tests2/22_floating_point.c
67
1146
#include <stdio.h> #include <math.h> int main() { // variables float a = 12.34 + 56.78; printf("%f\n", a); // infix operators printf("%f\n", 12.34 + 56.78); printf("%f\n", 12.34 - 56.78); printf("%f\n", 12.34 * 56.78); printf("%f\n", 12.34 / 56.78); // comparison operators printf("%d %d %d %d %d %d\n", 12.34 < 56.78, 12.34 <= 56.78, 12.34 == 56.78, 12.34 >= 56.78, 12.34 > 56.78, 12.34 != 56.78); printf("%d %d %d %d %d %d\n", 12.34 < 12.34, 12.34 <= 12.34, 12.34 == 12.34, 12.34 >= 12.34, 12.34 > 12.34, 12.34 != 12.34); printf("%d %d %d %d %d %d\n", 56.78 < 12.34, 56.78 <= 12.34, 56.78 == 12.34, 56.78 >= 12.34, 56.78 > 12.34, 56.78 != 12.34); // assignment operators a = 12.34; a += 56.78; printf("%f\n", a); a = 12.34; a -= 56.78; printf("%f\n", a); a = 12.34; a *= 56.78; printf("%f\n", a); a = 12.34; a /= 56.78; printf("%f\n", a); // prefix operators printf("%f\n", +12.34); printf("%f\n", -12.34); // type coercion a = 2; printf("%f\n", a); printf("%f\n", sin(2)); return 0; } /* vim: set expandtab ts=4 sw=3 sts=3 tw=80 :*/
lgpl-2.1
ruler501/pSDL
src/video/ataricommon/SDL_atarigl.c
80
24890
/* SDL - Simple DirectMedia Layer Copyright (C) 1997-2012 Sam Lantinga This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Sam Lantinga slouken@libsdl.org */ #include "SDL_config.h" /* Atari OSMesa.ldg implementation of SDL OpenGL support */ /*--- Includes ---*/ #if SDL_VIDEO_OPENGL #include <GL/osmesa.h> #endif #include <mint/osbind.h> #include "SDL_endian.h" #include "SDL_video.h" #include "SDL_atarigl_c.h" #if SDL_VIDEO_OPENGL_OSMESA_DYNAMIC #include "SDL_loadso.h" #endif /*--- Defines ---*/ #define PATH_OSMESA_LDG "osmesa.ldg" #define PATH_MESAGL_LDG "mesa_gl.ldg" #define PATH_TINYGL_LDG "tiny_gl.ldg" #define VDI_RGB 0xf /*--- Functions prototypes ---*/ #if SDL_VIDEO_OPENGL static void SDL_AtariGL_UnloadLibrary(_THIS); static void CopyShadowNull(_THIS, SDL_Surface *surface); static void CopyShadowDirect(_THIS, SDL_Surface *surface); static void CopyShadowRGBTo555(_THIS, SDL_Surface *surface); static void CopyShadowRGBTo565(_THIS, SDL_Surface *surface); static void CopyShadowRGBSwap(_THIS, SDL_Surface *surface); static void CopyShadowRGBToARGB(_THIS, SDL_Surface *surface); static void CopyShadowRGBToABGR(_THIS, SDL_Surface *surface); static void CopyShadowRGBToBGRA(_THIS, SDL_Surface *surface); static void CopyShadowRGBToRGBA(_THIS, SDL_Surface *surface); static void CopyShadow8888To555(_THIS, SDL_Surface *surface); static void CopyShadow8888To565(_THIS, SDL_Surface *surface); static void ConvertNull(_THIS, SDL_Surface *surface); static void Convert565To555be(_THIS, SDL_Surface *surface); static void Convert565To555le(_THIS, SDL_Surface *surface); static void Convert565le(_THIS, SDL_Surface *surface); static void ConvertBGRAToABGR(_THIS, SDL_Surface *surface); static int InitNew(_THIS, SDL_Surface *current); static int InitOld(_THIS, SDL_Surface *current); #endif /*--- Public functions ---*/ int SDL_AtariGL_Init(_THIS, SDL_Surface *current) { #if SDL_VIDEO_OPENGL if (gl_oldmesa) { gl_active = InitOld(this, current); } else { gl_active = InitNew(this, current); } #endif return (gl_active); } void SDL_AtariGL_Quit(_THIS, SDL_bool unload) { #if SDL_VIDEO_OPENGL if (gl_oldmesa) { /* Old mesa implementations */ if (this->gl_data->OSMesaDestroyLDG) { this->gl_data->OSMesaDestroyLDG(); } if (gl_shadow) { Mfree(gl_shadow); gl_shadow = NULL; } } else { /* New mesa implementation */ if (gl_ctx) { if (this->gl_data->OSMesaDestroyContext) { this->gl_data->OSMesaDestroyContext(gl_ctx); } gl_ctx = NULL; } } if (unload) { SDL_AtariGL_UnloadLibrary(this); } #endif /* SDL_VIDEO_OPENGL */ gl_active = 0; } int SDL_AtariGL_LoadLibrary(_THIS, const char *path) { #if SDL_VIDEO_OPENGL #if SDL_VIDEO_OPENGL_OSMESA_DYNAMIC void *handle; SDL_bool cancel_load; if (gl_active) { SDL_SetError("OpenGL context already created"); return -1; } /* Unload previous driver */ SDL_AtariGL_UnloadLibrary(this); /* Load library given by path */ handle = SDL_LoadObject(path); if (handle == NULL) { /* Try to load another one */ path = SDL_getenv("SDL_VIDEO_GL_DRIVER"); if ( path != NULL ) { handle = SDL_LoadObject(path); } /* If it does not work, try some other */ if (handle == NULL) { path = PATH_OSMESA_LDG; handle = SDL_LoadObject(path); } if (handle == NULL) { path = PATH_MESAGL_LDG; handle = SDL_LoadObject(path); } if (handle == NULL) { path = PATH_TINYGL_LDG; handle = SDL_LoadObject(path); } } if (handle == NULL) { SDL_SetError("Could not load OpenGL library"); return -1; } this->gl_data->glGetIntegerv = SDL_LoadFunction(handle, "glGetIntegerv"); this->gl_data->glFinish = SDL_LoadFunction(handle, "glFinish"); this->gl_data->glFlush = SDL_LoadFunction(handle, "glFlush"); cancel_load = SDL_FALSE; if (this->gl_data->glGetIntegerv == NULL) { cancel_load = SDL_TRUE; } else { /* We need either glFinish (OSMesa) or glFlush (TinyGL) */ if ((this->gl_data->glFinish == NULL) && (this->gl_data->glFlush == NULL)) { cancel_load = SDL_TRUE; } } if (cancel_load) { SDL_SetError("Could not retrieve OpenGL functions"); SDL_UnloadObject(handle); /* Restore pointers to static library */ SDL_AtariGL_InitPointers(this); return -1; } /* Load functions pointers (osmesa.ldg) */ this->gl_data->OSMesaCreateContextExt = SDL_LoadFunction(handle, "OSMesaCreateContextExt"); this->gl_data->OSMesaDestroyContext = SDL_LoadFunction(handle, "OSMesaDestroyContext"); this->gl_data->OSMesaMakeCurrent = SDL_LoadFunction(handle, "OSMesaMakeCurrent"); this->gl_data->OSMesaPixelStore = SDL_LoadFunction(handle, "OSMesaPixelStore"); this->gl_data->OSMesaGetProcAddress = SDL_LoadFunction(handle, "OSMesaGetProcAddress"); /* Load old functions pointers (mesa_gl.ldg, tiny_gl.ldg) */ this->gl_data->OSMesaCreateLDG = SDL_LoadFunction(handle, "OSMesaCreateLDG"); this->gl_data->OSMesaDestroyLDG = SDL_LoadFunction(handle, "OSMesaDestroyLDG"); gl_oldmesa = 0; if ( (this->gl_data->OSMesaCreateContextExt == NULL) || (this->gl_data->OSMesaDestroyContext == NULL) || (this->gl_data->OSMesaMakeCurrent == NULL) || (this->gl_data->OSMesaPixelStore == NULL) || (this->gl_data->OSMesaGetProcAddress == NULL)) { /* Hum, maybe old library ? */ if ( (this->gl_data->OSMesaCreateLDG == NULL) || (this->gl_data->OSMesaDestroyLDG == NULL)) { SDL_SetError("Could not retrieve OSMesa functions"); SDL_UnloadObject(handle); /* Restore pointers to static library */ SDL_AtariGL_InitPointers(this); return -1; } else { gl_oldmesa = 1; } } this->gl_config.dll_handle = handle; if ( path ) { SDL_strlcpy(this->gl_config.driver_path, path, SDL_arraysize(this->gl_config.driver_path)); } else { *this->gl_config.driver_path = '\0'; } #endif this->gl_config.driver_loaded = 1; return 0; #else return -1; #endif } void *SDL_AtariGL_GetProcAddress(_THIS, const char *proc) { void *func = NULL; #if SDL_VIDEO_OPENGL if (this->gl_config.dll_handle) { func = SDL_LoadFunction(this->gl_config.dll_handle, (void *)proc); } else if (this->gl_data->OSMesaGetProcAddress) { func = this->gl_data->OSMesaGetProcAddress(proc); } #endif return func; } int SDL_AtariGL_GetAttribute(_THIS, SDL_GLattr attrib, int* value) { #if SDL_VIDEO_OPENGL GLenum mesa_attrib; SDL_Surface *surface; if (!gl_active) { return -1; } switch(attrib) { case SDL_GL_RED_SIZE: mesa_attrib = GL_RED_BITS; break; case SDL_GL_GREEN_SIZE: mesa_attrib = GL_GREEN_BITS; break; case SDL_GL_BLUE_SIZE: mesa_attrib = GL_BLUE_BITS; break; case SDL_GL_ALPHA_SIZE: mesa_attrib = GL_ALPHA_BITS; break; case SDL_GL_DOUBLEBUFFER: surface = this->screen; *value = ((surface->flags & SDL_DOUBLEBUF)==SDL_DOUBLEBUF); return 0; case SDL_GL_DEPTH_SIZE: mesa_attrib = GL_DEPTH_BITS; break; case SDL_GL_STENCIL_SIZE: mesa_attrib = GL_STENCIL_BITS; break; case SDL_GL_ACCUM_RED_SIZE: mesa_attrib = GL_ACCUM_RED_BITS; break; case SDL_GL_ACCUM_GREEN_SIZE: mesa_attrib = GL_ACCUM_GREEN_BITS; break; case SDL_GL_ACCUM_BLUE_SIZE: mesa_attrib = GL_ACCUM_BLUE_BITS; break; case SDL_GL_ACCUM_ALPHA_SIZE: mesa_attrib = GL_ACCUM_ALPHA_BITS; break; default : return -1; } this->gl_data->glGetIntegerv(mesa_attrib, value); return 0; #else return -1; #endif } int SDL_AtariGL_MakeCurrent(_THIS) { #if SDL_VIDEO_OPENGL SDL_Surface *surface; GLenum type; if (gl_oldmesa && gl_active) { return 0; } if (this->gl_config.dll_handle) { if ((this->gl_data->OSMesaMakeCurrent == NULL) || (this->gl_data->OSMesaPixelStore == NULL)) { return -1; } } if (!gl_active) { SDL_SetError("Invalid OpenGL context"); return -1; } surface = this->screen; if ((surface->format->BitsPerPixel == 15) || (surface->format->BitsPerPixel == 16)) { type = GL_UNSIGNED_SHORT_5_6_5; } else { type = GL_UNSIGNED_BYTE; } if (!(this->gl_data->OSMesaMakeCurrent(gl_ctx, surface->pixels, type, surface->w, surface->h))) { SDL_SetError("Can not make OpenGL context current"); return -1; } /* OSMesa draws upside down */ this->gl_data->OSMesaPixelStore(OSMESA_Y_UP, 0); return 0; #else return -1; #endif } void SDL_AtariGL_SwapBuffers(_THIS) { #if SDL_VIDEO_OPENGL if (gl_active) { if (this->gl_config.dll_handle) { if (this->gl_data->glFinish) { this->gl_data->glFinish(); } else if (this->gl_data->glFlush) { this->gl_data->glFlush(); } } else { this->gl_data->glFinish(); } gl_copyshadow(this, this->screen); gl_convert(this, this->screen); } #endif } void SDL_AtariGL_InitPointers(_THIS) { #if SDL_VIDEO_OPENGL this->gl_data->OSMesaCreateContextExt = OSMesaCreateContextExt; this->gl_data->OSMesaDestroyContext = OSMesaDestroyContext; this->gl_data->OSMesaMakeCurrent = OSMesaMakeCurrent; this->gl_data->OSMesaPixelStore = OSMesaPixelStore; this->gl_data->OSMesaGetProcAddress = OSMesaGetProcAddress; this->gl_data->glGetIntegerv = glGetIntegerv; this->gl_data->glFinish = glFinish; this->gl_data->glFlush = glFlush; this->gl_data->OSMesaCreateLDG = NULL; this->gl_data->OSMesaDestroyLDG = NULL; #endif } /*--- Private functions ---*/ #if SDL_VIDEO_OPENGL static void SDL_AtariGL_UnloadLibrary(_THIS) { if (this->gl_config.dll_handle) { SDL_UnloadObject(this->gl_config.dll_handle); this->gl_config.dll_handle = NULL; /* Restore pointers to static library */ SDL_AtariGL_InitPointers(this); } } /*--- Creation of an OpenGL context using new/old functions ---*/ static int InitNew(_THIS, SDL_Surface *current) { GLenum osmesa_format; SDL_PixelFormat *pixel_format; Uint32 redmask; int recreatecontext; GLint newaccumsize; if (this->gl_config.dll_handle) { if (this->gl_data->OSMesaCreateContextExt == NULL) { return 0; } } /* Init OpenGL context using OSMesa */ gl_convert = ConvertNull; gl_copyshadow = CopyShadowNull; gl_upsidedown = SDL_FALSE; pixel_format = current->format; redmask = pixel_format->Rmask; switch (pixel_format->BitsPerPixel) { case 15: /* 1555, big and little endian, unsupported */ gl_pixelsize = 2; osmesa_format = OSMESA_RGB_565; if (redmask == 31<<10) { gl_convert = Convert565To555be; } else { gl_convert = Convert565To555le; } break; case 16: gl_pixelsize = 2; if (redmask == 31<<11) { osmesa_format = OSMESA_RGB_565; } else { /* 565, little endian, unsupported */ osmesa_format = OSMESA_RGB_565; gl_convert = Convert565le; } break; case 24: gl_pixelsize = 3; if (redmask == 255<<16) { osmesa_format = OSMESA_RGB; } else { osmesa_format = OSMESA_BGR; } break; case 32: gl_pixelsize = 4; if (redmask == 255<<16) { osmesa_format = OSMESA_ARGB; } else if (redmask == 255<<8) { osmesa_format = OSMESA_BGRA; } else if (redmask == 255<<24) { osmesa_format = OSMESA_RGBA; } else { /* ABGR format unsupported */ osmesa_format = OSMESA_BGRA; gl_convert = ConvertBGRAToABGR; } break; default: gl_pixelsize = 1; osmesa_format = OSMESA_COLOR_INDEX; break; } /* Try to keep current context if possible */ newaccumsize = this->gl_config.accum_red_size + this->gl_config.accum_green_size + this->gl_config.accum_blue_size + this->gl_config.accum_alpha_size; recreatecontext=1; if (gl_ctx && (gl_curformat == osmesa_format) && (gl_curdepth == this->gl_config.depth_size) && (gl_curstencil == this->gl_config.stencil_size) && (gl_curaccum == newaccumsize)) { recreatecontext = 0; } if (recreatecontext) { SDL_AtariGL_Quit(this, SDL_FALSE); gl_ctx = this->gl_data->OSMesaCreateContextExt( osmesa_format, this->gl_config.depth_size, this->gl_config.stencil_size, newaccumsize, NULL ); if (gl_ctx) { gl_curformat = osmesa_format; gl_curdepth = this->gl_config.depth_size; gl_curstencil = this->gl_config.stencil_size; gl_curaccum = newaccumsize; } else { gl_curformat = 0; gl_curdepth = 0; gl_curstencil = 0; gl_curaccum = 0; } } return (gl_ctx != NULL); } static int InitOld(_THIS, SDL_Surface *current) { GLenum osmesa_format; SDL_PixelFormat *pixel_format; Uint32 redmask; int recreatecontext, tinygl_present; if (this->gl_config.dll_handle) { if (this->gl_data->OSMesaCreateLDG == NULL) { return 0; } } /* TinyGL only supports VDI_RGB (OSMESA_RGB) */ tinygl_present=0; if (this->gl_config.dll_handle) { if (this->gl_data->glFinish == NULL) { tinygl_present=1; } } /* Init OpenGL context using OSMesa */ gl_convert = ConvertNull; gl_copyshadow = CopyShadowNull; gl_upsidedown = SDL_FALSE; pixel_format = current->format; redmask = pixel_format->Rmask; switch (pixel_format->BitsPerPixel) { case 15: /* 15 bits unsupported */ if (tinygl_present) { gl_pixelsize = 3; osmesa_format = VDI_RGB; if (redmask == 31<<10) { gl_copyshadow = CopyShadowRGBTo555; } else { gl_copyshadow = CopyShadowRGBTo565; gl_convert = Convert565To555le; } } else { gl_pixelsize = 4; gl_upsidedown = SDL_TRUE; osmesa_format = OSMESA_ARGB; if (redmask == 31<<10) { gl_copyshadow = CopyShadow8888To555; } else { gl_copyshadow = CopyShadow8888To565; gl_convert = Convert565To555le; } } break; case 16: /* 16 bits unsupported */ if (tinygl_present) { gl_pixelsize = 3; osmesa_format = VDI_RGB; gl_copyshadow = CopyShadowRGBTo565; if (redmask != 31<<11) { /* 565, little endian, unsupported */ gl_convert = Convert565le; } } else { gl_pixelsize = 4; gl_upsidedown = SDL_TRUE; osmesa_format = OSMESA_ARGB; gl_copyshadow = CopyShadow8888To565; if (redmask != 31<<11) { /* 565, little endian, unsupported */ gl_convert = Convert565le; } } break; case 24: gl_pixelsize = 3; if (tinygl_present) { osmesa_format = VDI_RGB; gl_copyshadow = CopyShadowDirect; if (redmask != 255<<16) { gl_copyshadow = CopyShadowRGBSwap; } } else { gl_copyshadow = CopyShadowDirect; gl_upsidedown = SDL_TRUE; if (redmask == 255<<16) { osmesa_format = OSMESA_RGB; } else { osmesa_format = OSMESA_BGR; } } break; case 32: if (tinygl_present) { gl_pixelsize = 3; osmesa_format = VDI_RGB; gl_copyshadow = CopyShadowRGBToARGB; if (redmask == 255) { gl_convert = CopyShadowRGBToABGR; } else if (redmask == 255<<8) { gl_convert = CopyShadowRGBToBGRA; } else if (redmask == 255<<24) { gl_convert = CopyShadowRGBToRGBA; } } else { gl_pixelsize = 4; gl_upsidedown = SDL_TRUE; gl_copyshadow = CopyShadowDirect; if (redmask == 255<<16) { osmesa_format = OSMESA_ARGB; } else if (redmask == 255<<8) { osmesa_format = OSMESA_BGRA; } else if (redmask == 255<<24) { osmesa_format = OSMESA_RGBA; } else { /* ABGR format unsupported */ osmesa_format = OSMESA_BGRA; gl_convert = ConvertBGRAToABGR; } } break; default: if (tinygl_present) { SDL_AtariGL_Quit(this, SDL_FALSE); return 0; } gl_pixelsize = 1; gl_copyshadow = CopyShadowDirect; osmesa_format = OSMESA_COLOR_INDEX; break; } /* Try to keep current context if possible */ recreatecontext=1; if (gl_shadow && (gl_curformat == osmesa_format) && (gl_curwidth == current->w) && (gl_curheight == current->h)) { recreatecontext = 0; } if (recreatecontext) { SDL_AtariGL_Quit(this, SDL_FALSE); gl_shadow = this->gl_data->OSMesaCreateLDG( osmesa_format, GL_UNSIGNED_BYTE, current->w, current->h ); if (gl_shadow) { gl_curformat = osmesa_format; gl_curwidth = current->w; gl_curheight = current->h; } else { gl_curformat = 0; gl_curwidth = 0; gl_curheight = 0; } } return (gl_shadow != NULL); } /*--- Conversions routines from shadow buffer to the screen ---*/ static void CopyShadowNull(_THIS, SDL_Surface *surface) { } static void CopyShadowDirect(_THIS, SDL_Surface *surface) { int y, srcpitch, dstpitch; Uint8 *srcline, *dstline; srcline = gl_shadow; srcpitch = surface->w * gl_pixelsize; dstline = surface->pixels; dstpitch = surface->pitch; if (gl_upsidedown) { srcline += (surface->h-1)*srcpitch; srcpitch = -srcpitch; } for (y=0; y<surface->h; y++) { SDL_memcpy(dstline, srcline, srcpitch); srcline += srcpitch; dstline += dstpitch; } } static void CopyShadowRGBTo555(_THIS, SDL_Surface *surface) { int x,y, srcpitch, dstpitch; Uint16 *dstline, *dstcol; Uint8 *srcline, *srccol; srcline = (Uint8 *)gl_shadow; srcpitch = surface->w * gl_pixelsize; dstline = surface->pixels; dstpitch = surface->pitch >>1; if (gl_upsidedown) { srcline += (surface->h-1)*srcpitch; srcpitch = -srcpitch; } for (y=0; y<surface->h; y++) { srccol = srcline; dstcol = dstline; for (x=0; x<surface->w; x++) { Uint16 dstcolor; dstcolor = ((*srccol++)<<7) & (31<<10); dstcolor |= ((*srccol++)<<2) & (31<<5); dstcolor |= ((*srccol++)>>3) & 31; *dstcol++ = dstcolor; } srcline += srcpitch; dstline += dstpitch; } } static void CopyShadowRGBTo565(_THIS, SDL_Surface *surface) { int x,y, srcpitch, dstpitch; Uint16 *dstline, *dstcol; Uint8 *srcline, *srccol; srcline = (Uint8 *)gl_shadow; srcpitch = surface->w * gl_pixelsize; dstline = surface->pixels; dstpitch = surface->pitch >>1; if (gl_upsidedown) { srcline += (surface->h-1)*srcpitch; srcpitch = -srcpitch; } for (y=0; y<surface->h; y++) { srccol = srcline; dstcol = dstline; for (x=0; x<surface->w; x++) { Uint16 dstcolor; dstcolor = ((*srccol++)<<8) & (31<<11); dstcolor |= ((*srccol++)<<3) & (63<<5); dstcolor |= ((*srccol++)>>3) & 31; *dstcol++ = dstcolor; } srcline += srcpitch; dstline += dstpitch; } } static void CopyShadowRGBSwap(_THIS, SDL_Surface *surface) { int x,y, srcpitch, dstpitch; Uint8 *dstline, *dstcol; Uint8 *srcline, *srccol; srcline = (Uint8 *)gl_shadow; srcpitch = surface->w * gl_pixelsize; dstline = surface->pixels; dstpitch = surface->pitch; if (gl_upsidedown) { srcline += (surface->h-1)*srcpitch; srcpitch = -srcpitch; } for (y=0; y<surface->h; y++) { srccol = srcline; dstcol = dstline; for (x=0; x<surface->w; x++) { *dstcol++ = srccol[2]; *dstcol++ = srccol[1]; *dstcol++ = srccol[0]; srccol += 3; } srcline += srcpitch; dstline += dstpitch; } } static void CopyShadowRGBToARGB(_THIS, SDL_Surface *surface) { int x,y, srcpitch, dstpitch; Uint32 *dstline, *dstcol; Uint8 *srcline, *srccol; srcline = (Uint8 *)gl_shadow; srcpitch = surface->w * gl_pixelsize; dstline = surface->pixels; dstpitch = surface->pitch >>2; if (gl_upsidedown) { srcline += (surface->h-1)*srcpitch; srcpitch = -srcpitch; } for (y=0; y<surface->h; y++) { srccol = srcline; dstcol = dstline; for (x=0; x<surface->w; x++) { Uint32 dstcolor; dstcolor = (*srccol++)<<16; dstcolor |= (*srccol++)<<8; dstcolor |= *srccol++; *dstcol++ = dstcolor; } srcline += srcpitch; dstline += dstpitch; } } static void CopyShadowRGBToABGR(_THIS, SDL_Surface *surface) { int x,y, srcpitch, dstpitch; Uint32 *dstline, *dstcol; Uint8 *srcline, *srccol; srcline = (Uint8 *)gl_shadow; srcpitch = surface->w * gl_pixelsize; dstline = surface->pixels; dstpitch = surface->pitch >>2; if (gl_upsidedown) { srcline += (surface->h-1)*srcpitch; srcpitch = -srcpitch; } for (y=0; y<surface->h; y++) { srccol = srcline; dstcol = dstline; for (x=0; x<surface->w; x++) { Uint32 dstcolor; dstcolor = *srccol++; dstcolor |= (*srccol++)<<8; dstcolor |= (*srccol++)<<16; *dstcol++ = dstcolor; } srcline += srcpitch; dstline += dstpitch; } } static void CopyShadowRGBToBGRA(_THIS, SDL_Surface *surface) { int x,y, srcpitch, dstpitch; Uint32 *dstline, *dstcol; Uint8 *srcline, *srccol; srcline = (Uint8 *)gl_shadow; srcpitch = surface->w * gl_pixelsize; dstline = surface->pixels; dstpitch = surface->pitch >>2; if (gl_upsidedown) { srcline += (surface->h-1)*srcpitch; srcpitch = -srcpitch; } for (y=0; y<surface->h; y++) { srccol = srcline; dstcol = dstline; for (x=0; x<surface->w; x++) { Uint32 dstcolor; dstcolor = (*srccol++)<<8; dstcolor |= (*srccol++)<<16; dstcolor |= (*srccol++)<<24; *dstcol++ = dstcolor; } srcline += srcpitch; dstline += dstpitch; } } static void CopyShadowRGBToRGBA(_THIS, SDL_Surface *surface) { int x,y, srcpitch, dstpitch; Uint32 *dstline, *dstcol; Uint8 *srcline, *srccol; srcline = (Uint8 *)gl_shadow; srcpitch = surface->w * gl_pixelsize; dstline = surface->pixels; dstpitch = surface->pitch >>2; if (gl_upsidedown) { srcline += (surface->h-1)*srcpitch; srcpitch = -srcpitch; } for (y=0; y<surface->h; y++) { srccol = srcline; dstcol = dstline; for (x=0; x<surface->w; x++) { Uint32 dstcolor; dstcolor = (*srccol++)<<24; dstcolor |= (*srccol++)<<16; dstcolor |= (*srccol++)<<8; *dstcol++ = dstcolor; } srcline += srcpitch; dstline += dstpitch; } } static void CopyShadow8888To555(_THIS, SDL_Surface *surface) { int x,y, srcpitch, dstpitch; Uint16 *dstline, *dstcol; Uint32 *srcline, *srccol; srcline = (Uint32 *)gl_shadow; srcpitch = (surface->w * gl_pixelsize) >>2; dstline = surface->pixels; dstpitch = surface->pitch >>1; if (gl_upsidedown) { srcline += (surface->h-1)*srcpitch; srcpitch = -srcpitch; } for (y=0; y<surface->h; y++) { srccol = srcline; dstcol = dstline; for (x=0; x<surface->w; x++) { Uint32 srccolor; Uint16 dstcolor; srccolor = *srccol++; dstcolor = (srccolor>>9) & (31<<10); dstcolor |= (srccolor>>6) & (31<<5); dstcolor |= (srccolor>>3) & 31; *dstcol++ = dstcolor; } srcline += srcpitch; dstline += dstpitch; } } static void CopyShadow8888To565(_THIS, SDL_Surface *surface) { int x,y, srcpitch, dstpitch; Uint16 *dstline, *dstcol; Uint32 *srcline, *srccol; srcline = (Uint32 *)gl_shadow; srcpitch = (surface->w * gl_pixelsize) >> 2; dstline = surface->pixels; dstpitch = surface->pitch >>1; if (gl_upsidedown) { srcline += (surface->h-1)*srcpitch; srcpitch = -srcpitch; } for (y=0; y<surface->h; y++) { srccol = srcline; dstcol = dstline; for (x=0; x<surface->w; x++) { Uint32 srccolor; Uint16 dstcolor; srccolor = *srccol++; dstcolor = (srccolor>>8) & (31<<11); dstcolor |= (srccolor>>5) & (63<<5); dstcolor |= (srccolor>>3) & 31; *dstcol++ = dstcolor; } srcline += srcpitch; dstline += dstpitch; } } /*--- Conversions routines in the screen ---*/ static void ConvertNull(_THIS, SDL_Surface *surface) { } static void Convert565To555be(_THIS, SDL_Surface *surface) { int x,y, pitch; unsigned short *line, *pixel; line = surface->pixels; pitch = surface->pitch >> 1; for (y=0; y<surface->h; y++) { pixel = line; for (x=0; x<surface->w; x++) { unsigned short color = *pixel; *pixel++ = (color & 0x1f)|((color>>1) & 0xffe0); } line += pitch; } } static void Convert565To555le(_THIS, SDL_Surface *surface) { int x,y, pitch; unsigned short *line, *pixel; line = surface->pixels; pitch = surface->pitch >>1; for (y=0; y<surface->h; y++) { pixel = line; for (x=0; x<surface->w; x++) { unsigned short color = *pixel; color = (color & 0x1f)|((color>>1) & 0xffe0); *pixel++ = SDL_Swap16(color); } line += pitch; } } static void Convert565le(_THIS, SDL_Surface *surface) { int x,y, pitch; unsigned short *line, *pixel; line = surface->pixels; pitch = surface->pitch >>1; for (y=0; y<surface->h; y++) { pixel = line; for (x=0; x<surface->w; x++) { unsigned short color = *pixel; *pixel++ = SDL_Swap16(color); } line += pitch; } } static void ConvertBGRAToABGR(_THIS, SDL_Surface *surface) { int x,y, pitch; unsigned long *line, *pixel; line = surface->pixels; pitch = surface->pitch >>2; for (y=0; y<surface->h; y++) { pixel = line; for (x=0; x<surface->w; x++) { unsigned long color = *pixel; *pixel++ = (color<<24)|(color>>8); } line += pitch; } } #endif /* SDL_VIDEO_OPENGL */
lgpl-2.1
brammittendorff/PF_RING
linux-3.16.7-ckt9/drivers/acpi/acpica/rsio.c
600
9211
/******************************************************************************* * * Module Name: rsio - IO and DMA resource descriptors * ******************************************************************************/ /* * Copyright (C) 2000 - 2014, Intel Corp. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * Alternatively, this software may be distributed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * * NO WARRANTY * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGES. */ #include <acpi/acpi.h> #include "accommon.h" #include "acresrc.h" #define _COMPONENT ACPI_RESOURCES ACPI_MODULE_NAME("rsio") /******************************************************************************* * * acpi_rs_convert_io * ******************************************************************************/ struct acpi_rsconvert_info acpi_rs_convert_io[5] = { {ACPI_RSC_INITGET, ACPI_RESOURCE_TYPE_IO, ACPI_RS_SIZE(struct acpi_resource_io), ACPI_RSC_TABLE_SIZE(acpi_rs_convert_io)}, {ACPI_RSC_INITSET, ACPI_RESOURCE_NAME_IO, sizeof(struct aml_resource_io), 0}, /* Decode flag */ {ACPI_RSC_1BITFLAG, ACPI_RS_OFFSET(data.io.io_decode), AML_OFFSET(io.flags), 0}, /* * These fields are contiguous in both the source and destination: * Address Alignment * Length * Minimum Base Address * Maximum Base Address */ {ACPI_RSC_MOVE8, ACPI_RS_OFFSET(data.io.alignment), AML_OFFSET(io.alignment), 2}, {ACPI_RSC_MOVE16, ACPI_RS_OFFSET(data.io.minimum), AML_OFFSET(io.minimum), 2} }; /******************************************************************************* * * acpi_rs_convert_fixed_io * ******************************************************************************/ struct acpi_rsconvert_info acpi_rs_convert_fixed_io[4] = { {ACPI_RSC_INITGET, ACPI_RESOURCE_TYPE_FIXED_IO, ACPI_RS_SIZE(struct acpi_resource_fixed_io), ACPI_RSC_TABLE_SIZE(acpi_rs_convert_fixed_io)}, {ACPI_RSC_INITSET, ACPI_RESOURCE_NAME_FIXED_IO, sizeof(struct aml_resource_fixed_io), 0}, /* * These fields are contiguous in both the source and destination: * Base Address * Length */ {ACPI_RSC_MOVE8, ACPI_RS_OFFSET(data.fixed_io.address_length), AML_OFFSET(fixed_io.address_length), 1}, {ACPI_RSC_MOVE16, ACPI_RS_OFFSET(data.fixed_io.address), AML_OFFSET(fixed_io.address), 1} }; /******************************************************************************* * * acpi_rs_convert_generic_reg * ******************************************************************************/ struct acpi_rsconvert_info acpi_rs_convert_generic_reg[4] = { {ACPI_RSC_INITGET, ACPI_RESOURCE_TYPE_GENERIC_REGISTER, ACPI_RS_SIZE(struct acpi_resource_generic_register), ACPI_RSC_TABLE_SIZE(acpi_rs_convert_generic_reg)}, {ACPI_RSC_INITSET, ACPI_RESOURCE_NAME_GENERIC_REGISTER, sizeof(struct aml_resource_generic_register), 0}, /* * These fields are contiguous in both the source and destination: * Address Space ID * Register Bit Width * Register Bit Offset * Access Size */ {ACPI_RSC_MOVE8, ACPI_RS_OFFSET(data.generic_reg.space_id), AML_OFFSET(generic_reg.address_space_id), 4}, /* Get the Register Address */ {ACPI_RSC_MOVE64, ACPI_RS_OFFSET(data.generic_reg.address), AML_OFFSET(generic_reg.address), 1} }; /******************************************************************************* * * acpi_rs_convert_end_dpf * ******************************************************************************/ struct acpi_rsconvert_info acpi_rs_convert_end_dpf[2] = { {ACPI_RSC_INITGET, ACPI_RESOURCE_TYPE_END_DEPENDENT, ACPI_RS_SIZE_MIN, ACPI_RSC_TABLE_SIZE(acpi_rs_convert_end_dpf)}, {ACPI_RSC_INITSET, ACPI_RESOURCE_NAME_END_DEPENDENT, sizeof(struct aml_resource_end_dependent), 0} }; /******************************************************************************* * * acpi_rs_convert_end_tag * ******************************************************************************/ struct acpi_rsconvert_info acpi_rs_convert_end_tag[2] = { {ACPI_RSC_INITGET, ACPI_RESOURCE_TYPE_END_TAG, ACPI_RS_SIZE_MIN, ACPI_RSC_TABLE_SIZE(acpi_rs_convert_end_tag)}, /* * Note: The checksum field is set to zero, meaning that the resource * data is treated as if the checksum operation succeeded. * (ACPI Spec 1.0b Section 6.4.2.8) */ {ACPI_RSC_INITSET, ACPI_RESOURCE_NAME_END_TAG, sizeof(struct aml_resource_end_tag), 0} }; /******************************************************************************* * * acpi_rs_get_start_dpf * ******************************************************************************/ struct acpi_rsconvert_info acpi_rs_get_start_dpf[6] = { {ACPI_RSC_INITGET, ACPI_RESOURCE_TYPE_START_DEPENDENT, ACPI_RS_SIZE(struct acpi_resource_start_dependent), ACPI_RSC_TABLE_SIZE(acpi_rs_get_start_dpf)}, /* Defaults for Compatibility and Performance priorities */ {ACPI_RSC_SET8, ACPI_RS_OFFSET(data.start_dpf.compatibility_priority), ACPI_ACCEPTABLE_CONFIGURATION, 2}, /* Get the descriptor length (0 or 1 for Start Dpf descriptor) */ {ACPI_RSC_1BITFLAG, ACPI_RS_OFFSET(data.start_dpf.descriptor_length), AML_OFFSET(start_dpf.descriptor_type), 0}, /* All done if there is no flag byte present in the descriptor */ {ACPI_RSC_EXIT_NE, ACPI_RSC_COMPARE_AML_LENGTH, 0, 1}, /* Flag byte is present, get the flags */ {ACPI_RSC_2BITFLAG, ACPI_RS_OFFSET(data.start_dpf.compatibility_priority), AML_OFFSET(start_dpf.flags), 0}, {ACPI_RSC_2BITFLAG, ACPI_RS_OFFSET(data.start_dpf.performance_robustness), AML_OFFSET(start_dpf.flags), 2} }; /******************************************************************************* * * acpi_rs_set_start_dpf * ******************************************************************************/ struct acpi_rsconvert_info acpi_rs_set_start_dpf[10] = { /* Start with a default descriptor of length 1 */ {ACPI_RSC_INITSET, ACPI_RESOURCE_NAME_START_DEPENDENT, sizeof(struct aml_resource_start_dependent), ACPI_RSC_TABLE_SIZE(acpi_rs_set_start_dpf)}, /* Set the default flag values */ {ACPI_RSC_2BITFLAG, ACPI_RS_OFFSET(data.start_dpf.compatibility_priority), AML_OFFSET(start_dpf.flags), 0}, {ACPI_RSC_2BITFLAG, ACPI_RS_OFFSET(data.start_dpf.performance_robustness), AML_OFFSET(start_dpf.flags), 2}, /* * All done if the output descriptor length is required to be 1 * (i.e., optimization to 0 bytes cannot be attempted) */ {ACPI_RSC_EXIT_EQ, ACPI_RSC_COMPARE_VALUE, ACPI_RS_OFFSET(data.start_dpf.descriptor_length), 1}, /* Set length to 0 bytes (no flags byte) */ {ACPI_RSC_LENGTH, 0, 0, sizeof(struct aml_resource_start_dependent_noprio)}, /* * All done if the output descriptor length is required to be 0. * * TBD: Perhaps we should check for error if input flags are not * compatible with a 0-byte descriptor. */ {ACPI_RSC_EXIT_EQ, ACPI_RSC_COMPARE_VALUE, ACPI_RS_OFFSET(data.start_dpf.descriptor_length), 0}, /* Reset length to 1 byte (descriptor with flags byte) */ {ACPI_RSC_LENGTH, 0, 0, sizeof(struct aml_resource_start_dependent)}, /* * All done if flags byte is necessary -- if either priority value * is not ACPI_ACCEPTABLE_CONFIGURATION */ {ACPI_RSC_EXIT_NE, ACPI_RSC_COMPARE_VALUE, ACPI_RS_OFFSET(data.start_dpf.compatibility_priority), ACPI_ACCEPTABLE_CONFIGURATION}, {ACPI_RSC_EXIT_NE, ACPI_RSC_COMPARE_VALUE, ACPI_RS_OFFSET(data.start_dpf.performance_robustness), ACPI_ACCEPTABLE_CONFIGURATION}, /* Flag byte is not necessary */ {ACPI_RSC_LENGTH, 0, 0, sizeof(struct aml_resource_start_dependent_noprio)} };
lgpl-2.1
rockhowse/jna
native/libffi/testsuite/libffi.call/cls_align_longdouble.c
366
2571
/* Area: ffi_call, closure_call Purpose: Check structure alignment of long double. Limitations: none. PR: none. Originator: <hos@tamanegi.org> 20031203 */ /* { dg-do run } */ #include "ffitest.h" typedef struct cls_struct_align { unsigned char a; long double b; unsigned char c; } cls_struct_align; cls_struct_align cls_struct_align_fn(struct cls_struct_align a1, struct cls_struct_align a2) { struct cls_struct_align result; result.a = a1.a + a2.a; result.b = a1.b + a2.b; result.c = a1.c + a2.c; printf("%d %g %d %d %g %d: %d %g %d\n", a1.a, (double)a1.b, a1.c, a2.a, (double)a2.b, a2.c, result.a, (double)result.b, result.c); return result; } static void cls_struct_align_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, void* userdata __UNUSED__) { struct cls_struct_align a1, a2; a1 = *(struct cls_struct_align*)(args[0]); a2 = *(struct cls_struct_align*)(args[1]); *(cls_struct_align*)resp = cls_struct_align_fn(a1, a2); } int main (void) { ffi_cif cif; void *code; ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); void* args_dbl[5]; ffi_type* cls_struct_fields[4]; ffi_type cls_struct_type; ffi_type* dbl_arg_types[5]; cls_struct_type.size = 0; cls_struct_type.alignment = 0; cls_struct_type.type = FFI_TYPE_STRUCT; cls_struct_type.elements = cls_struct_fields; struct cls_struct_align g_dbl = { 12, 4951, 127 }; struct cls_struct_align f_dbl = { 1, 9320, 13 }; struct cls_struct_align res_dbl; cls_struct_fields[0] = &ffi_type_uchar; cls_struct_fields[1] = &ffi_type_longdouble; cls_struct_fields[2] = &ffi_type_uchar; cls_struct_fields[3] = NULL; dbl_arg_types[0] = &cls_struct_type; dbl_arg_types[1] = &cls_struct_type; dbl_arg_types[2] = NULL; CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type, dbl_arg_types) == FFI_OK); args_dbl[0] = &g_dbl; args_dbl[1] = &f_dbl; args_dbl[2] = NULL; ffi_call(&cif, FFI_FN(cls_struct_align_fn), &res_dbl, args_dbl); /* { dg-output "12 4951 127 1 9320 13: 13 14271 140" } */ printf("res: %d %g %d\n", res_dbl.a, (double)res_dbl.b, res_dbl.c); /* { dg-output "\nres: 13 14271 140" } */ CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_align_gn, NULL, code) == FFI_OK); res_dbl = ((cls_struct_align(*)(cls_struct_align, cls_struct_align))(code))(g_dbl, f_dbl); /* { dg-output "\n12 4951 127 1 9320 13: 13 14271 140" } */ printf("res: %d %g %d\n", res_dbl.a, (double)res_dbl.b, res_dbl.c); /* { dg-output "\nres: 13 14271 140" } */ exit(0); }
lgpl-2.1
xyzz/vcmi-build
project/jni/application/lbreakout2-2.6.2/intl/relocatable.c
126
13040
/* Provide relocatable packages. Copyright (C) 2003 Free Software Foundation, Inc. Written by Bruno Haible <bruno@clisp.org>, 2003. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /* Tell glibc's <stdio.h> to provide a prototype for getline(). This must come before <config.h> because <config.h> may include <features.h>, and once <features.h> has been included, it's too late. */ #ifndef _GNU_SOURCE # define _GNU_SOURCE 1 #endif #ifdef HAVE_CONFIG_H # include "config.h" #endif /* Specification. */ #include "relocatable.h" #if ENABLE_RELOCATABLE #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef NO_XMALLOC # define xmalloc malloc #else # include "xalloc.h" #endif #if defined _WIN32 || defined __WIN32__ # define WIN32_LEAN_AND_MEAN # include <windows.h> #endif #if DEPENDS_ON_LIBCHARSET # include <libcharset.h> #endif #if DEPENDS_ON_LIBICONV && HAVE_ICONV # include <iconv.h> #endif #if DEPENDS_ON_LIBINTL && ENABLE_NLS # include <libintl.h> #endif /* Faked cheap 'bool'. */ #undef bool #undef false #undef true #define bool int #define false 0 #define true 1 /* Pathname support. ISSLASH(C) tests whether C is a directory separator character. IS_PATH_WITH_DIR(P) tests whether P contains a directory specification. */ #if defined _WIN32 || defined __WIN32__ || defined __EMX__ || defined __DJGPP__ /* Win32, OS/2, DOS */ # define ISSLASH(C) ((C) == '/' || (C) == '\\') # define HAS_DEVICE(P) \ ((((P)[0] >= 'A' && (P)[0] <= 'Z') || ((P)[0] >= 'a' && (P)[0] <= 'z')) \ && (P)[1] == ':') # define IS_PATH_WITH_DIR(P) \ (strchr (P, '/') != NULL || strchr (P, '\\') != NULL || HAS_DEVICE (P)) # define FILESYSTEM_PREFIX_LEN(P) (HAS_DEVICE (P) ? 2 : 0) #else /* Unix */ # define ISSLASH(C) ((C) == '/') # define IS_PATH_WITH_DIR(P) (strchr (P, '/') != NULL) # define FILESYSTEM_PREFIX_LEN(P) 0 #endif /* Original installation prefix. */ static char *orig_prefix; static size_t orig_prefix_len; /* Current installation prefix. */ static char *curr_prefix; static size_t curr_prefix_len; /* These prefixes do not end in a slash. Anything that will be concatenated to them must start with a slash. */ /* Sets the original and the current installation prefix of this module. Relocation simply replaces a pathname starting with the original prefix by the corresponding pathname with the current prefix instead. Both prefixes should be directory names without trailing slash (i.e. use "" instead of "/"). */ static void set_this_relocation_prefix (const char *orig_prefix_arg, const char *curr_prefix_arg) { if (orig_prefix_arg != NULL && curr_prefix_arg != NULL /* Optimization: if orig_prefix and curr_prefix are equal, the relocation is a nop. */ && strcmp (orig_prefix_arg, curr_prefix_arg) != 0) { /* Duplicate the argument strings. */ char *memory; orig_prefix_len = strlen (orig_prefix_arg); curr_prefix_len = strlen (curr_prefix_arg); memory = (char *) xmalloc (orig_prefix_len + 1 + curr_prefix_len + 1); #ifdef NO_XMALLOC if (memory != NULL) #endif { memcpy (memory, orig_prefix_arg, orig_prefix_len + 1); orig_prefix = memory; memory += orig_prefix_len + 1; memcpy (memory, curr_prefix_arg, curr_prefix_len + 1); curr_prefix = memory; return; } } orig_prefix = NULL; curr_prefix = NULL; /* Don't worry about wasted memory here - this function is usually only called once. */ } /* Sets the original and the current installation prefix of the package. Relocation simply replaces a pathname starting with the original prefix by the corresponding pathname with the current prefix instead. Both prefixes should be directory names without trailing slash (i.e. use "" instead of "/"). */ void set_relocation_prefix (const char *orig_prefix_arg, const char *curr_prefix_arg) { set_this_relocation_prefix (orig_prefix_arg, curr_prefix_arg); /* Now notify all dependent libraries. */ #if DEPENDS_ON_LIBCHARSET libcharset_set_relocation_prefix (orig_prefix_arg, curr_prefix_arg); #endif #if DEPENDS_ON_LIBICONV && HAVE_ICONV && _LIBICONV_VERSION >= 0x0109 libiconv_set_relocation_prefix (orig_prefix_arg, curr_prefix_arg); #endif #if DEPENDS_ON_LIBINTL && ENABLE_NLS && defined libintl_set_relocation_prefix libintl_set_relocation_prefix (orig_prefix_arg, curr_prefix_arg); #endif } #if !defined IN_LIBRARY || (defined PIC && defined INSTALLDIR) /* Convenience function: Computes the current installation prefix, based on the original installation prefix, the original installation directory of a particular file, and the current pathname of this file. Returns NULL upon failure. */ #ifdef IN_LIBRARY #define compute_curr_prefix local_compute_curr_prefix static #endif const char * compute_curr_prefix (const char *orig_installprefix, const char *orig_installdir, const char *curr_pathname) { const char *curr_installdir; const char *rel_installdir; if (curr_pathname == NULL) return NULL; /* Determine the relative installation directory, relative to the prefix. This is simply the difference between orig_installprefix and orig_installdir. */ if (strncmp (orig_installprefix, orig_installdir, strlen (orig_installprefix)) != 0) /* Shouldn't happen - nothing should be installed outside $(prefix). */ return NULL; rel_installdir = orig_installdir + strlen (orig_installprefix); /* Determine the current installation directory. */ { const char *p_base = curr_pathname + FILESYSTEM_PREFIX_LEN (curr_pathname); const char *p = curr_pathname + strlen (curr_pathname); char *q; while (p > p_base) { p--; if (ISSLASH (*p)) break; } q = (char *) xmalloc (p - curr_pathname + 1); #ifdef NO_XMALLOC if (q == NULL) return NULL; #endif memcpy (q, curr_pathname, p - curr_pathname); q[p - curr_pathname] = '\0'; curr_installdir = q; } /* Compute the current installation prefix by removing the trailing rel_installdir from it. */ { const char *rp = rel_installdir + strlen (rel_installdir); const char *cp = curr_installdir + strlen (curr_installdir); const char *cp_base = curr_installdir + FILESYSTEM_PREFIX_LEN (curr_installdir); while (rp > rel_installdir && cp > cp_base) { bool same = false; const char *rpi = rp; const char *cpi = cp; while (rpi > rel_installdir && cpi > cp_base) { rpi--; cpi--; if (ISSLASH (*rpi) || ISSLASH (*cpi)) { if (ISSLASH (*rpi) && ISSLASH (*cpi)) same = true; break; } #if defined _WIN32 || defined __WIN32__ || defined __EMX__ || defined __DJGPP__ /* Win32, OS/2, DOS - case insignificant filesystem */ if ((*rpi >= 'a' && *rpi <= 'z' ? *rpi - 'a' + 'A' : *rpi) != (*cpi >= 'a' && *cpi <= 'z' ? *cpi - 'a' + 'A' : *cpi)) break; #else if (*rpi != *cpi) break; #endif } if (!same) break; /* The last pathname component was the same. opi and cpi now point to the slash before it. */ rp = rpi; cp = cpi; } if (rp > rel_installdir) /* Unexpected: The curr_installdir does not end with rel_installdir. */ return NULL; { size_t curr_prefix_len = cp - curr_installdir; char *curr_prefix; curr_prefix = (char *) xmalloc (curr_prefix_len + 1); #ifdef NO_XMALLOC if (curr_prefix == NULL) return NULL; #endif memcpy (curr_prefix, curr_installdir, curr_prefix_len); curr_prefix[curr_prefix_len] = '\0'; return curr_prefix; } } } #endif /* !IN_LIBRARY || PIC */ #if defined PIC && defined INSTALLDIR /* Full pathname of shared library, or NULL. */ static char *shared_library_fullname; #if defined _WIN32 || defined __WIN32__ /* Determine the full pathname of the shared library when it is loaded. */ BOOL WINAPI DllMain (HINSTANCE module_handle, DWORD event, LPVOID reserved) { (void) reserved; if (event == DLL_PROCESS_ATTACH) { /* The DLL is being loaded into an application's address range. */ static char location[MAX_PATH]; if (!GetModuleFileName (module_handle, location, sizeof (location))) /* Shouldn't happen. */ return FALSE; if (!IS_PATH_WITH_DIR (location)) /* Shouldn't happen. */ return FALSE; shared_library_fullname = strdup (location); } return TRUE; } #else /* Unix */ static void find_shared_library_fullname () { #if defined __linux__ && __GLIBC__ >= 2 /* Linux has /proc/self/maps. glibc 2 has the getline() function. */ FILE *fp; /* Open the current process' maps file. It describes one VMA per line. */ fp = fopen ("/proc/self/maps", "r"); if (fp) { unsigned long address = (unsigned long) &find_shared_library_fullname; for (;;) { unsigned long start, end; int c; if (fscanf (fp, "%lx-%lx", &start, &end) != 2) break; if (address >= start && address <= end - 1) { /* Found it. Now see if this line contains a filename. */ while (c = getc (fp), c != EOF && c != '\n' && c != '/') continue; if (c == '/') { size_t size; int len; ungetc (c, fp); shared_library_fullname = NULL; size = 0; len = getline (&shared_library_fullname, &size, fp); if (len >= 0) { /* Success: filled shared_library_fullname. */ if (len > 0 && shared_library_fullname[len - 1] == '\n') shared_library_fullname[len - 1] = '\0'; } } break; } while (c = getc (fp), c != EOF && c != '\n') continue; } fclose (fp); } #endif } #endif /* WIN32 / Unix */ /* Return the full pathname of the current shared library. Return NULL if unknown. Guaranteed to work only on Linux and Woe32. */ static char * get_shared_library_fullname () { #if !(defined _WIN32 || defined __WIN32__) static bool tried_find_shared_library_fullname; if (!tried_find_shared_library_fullname) { find_shared_library_fullname (); tried_find_shared_library_fullname = true; } #endif return shared_library_fullname; } #endif /* PIC */ /* Returns the pathname, relocated according to the current installation directory. */ const char * relocate (const char *pathname) { #if defined PIC && defined INSTALLDIR static int initialized; /* Initialization code for a shared library. */ if (!initialized) { /* At this point, orig_prefix and curr_prefix likely have already been set through the main program's set_program_name_and_installdir function. This is sufficient in the case that the library has initially been installed in the same orig_prefix. But we can do better, to also cover the cases that 1. it has been installed in a different prefix before being moved to orig_prefix and (later) to curr_prefix, 2. unlike the program, it has not moved away from orig_prefix. */ const char *orig_installprefix = INSTALLPREFIX; const char *orig_installdir = INSTALLDIR; const char *curr_prefix_better; curr_prefix_better = compute_curr_prefix (orig_installprefix, orig_installdir, get_shared_library_fullname ()); if (curr_prefix_better == NULL) curr_prefix_better = curr_prefix; set_relocation_prefix (orig_installprefix, curr_prefix_better); initialized = 1; } #endif /* Note: It is not necessary to perform case insensitive comparison here, even for DOS-like filesystems, because the pathname argument was typically created from the same Makefile variable as orig_prefix came from. */ if (orig_prefix != NULL && curr_prefix != NULL && strncmp (pathname, orig_prefix, orig_prefix_len) == 0) { if (pathname[orig_prefix_len] == '\0') /* pathname equals orig_prefix. */ return curr_prefix; if (ISSLASH (pathname[orig_prefix_len])) { /* pathname starts with orig_prefix. */ const char *pathname_tail = &pathname[orig_prefix_len]; char *result = (char *) xmalloc (curr_prefix_len + strlen (pathname_tail) + 1); #ifdef NO_XMALLOC if (result != NULL) #endif { memcpy (result, curr_prefix, curr_prefix_len); strcpy (result + curr_prefix_len, pathname_tail); return result; } } } /* Nothing to relocate. */ return pathname; } #endif
lgpl-2.1
NumPDEClassTTU/femus
external/jsoncpp/jsoncpp-src-0.5.0/src/jsontestrunner/main.cpp
129
6135
#include <json/json.h> #include <algorithm> // sort #include <stdio.h> #if defined(_MSC_VER) && _MSC_VER >= 1310 # pragma warning( disable: 4996 ) // disable fopen deprecation warning #endif static std::string readInputTestFile( const char *path ) { FILE *file = fopen( path, "rb" ); if ( !file ) return std::string(""); fseek( file, 0, SEEK_END ); long size = ftell( file ); fseek( file, 0, SEEK_SET ); std::string text; char *buffer = new char[size+1]; buffer[size] = 0; if ( fread( buffer, 1, size, file ) == (unsigned long)size ) text = buffer; fclose( file ); delete[] buffer; return text; } static void printValueTree( FILE *fout, Json::Value &value, const std::string &path = "." ) { switch ( value.type() ) { case Json::nullValue: fprintf( fout, "%s=null\n", path.c_str() ); break; case Json::intValue: fprintf( fout, "%s=%d\n", path.c_str(), value.asInt() ); break; case Json::uintValue: fprintf( fout, "%s=%u\n", path.c_str(), value.asUInt() ); break; case Json::realValue: fprintf( fout, "%s=%.16g\n", path.c_str(), value.asDouble() ); break; case Json::stringValue: fprintf( fout, "%s=\"%s\"\n", path.c_str(), value.asString().c_str() ); break; case Json::booleanValue: fprintf( fout, "%s=%s\n", path.c_str(), value.asBool() ? "true" : "false" ); break; case Json::arrayValue: { fprintf( fout, "%s=[]\n", path.c_str() ); int size = value.size(); for ( int index =0; index < size; ++index ) { static char buffer[16]; sprintf( buffer, "[%d]", index ); printValueTree( fout, value[index], path + buffer ); } } break; case Json::objectValue: { fprintf( fout, "%s={}\n", path.c_str() ); Json::Value::Members members( value.getMemberNames() ); std::sort( members.begin(), members.end() ); std::string suffix = *(path.end()-1) == '.' ? "" : "."; for ( Json::Value::Members::iterator it = members.begin(); it != members.end(); ++it ) { const std::string &name = *it; printValueTree( fout, value[name], path + suffix + name ); } } break; default: break; } } static int parseAndSaveValueTree( const std::string &input, const std::string &actual, const std::string &kind, Json::Value &root, const Json::Features &features, bool parseOnly ) { Json::Reader reader( features ); bool parsingSuccessful = reader.parse( input, root ); if ( !parsingSuccessful ) { printf( "Failed to parse %s file: \n%s\n", kind.c_str(), reader.getFormatedErrorMessages().c_str() ); return 1; } if ( !parseOnly ) { FILE *factual = fopen( actual.c_str(), "wt" ); if ( !factual ) { printf( "Failed to create %s actual file.\n", kind.c_str() ); return 2; } printValueTree( factual, root ); fclose( factual ); } return 0; } static int rewriteValueTree( const std::string &rewritePath, const Json::Value &root, std::string &rewrite ) { //Json::FastWriter writer; //writer.enableYAMLCompatibility(); Json::StyledWriter writer; rewrite = writer.write( root ); FILE *fout = fopen( rewritePath.c_str(), "wt" ); if ( !fout ) { printf( "Failed to create rewrite file: %s\n", rewritePath.c_str() ); return 2; } fprintf( fout, "%s\n", rewrite.c_str() ); fclose( fout ); return 0; } static std::string removeSuffix( const std::string &path, const std::string &extension ) { if ( extension.length() >= path.length() ) return std::string(""); std::string suffix = path.substr( path.length() - extension.length() ); if ( suffix != extension ) return std::string(""); return path.substr( 0, path.length() - extension.length() ); } static int printUsage( const char *argv[] ) { printf( "Usage: %s [--strict] input-json-file", argv[0] ); return 3; } int parseCommandLine( int argc, const char *argv[], Json::Features &features, std::string &path, bool &parseOnly ) { parseOnly = false; if ( argc < 2 ) { return printUsage( argv ); } int index = 1; if ( std::string(argv[1]) == "--json-checker" ) { features = Json::Features::strictMode(); parseOnly = true; ++index; } if ( index == argc || index + 1 < argc ) { return printUsage( argv ); } path = argv[index]; return 0; } int main( int argc, const char *argv[] ) { std::string path; Json::Features features; bool parseOnly; int exitCode = parseCommandLine( argc, argv, features, path, parseOnly ); if ( exitCode != 0 ) { return exitCode; } std::string input = readInputTestFile( path.c_str() ); if ( input.empty() ) { printf( "Failed to read input or empty input: %s\n", path.c_str() ); return 3; } std::string basePath = removeSuffix( argv[1], ".json" ); if ( !parseOnly && basePath.empty() ) { printf( "Bad input path. Path does not end with '.expected':\n%s\n", path.c_str() ); return 3; } std::string actualPath = basePath + ".actual"; std::string rewritePath = basePath + ".rewrite"; std::string rewriteActualPath = basePath + ".actual-rewrite"; Json::Value root; exitCode = parseAndSaveValueTree( input, actualPath, "input", root, features, parseOnly ); if ( exitCode == 0 && !parseOnly ) { std::string rewrite; exitCode = rewriteValueTree( rewritePath, root, rewrite ); if ( exitCode == 0 ) { Json::Value rewriteRoot; exitCode = parseAndSaveValueTree( rewrite, rewriteActualPath, "rewrite", rewriteRoot, features, parseOnly ); } } return exitCode; }
lgpl-2.1
PaulStoffregen/Arduino-1.6.2-Teensyduino
libraries/Robot_Control/src/utility/Adafruit_GFX.cpp
167
17465
/* This is the core graphics library for all our displays, providing a common set of graphics primitives (points, lines, circles, etc.). It needs to be paired with a hardware-specific library for each display device we carry (to handle the lower-level functions). Adafruit invests time and resources providing this open source code, please support Adafruit & open-source hardware by purchasing products from Adafruit! Copyright (c) 2013 Adafruit Industries. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Adafruit_GFX.h" #include "glcdfont.c" #ifdef __AVR__ #include <avr/pgmspace.h> #else #define pgm_read_byte(addr) (*(const unsigned char *)(addr)) #endif Adafruit_GFX::Adafruit_GFX(int16_t w, int16_t h): WIDTH(w), HEIGHT(h) { _width = WIDTH; _height = HEIGHT; rotation = 0; cursor_y = cursor_x = 0; textsize = 1; textcolor = textbgcolor = 0xFFFF; wrap = true; } // Draw a circle outline void Adafruit_GFX::drawCircle(int16_t x0, int16_t y0, int16_t r, uint16_t color) { int16_t f = 1 - r; int16_t ddF_x = 1; int16_t ddF_y = -2 * r; int16_t x = 0; int16_t y = r; drawPixel(x0 , y0+r, color); drawPixel(x0 , y0-r, color); drawPixel(x0+r, y0 , color); drawPixel(x0-r, y0 , color); while (x<y) { if (f >= 0) { y--; ddF_y += 2; f += ddF_y; } x++; ddF_x += 2; f += ddF_x; drawPixel(x0 + x, y0 + y, color); drawPixel(x0 - x, y0 + y, color); drawPixel(x0 + x, y0 - y, color); drawPixel(x0 - x, y0 - y, color); drawPixel(x0 + y, y0 + x, color); drawPixel(x0 - y, y0 + x, color); drawPixel(x0 + y, y0 - x, color); drawPixel(x0 - y, y0 - x, color); } } void Adafruit_GFX::drawCircleHelper( int16_t x0, int16_t y0, int16_t r, uint8_t cornername, uint16_t color) { int16_t f = 1 - r; int16_t ddF_x = 1; int16_t ddF_y = -2 * r; int16_t x = 0; int16_t y = r; while (x<y) { if (f >= 0) { y--; ddF_y += 2; f += ddF_y; } x++; ddF_x += 2; f += ddF_x; if (cornername & 0x4) { drawPixel(x0 + x, y0 + y, color); drawPixel(x0 + y, y0 + x, color); } if (cornername & 0x2) { drawPixel(x0 + x, y0 - y, color); drawPixel(x0 + y, y0 - x, color); } if (cornername & 0x8) { drawPixel(x0 - y, y0 + x, color); drawPixel(x0 - x, y0 + y, color); } if (cornername & 0x1) { drawPixel(x0 - y, y0 - x, color); drawPixel(x0 - x, y0 - y, color); } } } void Adafruit_GFX::fillCircle(int16_t x0, int16_t y0, int16_t r, uint16_t color) { drawFastVLine(x0, y0-r, 2*r+1, color); fillCircleHelper(x0, y0, r, 3, 0, color); } // Used to do circles and roundrects void Adafruit_GFX::fillCircleHelper(int16_t x0, int16_t y0, int16_t r, uint8_t cornername, int16_t delta, uint16_t color) { int16_t f = 1 - r; int16_t ddF_x = 1; int16_t ddF_y = -2 * r; int16_t x = 0; int16_t y = r; while (x<y) { if (f >= 0) { y--; ddF_y += 2; f += ddF_y; } x++; ddF_x += 2; f += ddF_x; if (cornername & 0x1) { drawFastVLine(x0+x, y0-y, 2*y+1+delta, color); drawFastVLine(x0+y, y0-x, 2*x+1+delta, color); } if (cornername & 0x2) { drawFastVLine(x0-x, y0-y, 2*y+1+delta, color); drawFastVLine(x0-y, y0-x, 2*x+1+delta, color); } } } // Bresenham's algorithm - thx wikpedia void Adafruit_GFX::drawLine(int16_t x0, int16_t y0, int16_t x1, int16_t y1, uint16_t color) { int16_t steep = abs(y1 - y0) > abs(x1 - x0); if (steep) { swap(x0, y0); swap(x1, y1); } if (x0 > x1) { swap(x0, x1); swap(y0, y1); } int16_t dx, dy; dx = x1 - x0; dy = abs(y1 - y0); int16_t err = dx / 2; int16_t ystep; if (y0 < y1) { ystep = 1; } else { ystep = -1; } for (; x0<=x1; x0++) { if (steep) { drawPixel(y0, x0, color); } else { drawPixel(x0, y0, color); } err -= dy; if (err < 0) { y0 += ystep; err += dx; } } } // Draw a rectangle void Adafruit_GFX::drawRect(int16_t x, int16_t y, int16_t w, int16_t h, uint16_t color) { drawFastHLine(x, y, w, color); drawFastHLine(x, y+h-1, w, color); drawFastVLine(x, y, h, color); drawFastVLine(x+w-1, y, h, color); } void Adafruit_GFX::drawFastVLine(int16_t x, int16_t y, int16_t h, uint16_t color) { // Update in subclasses if desired! drawLine(x, y, x, y+h-1, color); } void Adafruit_GFX::drawFastHLine(int16_t x, int16_t y, int16_t w, uint16_t color) { // Update in subclasses if desired! drawLine(x, y, x+w-1, y, color); } void Adafruit_GFX::fillRect(int16_t x, int16_t y, int16_t w, int16_t h, uint16_t color) { // Update in subclasses if desired! for (int16_t i=x; i<x+w; i++) { drawFastVLine(i, y, h, color); } } void Adafruit_GFX::fillScreen(uint16_t color) { fillRect(0, 0, _width, _height, color); } // Draw a rounded rectangle void Adafruit_GFX::drawRoundRect(int16_t x, int16_t y, int16_t w, int16_t h, int16_t r, uint16_t color) { // smarter version drawFastHLine(x+r , y , w-2*r, color); // Top drawFastHLine(x+r , y+h-1, w-2*r, color); // Bottom drawFastVLine(x , y+r , h-2*r, color); // Left drawFastVLine(x+w-1, y+r , h-2*r, color); // Right // draw four corners drawCircleHelper(x+r , y+r , r, 1, color); drawCircleHelper(x+w-r-1, y+r , r, 2, color); drawCircleHelper(x+w-r-1, y+h-r-1, r, 4, color); drawCircleHelper(x+r , y+h-r-1, r, 8, color); } // Fill a rounded rectangle void Adafruit_GFX::fillRoundRect(int16_t x, int16_t y, int16_t w, int16_t h, int16_t r, uint16_t color) { // smarter version fillRect(x+r, y, w-2*r, h, color); // draw four corners fillCircleHelper(x+w-r-1, y+r, r, 1, h-2*r-1, color); fillCircleHelper(x+r , y+r, r, 2, h-2*r-1, color); } // Draw a triangle void Adafruit_GFX::drawTriangle(int16_t x0, int16_t y0, int16_t x1, int16_t y1, int16_t x2, int16_t y2, uint16_t color) { drawLine(x0, y0, x1, y1, color); drawLine(x1, y1, x2, y2, color); drawLine(x2, y2, x0, y0, color); } // Fill a triangle void Adafruit_GFX::fillTriangle ( int16_t x0, int16_t y0, int16_t x1, int16_t y1, int16_t x2, int16_t y2, uint16_t color) { int16_t a, b, y, last; // Sort coordinates by Y order (y2 >= y1 >= y0) if (y0 > y1) { swap(y0, y1); swap(x0, x1); } if (y1 > y2) { swap(y2, y1); swap(x2, x1); } if (y0 > y1) { swap(y0, y1); swap(x0, x1); } if(y0 == y2) { // Handle awkward all-on-same-line case as its own thing a = b = x0; if(x1 < a) a = x1; else if(x1 > b) b = x1; if(x2 < a) a = x2; else if(x2 > b) b = x2; drawFastHLine(a, y0, b-a+1, color); return; } int16_t dx01 = x1 - x0, dy01 = y1 - y0, dx02 = x2 - x0, dy02 = y2 - y0, dx12 = x2 - x1, dy12 = y2 - y1, sa = 0, sb = 0; // For upper part of triangle, find scanline crossings for segments // 0-1 and 0-2. If y1=y2 (flat-bottomed triangle), the scanline y1 // is included here (and second loop will be skipped, avoiding a /0 // error there), otherwise scanline y1 is skipped here and handled // in the second loop...which also avoids a /0 error here if y0=y1 // (flat-topped triangle). if(y1 == y2) last = y1; // Include y1 scanline else last = y1-1; // Skip it for(y=y0; y<=last; y++) { a = x0 + sa / dy01; b = x0 + sb / dy02; sa += dx01; sb += dx02; /* longhand: a = x0 + (x1 - x0) * (y - y0) / (y1 - y0); b = x0 + (x2 - x0) * (y - y0) / (y2 - y0); */ if(a > b) swap(a,b); drawFastHLine(a, y, b-a+1, color); } // For lower part of triangle, find scanline crossings for segments // 0-2 and 1-2. This loop is skipped if y1=y2. sa = dx12 * (y - y1); sb = dx02 * (y - y0); for(; y<=y2; y++) { a = x1 + sa / dy12; b = x0 + sb / dy02; sa += dx12; sb += dx02; /* longhand: a = x1 + (x2 - x1) * (y - y1) / (y2 - y1); b = x0 + (x2 - x0) * (y - y0) / (y2 - y0); */ if(a > b) swap(a,b); drawFastHLine(a, y, b-a+1, color); } } void Adafruit_GFX::drawBitmap(int16_t x, int16_t y, const uint8_t *bitmap, int16_t w, int16_t h, uint16_t color) { int16_t i, j, byteWidth = (w + 7) / 8; for(j=0; j<h; j++) { for(i=0; i<w; i++ ) { if(pgm_read_byte(bitmap + j * byteWidth + i / 8) & (128 >> (i & 7))) { drawPixel(x+i, y+j, color); } } } } #if ARDUINO >= 100 size_t Adafruit_GFX::write(uint8_t c) { #else void Adafruit_GFX::write(uint8_t c) { #endif if (c == '\n') { cursor_y += textsize*8; cursor_x = 0; } else if (c == '\r') { // skip em } else { drawChar(cursor_x, cursor_y, c, textcolor, textbgcolor, textsize); cursor_x += textsize*6; if (wrap && (cursor_x > (_width - textsize*6))) { cursor_y += textsize*8; cursor_x = 0; } } #if ARDUINO >= 100 return 1; #endif } // Draw a character void Adafruit_GFX::drawChar(int16_t x, int16_t y, unsigned char c, uint16_t color, uint16_t bg, uint8_t size) { if((x >= _width) || // Clip right (y >= _height) || // Clip bottom ((x + 6 * size - 1) < 0) || // Clip left ((y + 8 * size - 1) < 0)) // Clip top return; for (int8_t i=0; i<6; i++ ) { uint8_t line; if (i == 5) line = 0x0; else line = pgm_read_byte(font+(c*5)+i); for (int8_t j = 0; j<8; j++) { if (line & 0x1) { if (size == 1) // default size drawPixel(x+i, y+j, color); else { // big size fillRect(x+(i*size), y+(j*size), size, size, color); } } else if (bg != color) { if (size == 1) // default size drawPixel(x+i, y+j, bg); else { // big size fillRect(x+i*size, y+j*size, size, size, bg); } } line >>= 1; } } } void Adafruit_GFX::setCursor(int16_t x, int16_t y) { cursor_x = x; cursor_y = y; } void Adafruit_GFX::setTextSize(uint8_t s) { textsize = (s > 0) ? s : 1; } void Adafruit_GFX::setTextColor(uint16_t c) { // For 'transparent' background, we'll set the bg // to the same as fg instead of using a flag textcolor = textbgcolor = c; } void Adafruit_GFX::setTextColor(uint16_t c, uint16_t b) { textcolor = c; textbgcolor = b; } void Adafruit_GFX::setTextWrap(boolean w) { wrap = w; } uint8_t Adafruit_GFX::getRotation(void) { return rotation; } void Adafruit_GFX::setRotation(uint8_t x) { rotation = (x & 3); switch(rotation) { case 0: case 2: _width = WIDTH; _height = HEIGHT; break; case 1: case 3: _width = HEIGHT; _height = WIDTH; break; } } // Return the size of the display (per current rotation) int16_t Adafruit_GFX::width(void) { return _width; } int16_t Adafruit_GFX::height(void) { return _height; } void Adafruit_GFX::invertDisplay(boolean i) { // Do nothing, must be subclassed if supported } uint16_t Adafruit_GFX::newColor(uint8_t r, uint8_t g, uint8_t b) { return ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3); } void Adafruit_GFX::background(uint8_t red, uint8_t green, uint8_t blue) { background(newColor(red, green, blue)); } void Adafruit_GFX::background(color c) { fillScreen(c); } void Adafruit_GFX::stroke(uint8_t red, uint8_t green, uint8_t blue) { stroke(newColor(red, green, blue)); } void Adafruit_GFX::stroke(color c) { useStroke = true; strokeColor = c; setTextColor(c); } void Adafruit_GFX::noStroke() { useStroke = false; } void Adafruit_GFX::noFill() { useFill = false; } void Adafruit_GFX::fill(uint8_t red, uint8_t green, uint8_t blue) { fill(newColor(red, green, blue)); } void Adafruit_GFX::fill(color c) { useFill = true; fillColor = c; } void Adafruit_GFX::text(int value, uint8_t x, uint8_t y){ if (!useStroke) return; setTextWrap(false); setTextColor(strokeColor); setCursor(x, y); print(value); } void Adafruit_GFX::text(long value, uint8_t x, uint8_t y){ if (!useStroke) return; setTextWrap(false); setTextColor(strokeColor); setCursor(x, y); print(value); } void Adafruit_GFX::text(char value, uint8_t x, uint8_t y){ if (!useStroke) return; setTextWrap(false); setTextColor(strokeColor); setCursor(x, y); print(value); } void Adafruit_GFX::text(const char * text, int16_t x, int16_t y) { if (!useStroke) return; setTextWrap(false); setTextColor(strokeColor); setCursor(x, y); print(text); } void Adafruit_GFX::textWrap(const char * text, int16_t x, int16_t y) { if (!useStroke) return; setTextWrap(true); setTextColor(strokeColor); setCursor(x, y); print(text); } void Adafruit_GFX::textSize(uint8_t size) { setTextSize(size); } void Adafruit_GFX::point(int16_t x, int16_t y) { if (!useStroke) return; drawPixel(x, y, strokeColor); } void Adafruit_GFX::line(int16_t x1, int16_t y1, int16_t x2, int16_t y2) { if (!useStroke) return; if (x1 == x2) { drawFastVLine(x1, y1, y2 - y1, strokeColor); } else if (y1 == y2) { drawFastHLine(x1, y1, x2 - x1, strokeColor); } else { drawLine(x1, y1, x2, y2, strokeColor); } } void Adafruit_GFX::rect(int16_t x, int16_t y, int16_t width, int16_t height) { if (useFill) { fillRect(x, y, width, height, fillColor); } if (useStroke) { drawRect(x, y, width, height, strokeColor); } } void Adafruit_GFX::rect(int16_t x, int16_t y, int16_t width, int16_t height, int16_t radius) { if (radius == 0) { rect(x, y, width, height); } if (useFill) { fillRoundRect(x, y, width, height, radius, fillColor); } if (useStroke) { drawRoundRect(x, y, width, height, radius, strokeColor); } } void Adafruit_GFX::circle(int16_t x, int16_t y, int16_t r) { if (r == 0) return; if (useFill) { fillCircle(x, y, r, fillColor); } if (useStroke) { drawCircle(x, y, r, strokeColor); } } void Adafruit_GFX::triangle(int16_t x1, int16_t y1, int16_t x2, int16_t y2, int16_t x3, int16_t y3) { if (useFill) { fillTriangle(x1, y1, x2, y2, x3, y3, fillColor); } if (useStroke) { drawTriangle(x1, y1, x2, y2, x3, y3, strokeColor); } } #define BUFFPIXEL 20 /* void Adafruit_GFX::image(PImage & img, uint16_t x, uint16_t y) { int w, h, row, col; uint8_t r, g, b; uint32_t pos = 0; uint8_t sdbuffer[3*BUFFPIXEL]; // pixel buffer (R+G+B per pixel) uint8_t buffidx = sizeof(sdbuffer); // Current position in sdbuffer // Crop area to be loaded w = img._bmpWidth; h = img._bmpHeight; if((x+w-1) >= width()) w = width() - x; if((y+h-1) >= height()) h = height() - y; // Set TFT address window to clipped image bounds //setAddrWindow(x, y, x+w-1, y+h-1); for (row=0; row<h; row++) { // For each scanline... // Seek to start of scan line. It might seem labor- // intensive to be doing this on every line, but this // method covers a lot of gritty details like cropping // and scanline padding. Also, the seek only takes // place if the file position actually needs to change // (avoids a lot of cluster math in SD library). if(img._flip) // Bitmap is stored bottom-to-top order (normal BMP) pos = img._bmpImageoffset + (img._bmpHeight - 1 - row) * img._rowSize; else // Bitmap is stored top-to-bottom pos = img._bmpImageoffset + row * img._rowSize; if(img._bmpFile.position() != pos) { // Need seek? img._bmpFile.seek(pos); buffidx = sizeof(sdbuffer); // Force buffer reload } for (col=0; col<w; col++) { // For each pixel... // Time to read more pixel data? if (buffidx >= sizeof(sdbuffer)) { // Indeed img._bmpFile.read(sdbuffer, sizeof(sdbuffer)); buffidx = 0; // Set index to beginning } // Convert pixel from BMP to TFT format, push to display b = sdbuffer[buffidx++]; g = sdbuffer[buffidx++]; r = sdbuffer[buffidx++]; //pushColor(tft.Color565(r,g,b)); drawPixel(x + col, y + row, newColor(r, g, b)); } // end pixel } // end scanline }*/
lgpl-2.1
stanxii/wr1004sjl
linux-3.4.6/security/tomoyo/securityfs_if.c
5070
7630
/* * security/tomoyo/securityfs_if.c * * Copyright (C) 2005-2011 NTT DATA CORPORATION */ #include <linux/security.h> #include "common.h" /** * tomoyo_check_task_acl - Check permission for task operation. * * @r: Pointer to "struct tomoyo_request_info". * @ptr: Pointer to "struct tomoyo_acl_info". * * Returns true if granted, false otherwise. */ static bool tomoyo_check_task_acl(struct tomoyo_request_info *r, const struct tomoyo_acl_info *ptr) { const struct tomoyo_task_acl *acl = container_of(ptr, typeof(*acl), head); return !tomoyo_pathcmp(r->param.task.domainname, acl->domainname); } /** * tomoyo_write_self - write() for /sys/kernel/security/tomoyo/self_domain interface. * * @file: Pointer to "struct file". * @buf: Domainname to transit to. * @count: Size of @buf. * @ppos: Unused. * * Returns @count on success, negative value otherwise. * * If domain transition was permitted but the domain transition failed, this * function returns error rather than terminating current thread with SIGKILL. */ static ssize_t tomoyo_write_self(struct file *file, const char __user *buf, size_t count, loff_t *ppos) { char *data; int error; if (!count || count >= TOMOYO_EXEC_TMPSIZE - 10) return -ENOMEM; data = kzalloc(count + 1, GFP_NOFS); if (!data) return -ENOMEM; if (copy_from_user(data, buf, count)) { error = -EFAULT; goto out; } tomoyo_normalize_line(data); if (tomoyo_correct_domain(data)) { const int idx = tomoyo_read_lock(); struct tomoyo_path_info name; struct tomoyo_request_info r; name.name = data; tomoyo_fill_path_info(&name); /* Check "task manual_domain_transition" permission. */ tomoyo_init_request_info(&r, NULL, TOMOYO_MAC_FILE_EXECUTE); r.param_type = TOMOYO_TYPE_MANUAL_TASK_ACL; r.param.task.domainname = &name; tomoyo_check_acl(&r, tomoyo_check_task_acl); if (!r.granted) error = -EPERM; else { struct tomoyo_domain_info *new_domain = tomoyo_assign_domain(data, true); if (!new_domain) { error = -ENOENT; } else { struct cred *cred = prepare_creds(); if (!cred) { error = -ENOMEM; } else { struct tomoyo_domain_info *old_domain = cred->security; cred->security = new_domain; atomic_inc(&new_domain->users); atomic_dec(&old_domain->users); commit_creds(cred); error = 0; } } } tomoyo_read_unlock(idx); } else error = -EINVAL; out: kfree(data); return error ? error : count; } /** * tomoyo_read_self - read() for /sys/kernel/security/tomoyo/self_domain interface. * * @file: Pointer to "struct file". * @buf: Domainname which current thread belongs to. * @count: Size of @buf. * @ppos: Bytes read by now. * * Returns read size on success, negative value otherwise. */ static ssize_t tomoyo_read_self(struct file *file, char __user *buf, size_t count, loff_t *ppos) { const char *domain = tomoyo_domain()->domainname->name; loff_t len = strlen(domain); loff_t pos = *ppos; if (pos >= len || !count) return 0; len -= pos; if (count < len) len = count; if (copy_to_user(buf, domain + pos, len)) return -EFAULT; *ppos += len; return len; } /* Operations for /sys/kernel/security/tomoyo/self_domain interface. */ static const struct file_operations tomoyo_self_operations = { .write = tomoyo_write_self, .read = tomoyo_read_self, }; /** * tomoyo_open - open() for /sys/kernel/security/tomoyo/ interface. * * @inode: Pointer to "struct inode". * @file: Pointer to "struct file". * * Returns 0 on success, negative value otherwise. */ static int tomoyo_open(struct inode *inode, struct file *file) { const int key = ((u8 *) file->f_path.dentry->d_inode->i_private) - ((u8 *) NULL); return tomoyo_open_control(key, file); } /** * tomoyo_release - close() for /sys/kernel/security/tomoyo/ interface. * * @inode: Pointer to "struct inode". * @file: Pointer to "struct file". * * Returns 0 on success, negative value otherwise. */ static int tomoyo_release(struct inode *inode, struct file *file) { return tomoyo_close_control(file->private_data); } /** * tomoyo_poll - poll() for /sys/kernel/security/tomoyo/ interface. * * @file: Pointer to "struct file". * @wait: Pointer to "poll_table". Maybe NULL. * * Returns POLLIN | POLLRDNORM | POLLOUT | POLLWRNORM if ready to read/write, * POLLOUT | POLLWRNORM otherwise. */ static unsigned int tomoyo_poll(struct file *file, poll_table *wait) { return tomoyo_poll_control(file, wait); } /** * tomoyo_read - read() for /sys/kernel/security/tomoyo/ interface. * * @file: Pointer to "struct file". * @buf: Pointer to buffer. * @count: Size of @buf. * @ppos: Unused. * * Returns bytes read on success, negative value otherwise. */ static ssize_t tomoyo_read(struct file *file, char __user *buf, size_t count, loff_t *ppos) { return tomoyo_read_control(file->private_data, buf, count); } /** * tomoyo_write - write() for /sys/kernel/security/tomoyo/ interface. * * @file: Pointer to "struct file". * @buf: Pointer to buffer. * @count: Size of @buf. * @ppos: Unused. * * Returns @count on success, negative value otherwise. */ static ssize_t tomoyo_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos) { return tomoyo_write_control(file->private_data, buf, count); } /* * tomoyo_operations is a "struct file_operations" which is used for handling * /sys/kernel/security/tomoyo/ interface. * * Some files under /sys/kernel/security/tomoyo/ directory accept open(O_RDWR). * See tomoyo_io_buffer for internals. */ static const struct file_operations tomoyo_operations = { .open = tomoyo_open, .release = tomoyo_release, .poll = tomoyo_poll, .read = tomoyo_read, .write = tomoyo_write, .llseek = noop_llseek, }; /** * tomoyo_create_entry - Create interface files under /sys/kernel/security/tomoyo/ directory. * * @name: The name of the interface file. * @mode: The permission of the interface file. * @parent: The parent directory. * @key: Type of interface. * * Returns nothing. */ static void __init tomoyo_create_entry(const char *name, const umode_t mode, struct dentry *parent, const u8 key) { securityfs_create_file(name, mode, parent, ((u8 *) NULL) + key, &tomoyo_operations); } /** * tomoyo_initerface_init - Initialize /sys/kernel/security/tomoyo/ interface. * * Returns 0. */ static int __init tomoyo_initerface_init(void) { struct dentry *tomoyo_dir; /* Don't create securityfs entries unless registered. */ if (current_cred()->security != &tomoyo_kernel_domain) return 0; tomoyo_dir = securityfs_create_dir("tomoyo", NULL); tomoyo_create_entry("query", 0600, tomoyo_dir, TOMOYO_QUERY); tomoyo_create_entry("domain_policy", 0600, tomoyo_dir, TOMOYO_DOMAINPOLICY); tomoyo_create_entry("exception_policy", 0600, tomoyo_dir, TOMOYO_EXCEPTIONPOLICY); tomoyo_create_entry("audit", 0400, tomoyo_dir, TOMOYO_AUDIT); tomoyo_create_entry(".process_status", 0600, tomoyo_dir, TOMOYO_PROCESS_STATUS); tomoyo_create_entry("stat", 0644, tomoyo_dir, TOMOYO_STAT); tomoyo_create_entry("profile", 0600, tomoyo_dir, TOMOYO_PROFILE); tomoyo_create_entry("manager", 0600, tomoyo_dir, TOMOYO_MANAGER); tomoyo_create_entry("version", 0400, tomoyo_dir, TOMOYO_VERSION); securityfs_create_file("self_domain", 0666, tomoyo_dir, NULL, &tomoyo_self_operations); tomoyo_load_builtin_policy(); return 0; } fs_initcall(tomoyo_initerface_init);
lgpl-2.1
kindahl/descripten
runtime/value_data.c
1
2512
/* * descripten - ECMAScript to native compiler * Copyright (C) 2011-2014 Christian Kindahl * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser Public License for more details. * * You should have received a copy of the GNU Lesser Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "value_data.h" // Make sure that we link one implementation of the inline functions. This is // necessary if a program that uses this library decides that it cannot inline // for some reason. In that case we must provide an implementation or the // program will not link. // // See: // http://gustedt.wordpress.com/2010/11/29/myth-and-reality-about-inline-in-c99/ extern inline EsValueData es_value_create(uint32_t type); extern inline EsValueData es_value_nothing(); extern inline EsValueData es_value_null(); extern inline EsValueData es_value_undefined(); extern inline EsValueData es_value_true(); extern inline EsValueData es_value_false(); extern inline EsValueData es_value_from_boolean(int val); extern inline EsValueData es_value_from_number(double val); extern inline EsValueData es_value_from_i64(int64_t val); extern inline EsValueData es_value_from_string(const struct EsString *str); extern inline EsValueData es_value_from_object(struct EsObject *obj); extern inline int es_value_is_nothing(const EsValueData value); extern inline int es_value_is_undefined(const EsValueData value); extern inline int es_value_is_null(const EsValueData value); extern inline int es_value_is_boolean(const EsValueData value); extern inline int es_value_is_number(const EsValueData value); extern inline int es_value_is_string(const EsValueData value); extern inline int es_value_is_object(const EsValueData value); extern inline int es_value_as_boolean(const EsValueData value); extern inline double es_value_as_number(const EsValueData value); extern inline struct EsString *es_value_as_string(const EsValueData value); extern inline struct EsObject *es_value_as_object(const EsValueData value); extern inline uint32_t es_value_type(const EsValueData value);
lgpl-3.0
openlecturnity/os45
lecturnity/editor/MouseAction.cpp
1
28968
#include "stdafx.h" #include "MouseAction.h" #include "MarkReaderWriter.h" #include "editorDoc.h" #include "InteractionStream.h" // E_IAX_INVALID_DATA #include "QuestionnaireEx.h" #include "QuestionEx.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif IMPLEMENT_DYNCREATE(CMouseAction, CObject) CMouseAction::CMouseAction() { m_pEditorProject = NULL; m_idAction = INTERACTION_NO_ACTION; m_nPageMarkId = 0; m_tszPath = NULL; m_nNameUsageCount = 0; m_pNextAction = NULL; } CMouseAction::~CMouseAction() { if (m_idAction == INTERACTION_JUMP_TARGET_MARK && m_pEditorProject != NULL) { CStopJumpMark *pMark = m_pEditorProject->GetMarkWithId(m_nPageMarkId); if (pMark != NULL) pMark->UnregisterUser(); } if (m_tszPath != NULL) delete[] m_tszPath; if (m_pNextAction != NULL) delete m_pNextAction; } HRESULT CMouseAction::Init(CEditorProject *pProject, AreaActionTypeId idAction, UINT nPageMarkId, LPCTSTR tszPath, AreaActionTypeId idActionFollowup) { if (pProject == NULL) return E_POINTER; int iPathLength = 0; if (tszPath != NULL) iPathLength = _tcslen(tszPath); if (idAction == INTERACTION_OPEN_URL || idAction == INTERACTION_OPEN_FILE) { if (tszPath == NULL) return E_POINTER; else if (iPathLength < 1) return E_INVALIDARG; } if (idAction == INTERACTION_JUMP_TARGET_MARK) { if (nPageMarkId == 0) return E_INVALIDARG; } if (idActionFollowup != INTERACTION_NO_ACTION) { if (idActionFollowup != INTERACTION_START_REPLAY && idActionFollowup != INTERACTION_STOP_REPLAY) return E_INVALIDARG; // others not implemented/specified yet } m_pEditorProject = pProject; m_idAction = idAction; m_nPageMarkId = nPageMarkId; if (m_idAction == INTERACTION_JUMP_TARGET_MARK) { CStopJumpMark *pMark = pProject->GetMarkWithId(m_nPageMarkId); if (pMark != NULL) pMark->RegisterUser(); } if (m_tszPath != NULL) delete[] m_tszPath; m_tszPath = new _TCHAR[iPathLength + 1]; ZeroMemory(m_tszPath, iPathLength + 1); _tcsncpy(m_tszPath, tszPath, iPathLength); m_tszPath[iPathLength] = 0; //destroyed by _tcsncpy() if (m_pNextAction != NULL) delete m_pNextAction; if (idActionFollowup != INTERACTION_NO_ACTION) { m_pNextAction = new CMouseAction(); m_pNextAction->Init(pProject, idActionFollowup); } return S_OK; } HRESULT CMouseAction::Parse(CString& csDefinition, CEditorProject *pProject, UINT nInsertPositionMs) { HRESULT hr = S_OK; CString csAction = csDefinition; if (!csAction.IsEmpty()) { if (StringManipulation::StartsWith(csAction, CString(_T("start")))) { m_idAction = INTERACTION_START_REPLAY; } else if (StringManipulation::StartsWith(csAction, CString(_T("stop")))) { m_idAction = INTERACTION_STOP_REPLAY; } else if (StringManipulation::StartsWith(csAction, CString(_T("jump")))) { CString csParameter = csAction; StringManipulation::GetParameter(csParameter); if (StringManipulation::StartsWith(csParameter, CString(_T("next")))) { m_idAction = INTERACTION_JUMP_NEXT_PAGE; } else if (StringManipulation::StartsWith(csParameter, CString(_T("question")))) { m_idAction = INTERACTION_JUMP_RANDOM_QUESTION; } else if (StringManipulation::StartsWith(csParameter, CString(_T("prev")))) { m_idAction = INTERACTION_JUMP_PREVIOUS_PAGE; } else if (StringManipulation::StartsWith(csParameter, CString(_T("page")))) { m_idAction = INTERACTION_JUMP_SPECIFIC_PAGE; StringManipulation::GetParameter(csParameter); // obtain second parameter UINT nMarkPosMs = _ttoi(csParameter); CPage *pPage = pProject->FindPageAt(nMarkPosMs + nInsertPositionMs); if (pPage != NULL) m_nPageMarkId = pPage->GetJumpId(); else hr = E_INVALIDARG; } else if (StringManipulation::StartsWith(csParameter, CString(_T("mark")))) { m_idAction = INTERACTION_JUMP_TARGET_MARK; StringManipulation::GetParameter(csParameter); // obtain second parameter UINT nMarkPosMs = _ttoi(csParameter); // will get resolved later: m_nPageMarkId = nMarkPosMs; // TODO maybe use an additional variable to distinguish between // not specified/not found and not resolved (yet) } else hr = E_INVALIDARG; } else if (StringManipulation::StartsWith(csAction, CString(_T("open")))) { CString csSub = csAction.Mid(5, 3); // 5 -> "open-" if (StringManipulation::StartsWith(csSub, CString(_T("fil")))) m_idAction = INTERACTION_OPEN_FILE; else m_idAction = INTERACTION_OPEN_URL; CString csParameter = csAction; StringManipulation::GetParameter(csParameter); if (m_tszPath != NULL) delete[] m_tszPath; if (csParameter.GetLength() > 0) { CString csOpenPath = csParameter; if (m_idAction == INTERACTION_OPEN_FILE) { // Directly using the constructor will give an exception if the file is missing. //CFile file(csParameter, CFile::modeRead); CFile file; file.Open(csParameter, CFile::modeRead); csOpenPath = file.GetFilePath(); // This converts local paths to global paths // and relies on the fact that the "current directory" is correctly set. // That is done in CEditorDoc::Import(). } int iLength = csOpenPath.GetLength(); m_tszPath = new _TCHAR[iLength + 1]; ZeroMemory(m_tszPath, iLength + 1); _tcsncpy(m_tszPath, csOpenPath, iLength); m_tszPath[iLength] = 0; // is destroyed by _tcsncpy } else hr = E_INVALIDARG; } else if (StringManipulation::StartsWith(csAction, CString(_T("audio")))) { CString csParameter = csAction; StringManipulation::GetParameter(csParameter); if (StringManipulation::StartsWith(csParameter, CString(_T("on")))) m_idAction = INTERACTION_AUDIO_ON; else m_idAction = INTERACTION_AUDIO_OFF; } else if (StringManipulation::StartsWith(csAction, CString(_T("close")))) { m_idAction = INTERACTION_EXIT_PROCESS; } else if (StringManipulation::StartsWith(csAction, CString(_T("check")))) { m_idAction = INTERACTION_CHECK_QUESTION; } else if (StringManipulation::StartsWith(csAction, CString(_T("reset")))) { m_idAction = INTERACTION_RESET_QUESTION; } else hr = E_INVALIDARG; if (SUCCEEDED(hr)) { bool bNext = StringManipulation::GetNextCommand(csAction); if (bNext) { // there are more commands, parse them, too CMouseAction followingAction; hr = followingAction.Parse(csAction, pProject, nInsertPositionMs); if (SUCCEEDED(hr)) AddFollowingAction(&followingAction); } } } return hr; } HRESULT CMouseAction::ResolveJumpTimes(CEditorProject *pProject, UINT nInsertPositionMs) { HRESULT hr = S_OK; if (m_idAction == INTERACTION_JUMP_TARGET_MARK) { CStopJumpMark *pMark = pProject->GetJumpMarkAt(m_nPageMarkId); if (pMark != NULL) { m_nPageMarkId = pMark->GetId(); pMark->RegisterUser(); // BUGFIX #4328: also obtain the label of this mark int iPathLength = 0; LPCTSTR tszMarkLabel = pMark->GetLabel(); if (tszMarkLabel != NULL) iPathLength = _tcslen(tszMarkLabel); if (m_tszPath != NULL) delete[] m_tszPath; m_tszPath = new _TCHAR[iPathLength + 1]; // can be empty ZeroMemory(m_tszPath, iPathLength + 1); if (iPathLength > 0) { _tcsncpy(m_tszPath, tszMarkLabel, iPathLength); m_tszPath[iPathLength] = 0; //destroyed by _tcsncpy() } } else hr = E_IAX_INVALID_DATA; } if (SUCCEEDED(hr) && m_pNextAction != NULL) hr = m_pNextAction->ResolveJumpTimes(pProject, nInsertPositionMs); return hr; } HRESULT CMouseAction::CloneTo(CMouseAction *pTarget) { HRESULT hr = S_OK; if (pTarget == NULL) return E_POINTER; pTarget->m_idAction = m_idAction; pTarget->m_nPageMarkId = m_nPageMarkId; if (pTarget->m_tszPath != NULL) delete[] pTarget->m_tszPath; if (pTarget->m_pNextAction != NULL) delete pTarget->m_pNextAction; if (m_tszPath != NULL) { int iPathLength = _tcslen(m_tszPath); pTarget->m_tszPath = new _TCHAR[iPathLength + 1]; ZeroMemory(pTarget->m_tszPath, iPathLength + 1); _tcsncpy(pTarget->m_tszPath, m_tszPath, iPathLength); pTarget->m_tszPath[iPathLength] = 0; // destroyed by _tcsncpy() } else pTarget->m_tszPath = NULL; if (m_pNextAction != NULL) { pTarget->m_pNextAction = new CMouseAction; hr = m_pNextAction->CloneTo(pTarget->m_pNextAction); } else pTarget->m_pNextAction = NULL; return hr; } CMouseAction* CMouseAction::Copy() { CMouseAction *pNewAction = new CMouseAction(); HRESULT hr = CloneTo(pNewAction); if (SUCCEEDED(hr)) return pNewAction; else { delete pNewAction; return NULL; } } HRESULT CMouseAction::AddFollowingAction(CMouseAction *pAction) { HRESULT hr = S_OK; if (m_pNextAction != NULL) hr = m_pNextAction->AddFollowingAction(pAction); else { m_pNextAction = new CMouseAction; hr = pAction->CloneTo(m_pNextAction); } return hr; } void CMouseAction::SetActionId(AreaActionTypeId actionId) { m_idAction = actionId; } HRESULT CMouseAction::Execute(CEditorDoc *pDoc) { HRESULT hr = S_OK; CEditorProject *pProject = &pDoc->project; UINT nPreviewMs = pDoc->GetCurrentPreviewPos(); HINSTANCE hResult = 0; UINT nJumpMs = 0xffffffff; CString csMessage; switch(m_idAction) { case INTERACTION_JUMP_NEXT_PAGE: pDoc->JumpPreview(pProject->GetNextPageBegin(nPreviewMs)); break; case INTERACTION_JUMP_PREVIOUS_PAGE: pDoc->JumpPreview(pProject->GetPrevPageBegin(nPreviewMs, true)); break; case INTERACTION_JUMP_SPECIFIC_PAGE: nJumpMs = pProject->GetTimeForPageId(m_nPageMarkId); if (nJumpMs != 0xffffffff) pDoc->JumpPreview(nJumpMs); // else page undefined break; case INTERACTION_JUMP_TARGET_MARK: nJumpMs = pProject->GetTimeForMarkId(m_nPageMarkId); if (nJumpMs != 0xffffffff) pDoc->JumpPreview(nJumpMs); // else mark undefined break; case INTERACTION_JUMP_RANDOM_QUESTION: { pDoc->project.StartRandomTest(true); CQuestionnaireEx *pQuestionnaire = pProject->GetFirstQuestionnaireEx(); if (!pQuestionnaire) { ASSERT(FALSE); break; } if (!pQuestionnaire->AnyQuestionsLeft()) { break;// There is no reason to make any jumps to random question after the test finished } if (pQuestionnaire->GetRandomQuestionReplayIndex() == pQuestionnaire->GetNumberOfRandomQuestions()) { pDoc->JumpPreview(pProject->GetLastQuestionEndTimeStamp() + 1); } else { CQuestionEx *pRandomQuestion = pQuestionnaire->GetRandomQuestionFromPosition(pQuestionnaire->GetRandomQuestionReplayIndex()); pDoc->JumpPreview(pRandomQuestion->GetPageBegin()); } break; } case INTERACTION_OPEN_URL: case INTERACTION_OPEN_FILE: // TODO m_tszPath could be local hResult = ::ShellExecute(NULL, _T("open"), m_tszPath, _T(""), _T(""), SW_SHOWNORMAL); if ((int)hResult <= 32) { csMessage.Format(IDS_MSG_FILE_FAILED, m_tszPath); pDoc->ShowErrorMessage(csMessage); } break; case INTERACTION_START_REPLAY: pDoc->StartPreview(); break; case INTERACTION_STOP_REPLAY: if (pDoc->IsPreviewActive()) pDoc->PausePreviewSpecial(); break; case INTERACTION_AUDIO_ON: csMessage.LoadString(IDS_MSG_AUDIO_ON); pDoc->ShowWarningMessage(csMessage); break; case INTERACTION_AUDIO_OFF: csMessage.LoadString(IDS_MSG_AUDIO_OFF); pDoc->ShowWarningMessage(csMessage); break; case INTERACTION_EXIT_PROCESS: csMessage.LoadString(IDS_MSG_CLOSE_INSTANCE); pDoc->ShowWarningMessage(csMessage); break; case INTERACTION_RESET_QUESTION: pProject->ResetQuestion(); break; case INTERACTION_CHECK_QUESTION: if (pDoc->IsPreviewActive()) pDoc->PausePreviewSpecial(); pProject->CheckQuestion(); break; } if (m_pNextAction != NULL) hr = m_pNextAction->Execute(pDoc); return hr; } HRESULT CMouseAction::AppendData(CArrayOutput *pTarget, LPCTSTR tszExportPrefix, CEditorProject *pProject) { HRESULT hr = S_OK; if (pTarget == NULL) return E_POINTER; static _TCHAR tszTarget[2000]; _TCHAR *sTarget = tszTarget; tszTarget[0] = 0; UINT nTimeMs = 0; CString csOutputFileName = m_tszPath; if (csOutputFileName.GetLength() > 0) { bool bIsFile = _taccess(m_tszPath, 04) == 0; if (bIsFile) { if (tszExportPrefix == NULL) { // LEP output: preserve full path // it doesn't matter here if it is a URL or a path: only "\" are replaced _TCHAR tszEscapedPath[1200]; // TODO remove/merge with other occurances (for exampel DrawSdk::Image::Write()) ZeroMemory(tszEscapedPath, 1200); int iOutputPos = 0; int iLength = _tcslen(m_tszPath) + 1; for (int i=0; i<iLength; ++i) { if (m_tszPath[i] == '\\') tszEscapedPath[iOutputPos++] = '\\'; tszEscapedPath[iOutputPos++] = m_tszPath[i]; } csOutputFileName = tszEscapedPath; } else { // this is an export: // make a copy of the file to target directory StringManipulation::GetFilename(csOutputFileName); if (m_nNameUsageCount > 0) { // there is more than one file with this name: change the output name CString csPrefix = csOutputFileName; CString csSuffix = csOutputFileName; CString csNumber; csNumber.Format(_T("_%03d."), m_nNameUsageCount); StringManipulation::GetFilePrefix(csPrefix); StringManipulation::GetFileSuffix(csSuffix); csOutputFileName = csPrefix; csOutputFileName += csNumber; csOutputFileName += csSuffix; } CString csSourceFile = m_tszPath; CString csTargetFile = tszExportPrefix; StringManipulation::GetPath(csTargetFile); csTargetFile += _T("\\"); csTargetFile += csOutputFileName; bool bTargetExists = _taccess(csTargetFile, 00) == 0; if (bTargetExists) { bTargetExists = false; // copy anyway except if they are really the same if (csSourceFile.CompareNoCase(csTargetFile) != 0) { CFile file1(csSourceFile, CFile::modeRead); CFile file2(csTargetFile, CFile::modeRead); if (file1.GetLength() == file2.GetLength()) { CFileStatus fileStatus1; CFileStatus fileStatus2; file1.GetStatus(fileStatus1); file2.GetStatus(fileStatus2); BOOL bTimesTheSame = fileStatus1.m_mtime == fileStatus2.m_mtime; if (bTimesTheSame) bTargetExists = true; } } else { // same source and target path: make no copy/this is a strange special case bTargetExists = true; } } if (!bTargetExists) ::CopyFile(csSourceFile, csTargetFile, FALSE); // TODO what about error here? } } // else: no file: just take the m_tszPath/csOutputFileName as address // TODO what about INTERACTION_OPEN_FILE (or URL) with a local file that // cannot be copied?? // What about the target file cannot be overwritten? } switch(m_idAction) { case INTERACTION_JUMP_NEXT_PAGE: _tcscat(sTarget, _T("jump next")); sTarget += _tcslen(sTarget); break; case INTERACTION_JUMP_PREVIOUS_PAGE: _tcscat(sTarget, _T("jump prev")); sTarget += _tcslen(sTarget); break; case INTERACTION_JUMP_SPECIFIC_PAGE: nTimeMs = pProject->GetTimeForPageId(m_nPageMarkId); if (nTimeMs != 0xffffffff) { _stprintf(sTarget, _T("jump page %d"), nTimeMs); sTarget += _tcslen(sTarget); } // else page undefined break; case INTERACTION_JUMP_TARGET_MARK: nTimeMs = pProject->GetTimeForMarkId(m_nPageMarkId); if (nTimeMs != 0xffffffff) { _stprintf(sTarget, _T("jump mark %d"), nTimeMs); sTarget += _tcslen(sTarget); } // else mark undefined break; case INTERACTION_JUMP_RANDOM_QUESTION: _tcscat(sTarget, _T("jump question")); sTarget += _tcslen(sTarget); break; case INTERACTION_OPEN_URL: // TODO what about TCHAR here? path/url only 8-bit? Maybe not! _stprintf(sTarget, _T("open-url %s"), csOutputFileName); sTarget += _tcslen(sTarget); break; case INTERACTION_OPEN_FILE: // TODO what about TCHAR here? path/url only 8-bit? Maybe not! _stprintf(sTarget, _T("open-file %s"), csOutputFileName); sTarget += _tcslen(sTarget); break; case INTERACTION_START_REPLAY: _tcscat(sTarget, _T("start")); sTarget += _tcslen(sTarget); break; case INTERACTION_STOP_REPLAY: _tcscat(sTarget, _T("stop")); sTarget += _tcslen(sTarget); break; case INTERACTION_AUDIO_ON: _tcscat(sTarget, _T("audio on")); sTarget += _tcslen(sTarget); break; case INTERACTION_AUDIO_OFF: _tcscat(sTarget, _T("audio off")); sTarget += _tcslen(sTarget); break; case INTERACTION_EXIT_PROCESS: _tcscat(sTarget, _T("close")); sTarget += _tcslen(sTarget); break; case INTERACTION_RESET_QUESTION: _tcscat(sTarget, _T("reset")); sTarget += _tcslen(sTarget); break; case INTERACTION_CHECK_QUESTION: _tcscat(sTarget, _T("check")); sTarget += _tcslen(sTarget); break; } if (SUCCEEDED(hr)) hr = pTarget->Append(tszTarget); //ASSERT(!(m_pNextAction != NULL && m_pNextAction->GetActionId() == INTERACTION_NO_ACTION && m_idAction == INTERACTION_NO_ACTION)); if (m_pNextAction != NULL && m_pNextAction->GetActionId() != INTERACTION_NO_ACTION && m_idAction != INTERACTION_NO_ACTION) { pTarget->Append(_T(";")); hr = m_pNextAction->AppendData(pTarget, tszExportPrefix, pProject); } return hr; } void CMouseAction::GetActionStrings(CStringArray &aActionStrings, bool bIsRandomTest) { CString csAction; csAction.LoadString(IDS_NO_ACTION); aActionStrings.Add(csAction); csAction.LoadString(IDS_NEXT_PAGE); aActionStrings.Add(csAction); csAction.LoadString(IDS_PREVIOUS_PAGE); aActionStrings.Add(csAction); csAction.LoadString(IDS_SPECIAL_PAGE); aActionStrings.Add(csAction); csAction.LoadString(IDS_TARGET_MARK); aActionStrings.Add(csAction); if (bIsRandomTest) { csAction.LoadString(IDS_NEXT_RANDOM_QUESTION); aActionStrings.Add(csAction); } csAction.LoadString(IDS_OPEN_URL); aActionStrings.Add(csAction); csAction.LoadString(IDS_OPEN_FILE); aActionStrings.Add(csAction); csAction.LoadString(IDS_START_REPLAY); aActionStrings.Add(csAction); csAction.LoadString(IDS_STOP_REPLAY); aActionStrings.Add(csAction); csAction.LoadString(IDS_SWITCH_AUDIO_ON); aActionStrings.Add(csAction); csAction.LoadString(IDS_SWITCH_AUDIO_OFF); aActionStrings.Add(csAction); csAction.LoadString(IDS_EXIT_PROCESS); aActionStrings.Add(csAction); } AreaActionStringId CMouseAction::GetActionString(CMouseAction *pMouseAction) { AreaActionTypeId nActionId = pMouseAction->GetActionId(); CMouseAction *pNextAction = NULL; if (nActionId == INTERACTION_NO_ACTION) return NO_ACTION; else if (nActionId == INTERACTION_JUMP_NEXT_PAGE) { pNextAction = pMouseAction->GetNextAction(); if (!pNextAction) return NEXT_PAGE; else if (pNextAction->GetActionId() == INTERACTION_START_REPLAY) return NEXT_PAGE_STARTREPLAY; else if (pNextAction->GetActionId() == INTERACTION_STOP_REPLAY) return NEXT_PAGE_STOPREPLAY; } else if (nActionId == INTERACTION_JUMP_PREVIOUS_PAGE) { pNextAction = pMouseAction->GetNextAction(); if (!pNextAction) return PREVIOUS_PAGE; else if (pNextAction->GetActionId() == INTERACTION_START_REPLAY) return PREVIOUS_PAGE_STARTREPLAY; else if (pNextAction->GetActionId() == INTERACTION_STOP_REPLAY) return PREVIOUS_PAGE_STOPREPLAY; } else if (nActionId == INTERACTION_JUMP_SPECIFIC_PAGE) { pNextAction = pMouseAction->GetNextAction(); if (!pNextAction) return SPECIFIC_PAGE; else if (pNextAction->GetActionId() == INTERACTION_START_REPLAY) return SPECIFIC_PAGE_STARTREPLAY; else if (pNextAction->GetActionId() == INTERACTION_STOP_REPLAY) return SPECIFIC_PAGE_STOPREPLAY; } else if (nActionId == INTERACTION_JUMP_TARGET_MARK) { pNextAction = pMouseAction->GetNextAction(); if (!pNextAction) return TARGET_MARK; else if (pNextAction->GetActionId() == INTERACTION_START_REPLAY) return TARGET_MARK_STARTREPLAY; else if (pNextAction->GetActionId() == INTERACTION_STOP_REPLAY) return TARGET_MARK_STOPREPLAY; } else if (nActionId == INTERACTION_JUMP_RANDOM_QUESTION) { return RANDOM_QUESTION; } else if (nActionId == INTERACTION_OPEN_URL) { pNextAction = pMouseAction->GetNextAction(); if (!pNextAction) return OPEN_URL; else if (pNextAction->GetActionId() == INTERACTION_START_REPLAY) return OPEN_URL_STARTREPLAY; else if (pNextAction->GetActionId() == INTERACTION_STOP_REPLAY) return OPEN_URL_STOPREPLAY; } else if (nActionId == INTERACTION_OPEN_FILE) { pNextAction = pMouseAction->GetNextAction(); if (!pNextAction) return OPEN_FILE; else if (pNextAction->GetActionId() == INTERACTION_START_REPLAY) return OPEN_FILE_STARTREPLAY; else if (pNextAction->GetActionId() == INTERACTION_STOP_REPLAY) return OPEN_FILE_STOPREPLAY; } else if (nActionId == INTERACTION_START_REPLAY) { return START_REPLAY; } else if (nActionId == INTERACTION_STOP_REPLAY) { return STOP_REPLAY; } else if (nActionId == INTERACTION_AUDIO_ON) { pNextAction = pMouseAction->GetNextAction(); if (!pNextAction) return AUDIO_ON; else if (pNextAction->GetActionId() == INTERACTION_START_REPLAY) return AUDIO_ON_STARTREPLAY; else if (pNextAction->GetActionId() == INTERACTION_STOP_REPLAY) return AUDIO_ON_STOPREPLAY; } else if (nActionId == INTERACTION_AUDIO_OFF) { pNextAction = pMouseAction->GetNextAction(); if (!pNextAction) return AUDIO_OFF; else if (pNextAction->GetActionId() == INTERACTION_START_REPLAY) return AUDIO_OFF_STARTREPLAY; else if (pNextAction->GetActionId() == INTERACTION_STOP_REPLAY) return AUDIO_OFF_STOPREPLAY; } else if (nActionId == INTERACTION_EXIT_PROCESS) { return EXIT_PROCESS; } return NO_ACTION; } AreaActionTypeId CMouseAction::GetActionId(AreaActionStringId nActionStringId, AreaActionTypeId &nNextActionId) { AreaActionTypeId nActionId = INTERACTION_NO_ACTION; switch (nActionStringId) { case NO_ACTION: nNextActionId = INTERACTION_NO_ACTION; return INTERACTION_NO_ACTION; break; case NEXT_PAGE: nNextActionId = INTERACTION_NO_ACTION; return INTERACTION_JUMP_NEXT_PAGE; break; case NEXT_PAGE_STARTREPLAY: nNextActionId = INTERACTION_START_REPLAY; return INTERACTION_JUMP_NEXT_PAGE; break; case NEXT_PAGE_STOPREPLAY: nNextActionId = INTERACTION_STOP_REPLAY; return INTERACTION_JUMP_NEXT_PAGE; break; case PREVIOUS_PAGE: nNextActionId = INTERACTION_NO_ACTION; return INTERACTION_JUMP_PREVIOUS_PAGE; break; case RANDOM_QUESTION: nNextActionId = INTERACTION_START_REPLAY; return INTERACTION_JUMP_RANDOM_QUESTION; break; case PREVIOUS_PAGE_STARTREPLAY: nNextActionId = INTERACTION_START_REPLAY; return INTERACTION_JUMP_PREVIOUS_PAGE; break; case PREVIOUS_PAGE_STOPREPLAY: nNextActionId = INTERACTION_STOP_REPLAY; return INTERACTION_JUMP_PREVIOUS_PAGE; break; case SPECIFIC_PAGE: nNextActionId = INTERACTION_NO_ACTION; return INTERACTION_JUMP_SPECIFIC_PAGE; break; case SPECIFIC_PAGE_STARTREPLAY: nNextActionId = INTERACTION_START_REPLAY; return INTERACTION_JUMP_SPECIFIC_PAGE; break; case SPECIFIC_PAGE_STOPREPLAY: nNextActionId = INTERACTION_STOP_REPLAY; return INTERACTION_JUMP_SPECIFIC_PAGE; break; case TARGET_MARK: nNextActionId = INTERACTION_NO_ACTION; return INTERACTION_JUMP_TARGET_MARK; break; case TARGET_MARK_STARTREPLAY: nNextActionId = INTERACTION_START_REPLAY; return INTERACTION_JUMP_TARGET_MARK; break; case TARGET_MARK_STOPREPLAY: nNextActionId = INTERACTION_STOP_REPLAY; return INTERACTION_JUMP_TARGET_MARK; break; case OPEN_URL: nNextActionId = INTERACTION_NO_ACTION; return INTERACTION_OPEN_URL; break; case OPEN_URL_STARTREPLAY: nNextActionId = INTERACTION_START_REPLAY; return INTERACTION_OPEN_URL; break; case OPEN_URL_STOPREPLAY: nNextActionId = INTERACTION_STOP_REPLAY; return INTERACTION_OPEN_URL; break; case OPEN_FILE: nNextActionId = INTERACTION_NO_ACTION; return INTERACTION_OPEN_FILE; break; case OPEN_FILE_STARTREPLAY: nNextActionId = INTERACTION_START_REPLAY; return INTERACTION_OPEN_FILE; break; case OPEN_FILE_STOPREPLAY: nNextActionId = INTERACTION_STOP_REPLAY; return INTERACTION_OPEN_FILE; break; case START_REPLAY: nNextActionId = INTERACTION_NO_ACTION; return INTERACTION_START_REPLAY; case STOP_REPLAY: nNextActionId = INTERACTION_NO_ACTION; return INTERACTION_STOP_REPLAY; break; case AUDIO_ON: nNextActionId = INTERACTION_NO_ACTION; return INTERACTION_AUDIO_ON; break; case AUDIO_ON_STARTREPLAY: nNextActionId = INTERACTION_START_REPLAY; return INTERACTION_AUDIO_ON; break; case AUDIO_ON_STOPREPLAY: nNextActionId = INTERACTION_STOP_REPLAY; return INTERACTION_AUDIO_ON; break; case AUDIO_OFF: nNextActionId = INTERACTION_NO_ACTION; return INTERACTION_AUDIO_OFF; break; case AUDIO_OFF_STARTREPLAY: nNextActionId = INTERACTION_START_REPLAY; return INTERACTION_AUDIO_OFF; break; case AUDIO_OFF_STOPREPLAY: nNextActionId = INTERACTION_STOP_REPLAY; return INTERACTION_AUDIO_OFF; break; case EXIT_PROCESS: nNextActionId = INTERACTION_NO_ACTION; return INTERACTION_EXIT_PROCESS; break; } return INTERACTION_NO_ACTION; } //////////////////////////////////////////////////////////////////////////////
lgpl-3.0
marcomaggi/ccexceptions
tests/test-condition-subtyping-errno.c
1
1832
/* Part of: CCExceptions Contents: test for subtyping of errno conditions Date: Apr 18, 2020 Abstract Test file for subtyping of errno conditions. Copyright (C) 2020 Marco Maggi <mrc.mgg@gmail.com> See the COPYING file. */ /** -------------------------------------------------------------------- ** Heaaders. ** ----------------------------------------------------------------- */ #include "condition-subtyping-errno.h" #include <stdio.h> #include <stdlib.h> #include <errno.h> int main (void) { errno_subtyping_init_module(); { cce_location_t L[1]; if (cce_location(L)) { fprintf(stderr, "%s: static message: %s\n", __func__, cce_condition_static_message(cce_condition(L))); if (my_condition_is_errno_subtype(cce_condition(L))) { CCLIB_PC(my_condition_errno_subtype_t const, C, cce_condition(L)); CCLIB_PC(cce_condition_t const, K, &(C->parent)); fprintf(stderr, "%s: is errno subtype, errno=%d, message=%s, data=%d\n", __func__, cce_condition_ref_errno_errnum(K), cce_condition_ref_errno_message(K), *(C->data)); } else { fprintf(stderr, "%s: wrong condition-object type\n", __func__); exit(EXIT_FAILURE); } if (cce_condition_is_errno(cce_condition(L))) { fprintf(stderr, "%s: is errno condition\n", __func__); } else { fprintf(stderr, "%s: wrong condition-object type\n", __func__); exit(EXIT_FAILURE); } if (cce_condition_is_root(cce_condition(L))) { fprintf(stderr, "%s: is root condition\n", __func__); } else { fprintf(stderr, "%s: wrong condition-object type\n", __func__); exit(EXIT_FAILURE); } cce_run_catch_handlers_final(L); } else { cce_raise(L, my_condition_new_errno_subtype(L, ENOMEM, 123)); cce_run_body_handlers(L); } } exit(EXIT_SUCCESS); } /* end of file */
lgpl-3.0
gsvitec/lightning-objects
lmdb/liblmdb/mdb_stat.c
1
6519
/* mdb_stat.c - memory-mapped database status tool */ /* * Copyright 2011-2016 Howard Chu, Symas Corp. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted only as authorized by the OpenLDAP * Public License. * * A copy of this license is available in the file LICENSE in the * top-level directory of the distribution or, alternatively, at * <http://www.OpenLDAP.org/license.html>. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #if defined(_MSC_VER) #include "getopt.h" #include <BaseTsd.h> typedef SSIZE_T ssize_t; #else #include <unistd.h> #endif #include "lmdb.h" #define Z MDB_FMT_Z #define Yu MDB_PRIy(u) static void prstat(MDB_stat *ms) { #if 0 printf(" Page size: %u\n", ms->ms_psize); #endif printf(" Tree depth: %u\n", ms->ms_depth); printf(" Branch pages: %"Yu"\n", ms->ms_branch_pages); printf(" Leaf pages: %"Yu"\n", ms->ms_leaf_pages); printf(" Overflow pages: %"Yu"\n", ms->ms_overflow_pages); printf(" Entries: %"Yu"\n", ms->ms_entries); } static void usage(char *prog) { fprintf(stderr, "usage: %s [-V] [-n] [-e] [-r[r]] [-f[f[f]]] [-a|-s subdb] dbpath\n", prog); exit(EXIT_FAILURE); } int main(int argc, char *argv[]) { int i, rc; MDB_env *env; MDB_txn *txn; MDB_dbi dbi; MDB_stat mst; MDB_envinfo mei; char *prog = argv[0]; char *envname; char *subname = NULL; int alldbs = 0, envinfo = 0, envflags = 0, freinfo = 0, rdrinfo = 0; if (argc < 2) { usage(prog); } /* -a: print stat of main DB and all subDBs * -s: print stat of only the named subDB * -e: print env info * -f: print freelist info * -r: print reader info * -n: use NOSUBDIR flag on env_open * -V: print version and exit * (default) print stat of only the main DB */ while ((i = getopt(argc, argv, "Vaefnrs:")) != EOF) { switch(i) { case 'V': printf("%s\n", MDB_VERSION_STRING); exit(0); break; case 'a': if (subname) usage(prog); alldbs++; break; case 'e': envinfo++; break; case 'f': freinfo++; break; case 'n': envflags |= MDB_NOSUBDIR; break; case 'r': rdrinfo++; break; case 's': if (alldbs) usage(prog); subname = optarg; break; default: usage(prog); } } if (optind != argc - 1) usage(prog); envname = argv[optind]; rc = mdb_env_create(&env); if (rc) { fprintf(stderr, "mdb_env_create failed, error %d %s\n", rc, mdb_strerror(rc)); return EXIT_FAILURE; } if (alldbs || subname) { mdb_env_set_maxdbs(env, 4); } rc = mdb_env_open(env, envname, envflags | MDB_RDONLY, 0664); if (rc) { fprintf(stderr, "mdb_env_open failed, error %d %s\n", rc, mdb_strerror(rc)); goto env_close; } if (envinfo) { (void)mdb_env_stat(env, &mst); (void)mdb_env_info(env, &mei); printf("Environment Info\n"); printf(" Map address: %p\n", mei.me_mapaddr); printf(" Map size: %"Yu"\n", mei.me_mapsize); printf(" Page size: %u\n", mst.ms_psize); printf(" Max pages: %"Yu"\n", mei.me_mapsize / mst.ms_psize); printf(" Number of pages used: %"Yu"\n", mei.me_last_pgno+1); printf(" Last transaction ID: %"Yu"\n", mei.me_last_txnid); printf(" Max readers: %u\n", mei.me_maxreaders); printf(" Number of readers used: %u\n", mei.me_numreaders); } if (rdrinfo) { printf("Reader Table Status\n"); rc = mdb_reader_list(env, (MDB_msg_func *)fputs, stdout); if (rdrinfo > 1) { int dead; mdb_reader_check(env, &dead); printf(" %d stale readers cleared.\n", dead); rc = mdb_reader_list(env, (MDB_msg_func *)fputs, stdout); } if (!(subname || alldbs || freinfo)) goto env_close; } rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn); if (rc) { fprintf(stderr, "mdb_txn_begin failed, error %d %s\n", rc, mdb_strerror(rc)); goto env_close; } if (freinfo) { MDB_cursor *cursor; MDB_val key, data; mdb_size_t pages = 0, *iptr; printf("Freelist Status\n"); dbi = 0; rc = mdb_cursor_open(txn, dbi, &cursor); if (rc) { fprintf(stderr, "mdb_cursor_open failed, error %d %s\n", rc, mdb_strerror(rc)); goto txn_abort; } rc = mdb_stat(txn, dbi, &mst); if (rc) { fprintf(stderr, "mdb_stat failed, error %d %s\n", rc, mdb_strerror(rc)); goto txn_abort; } prstat(&mst); while ((rc = mdb_cursor_get(cursor, &key, &data, MDB_NEXT)) == 0) { iptr = data.mv_data; pages += *iptr; if (freinfo > 1) { char *bad = ""; mdb_size_t pg, prev; ssize_t i, j, span = 0; j = *iptr++; for (i = j, prev = 1; --i >= 0; ) { pg = iptr[i]; if (pg <= prev) bad = " [bad sequence]"; prev = pg; pg += span; for (; i >= span && iptr[i-span] == pg; span++, pg++) ; } printf(" Transaction %"Yu", %"Z"d pages, maxspan %"Z"d%s\n", *(mdb_size_t *)key.mv_data, j, span, bad); if (freinfo > 2) { for (--j; j >= 0; ) { pg = iptr[j]; for (span=1; --j >= 0 && iptr[j] == pg+span; span++) ; printf(span>1 ? " %9"Yu"[%"Z"d]\n" : " %9"Yu"\n", pg, span); } } } } mdb_cursor_close(cursor); printf(" Free pages: %"Yu"\n", pages); } rc = mdb_open(txn, subname, 0, &dbi); if (rc) { fprintf(stderr, "mdb_open failed, error %d %s\n", rc, mdb_strerror(rc)); goto txn_abort; } rc = mdb_stat(txn, dbi, &mst); if (rc) { fprintf(stderr, "mdb_stat failed, error %d %s\n", rc, mdb_strerror(rc)); goto txn_abort; } printf("Status of %s\n", subname ? subname : "Main DB"); prstat(&mst); if (alldbs) { MDB_cursor *cursor; MDB_val key; rc = mdb_cursor_open(txn, dbi, &cursor); if (rc) { fprintf(stderr, "mdb_cursor_open failed, error %d %s\n", rc, mdb_strerror(rc)); goto txn_abort; } while ((rc = mdb_cursor_get(cursor, &key, NULL, MDB_NEXT_NODUP)) == 0) { char *str; MDB_dbi db2; if (memchr(key.mv_data, '\0', key.mv_size)) continue; str = malloc(key.mv_size+1); memcpy(str, key.mv_data, key.mv_size); str[key.mv_size] = '\0'; rc = mdb_open(txn, str, 0, &db2); if (rc == MDB_SUCCESS) printf("Status of %s\n", str); free(str); if (rc) continue; rc = mdb_stat(txn, db2, &mst); if (rc) { fprintf(stderr, "mdb_stat failed, error %d %s\n", rc, mdb_strerror(rc)); goto txn_abort; } prstat(&mst); mdb_close(env, db2); } mdb_cursor_close(cursor); } if (rc == MDB_NOTFOUND) rc = MDB_SUCCESS; mdb_close(env, dbi); txn_abort: mdb_txn_abort(txn); env_close: mdb_env_close(env); return rc ? EXIT_FAILURE : EXIT_SUCCESS; }
lgpl-3.0
devicescape/aws_dynamo
src/aws_dynamo_delete_table.c
1
16478
/* * Copyright (c) 2014 Devicescape Software, Inc. * This file is part of aws_dynamo, a C library for AWS DynamoDB. * * aws_dynamo is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * aws_dynamo is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with aws_dynamo. If not, see <http://www.gnu.org/licenses/>. */ #define _GNU_SOURCE #include "aws_dynamo_utils.h" #include <stdlib.h> #include <yajl/yajl_parse.h> #include "http.h" #include "aws_dynamo.h" #include "aws_dynamo_delete_table.h" enum { PARSER_STATE_NONE, PARSER_STATE_ROOT_MAP, PARSER_STATE_TABLE_DESCRIPTION_KEY, PARSER_STATE_TABLE_DESCRIPTION_MAP, PARSER_STATE_CREATION_DATE_TIME_KEY, PARSER_STATE_KEY_SCHEMA_KEY, PARSER_STATE_KEY_SCHEMA_MAP, PARSER_STATE_HASH_KEY_ELEMENT_KEY, PARSER_STATE_HASH_KEY_ELEMENT_MAP, PARSER_STATE_HASH_KEY_ATTRIBUTE_NAME_KEY, PARSER_STATE_HASH_KEY_ATTRIBUTE_TYPE_KEY, PARSER_STATE_RANGE_KEY_ELEMENT_KEY, PARSER_STATE_RANGE_KEY_ELEMENT_MAP, PARSER_STATE_RANGE_KEY_ATTRIBUTE_NAME_KEY, PARSER_STATE_RANGE_KEY_ATTRIBUTE_TYPE_KEY, PARSER_STATE_PROVISIONED_THROUGHPUT_KEY, PARSER_STATE_PROVISIONED_THROUGHPUT_MAP, PARSER_STATE_READ_CAPACITY_UNITS_KEY, PARSER_STATE_WRITE_CAPACITY_UNITS_KEY, PARSER_STATE_TABLE_NAME_KEY, PARSER_STATE_ITEM_COUNT_KEY, PARSER_STATE_NUMBER_OF_DECREASES_TODAY_KEY, PARSER_STATE_TABLE_STATUS_KEY, PARSER_STATE_TABLE_SIZE_BYTES_KEY, }; struct ctx { struct aws_dynamo_delete_table_response *r; /* Index into the response structure. */ int attribute_index; int parser_state; }; static int handle_number(void *ctx, const char *val, unsigned int len) { struct ctx *_ctx = (struct ctx *)ctx; #ifdef DEBUG_PARSER char buf[len + 1]; snprintf(buf, len + 1, "%s", val); Debug("handle_number, val = %s, enter state %d", buf, _ctx->parser_state); #endif /* DEBUG_PARSER */ switch (_ctx->parser_state) { case PARSER_STATE_CREATION_DATE_TIME_KEY:{ double date_time; if (aws_dynamo_json_get_double(val, len, &date_time) == -1) { Warnx("handle_number: failed to get creation date time."); return 0; } _ctx->r->creation_date_time = (int)date_time; _ctx->parser_state = PARSER_STATE_TABLE_DESCRIPTION_MAP; break; } case PARSER_STATE_READ_CAPACITY_UNITS_KEY:{ if (aws_dynamo_json_get_int(val, len, &(_ctx->r->read_units)) == -1) { Warnx("handle_number: failed to get read units."); return 0; } _ctx->parser_state = PARSER_STATE_PROVISIONED_THROUGHPUT_MAP; break; } case PARSER_STATE_WRITE_CAPACITY_UNITS_KEY:{ if (aws_dynamo_json_get_int(val, len, &(_ctx->r->write_units)) == -1) { Warnx("handle_number: failed to get write units."); return 0; } _ctx->parser_state = PARSER_STATE_PROVISIONED_THROUGHPUT_MAP; break; } case PARSER_STATE_NUMBER_OF_DECREASES_TODAY_KEY:{ if (aws_dynamo_json_get_int(val, len, &(_ctx->r->number_decreases_today)) == -1) { Warnx("handle_number: failed to get number of decreases today."); return 0; } _ctx->parser_state = PARSER_STATE_PROVISIONED_THROUGHPUT_MAP; break; } case PARSER_STATE_ITEM_COUNT_KEY:{ if (aws_dynamo_json_get_int(val, len, &(_ctx->r->item_count)) == -1) { Warnx("handle_number: failed to get item count."); return 0; } _ctx->parser_state = PARSER_STATE_TABLE_DESCRIPTION_MAP; break; } case PARSER_STATE_TABLE_SIZE_BYTES_KEY:{ if (aws_dynamo_json_get_int(val, len, &(_ctx->r->table_size_bytes)) == -1) { Warnx("handle_number: failed to get table size bytes."); return 0; } _ctx->parser_state = PARSER_STATE_TABLE_DESCRIPTION_MAP; break; } default:{ Warnx("handle_number - unexpected state %d", _ctx->parser_state); return 0; break; } } #ifdef DEBUG_PARSER Debug("handle_number exit %d", _ctx->parser_state); #endif /* DEBUG_PARSER */ return 1; } static int handle_string(void *ctx, const unsigned char *val, unsigned int len) { struct ctx *_ctx = (struct ctx *)ctx; #ifdef DEBUG_PARSER char buf[len + 1]; snprintf(buf, len + 1, "%s", val); Debug("handle_string, val = %s, enter state %d", buf, _ctx->parser_state); #endif /* DEBUG_PARSER */ switch (_ctx->parser_state) { case PARSER_STATE_TABLE_STATUS_KEY:{ if (aws_dynamo_json_get_table_status(val, len, &(_ctx->r->status))) { Warnx("handle_string - failed to get table status"); return 0; } _ctx->parser_state = PARSER_STATE_TABLE_DESCRIPTION_MAP; break; } case PARSER_STATE_TABLE_NAME_KEY:{ _ctx->r->table_name = strndup(val, len); _ctx->parser_state = PARSER_STATE_TABLE_DESCRIPTION_MAP; break; } case PARSER_STATE_HASH_KEY_ATTRIBUTE_NAME_KEY:{ _ctx->r->hash_key_name = strndup(val, len); _ctx->parser_state = PARSER_STATE_HASH_KEY_ELEMENT_MAP; break; } case PARSER_STATE_RANGE_KEY_ATTRIBUTE_NAME_KEY:{ _ctx->r->range_key_name = strndup(val, len); _ctx->parser_state = PARSER_STATE_HASH_KEY_ELEMENT_MAP; break; } case PARSER_STATE_HASH_KEY_ATTRIBUTE_TYPE_KEY:{ if (aws_dynamo_json_get_type(val, len, &(_ctx->r->hash_key_type))) { Warnx("handle_string - failed to get hash key type"); return 0; } _ctx->parser_state = PARSER_STATE_HASH_KEY_ELEMENT_MAP; break; } case PARSER_STATE_RANGE_KEY_ATTRIBUTE_TYPE_KEY:{ if (aws_dynamo_json_get_type(val, len, &(_ctx->r->range_key_type))) { Warnx("handle_string - failed to get hash key type"); return 0; } _ctx->parser_state = PARSER_STATE_HASH_KEY_ELEMENT_MAP; break; } default:{ Warnx("handle_string - unexpected state %d", _ctx->parser_state); return 0; break; } } #ifdef DEBUG_PARSER Debug("handle_string exit %d", _ctx->parser_state); #endif /* DEBUG_PARSER */ return 1; } /* one case entry for every "key":{ sets state to whatever map we are now in */ static int handle_start_map(void *ctx) { struct ctx *_ctx = (struct ctx *)ctx; #ifdef DEBUG_PARSER Debug("handle_start_map, enter state %d", _ctx->parser_state); #endif /* DEBUG_PARSER */ switch (_ctx->parser_state) { case PARSER_STATE_NONE:{ _ctx->parser_state = PARSER_STATE_ROOT_MAP; break; } case PARSER_STATE_TABLE_DESCRIPTION_KEY:{ _ctx->parser_state = PARSER_STATE_TABLE_DESCRIPTION_MAP; break; } case PARSER_STATE_KEY_SCHEMA_KEY:{ _ctx->parser_state = PARSER_STATE_KEY_SCHEMA_MAP; break; } case PARSER_STATE_HASH_KEY_ELEMENT_KEY:{ _ctx->parser_state = PARSER_STATE_HASH_KEY_ELEMENT_MAP; break; } case PARSER_STATE_RANGE_KEY_ELEMENT_KEY:{ _ctx->parser_state = PARSER_STATE_RANGE_KEY_ELEMENT_MAP; break; } case PARSER_STATE_PROVISIONED_THROUGHPUT_KEY:{ _ctx->parser_state = PARSER_STATE_PROVISIONED_THROUGHPUT_MAP; break; } default:{ Warnx("handle_start_map - unexpected state: %d", _ctx->parser_state); return 0; break; } } #ifdef DEBUG_PARSER Debug("handle_start_map exit %d", _ctx->parser_state); #endif /* DEBUG_PARSER */ return 1; } /* each map is a case, compare key with all valid keys for that map * and set state accordingly. */ static int handle_map_key(void *ctx, const unsigned char *val, unsigned int len) { struct ctx *_ctx = (struct ctx *)ctx; #ifdef DEBUG_PARSER char buf[len + 1]; snprintf(buf, len + 1, "%s", val); Debug("handle_map_key, val = %s, enter state %d", buf, _ctx->parser_state); #endif /* DEBUG_PARSER */ switch (_ctx->parser_state) { case PARSER_STATE_ROOT_MAP:{ if (AWS_DYNAMO_VALCMP(AWS_DYNAMO_JSON_TABLE_DESCRIPTION, val, len)) { _ctx->parser_state = PARSER_STATE_TABLE_DESCRIPTION_KEY; } else { char key[len + 1]; snprintf(key, len + 1, "%s", val); Warnx("handle_map_key: Unknown root key '%s'.", key); return 0; } break; } case PARSER_STATE_TABLE_DESCRIPTION_MAP:{ if (AWS_DYNAMO_VALCMP(AWS_DYNAMO_JSON_CREATION_DATE_TIME, val, len)) { _ctx->parser_state = PARSER_STATE_CREATION_DATE_TIME_KEY; } else if (AWS_DYNAMO_VALCMP(AWS_DYNAMO_JSON_KEY_SCHEMA, val, len)) { _ctx->parser_state = PARSER_STATE_KEY_SCHEMA_KEY; } else if (AWS_DYNAMO_VALCMP(AWS_DYNAMO_JSON_PROVISIONED_THROUGHPUT, val, len)) { _ctx->parser_state = PARSER_STATE_PROVISIONED_THROUGHPUT_KEY; } else if (AWS_DYNAMO_VALCMP(AWS_DYNAMO_JSON_TABLE_NAME, val, len)) { _ctx->parser_state = PARSER_STATE_TABLE_NAME_KEY; } else if (AWS_DYNAMO_VALCMP(AWS_DYNAMO_JSON_TABLE_STATUS, val, len)) { _ctx->parser_state = PARSER_STATE_TABLE_STATUS_KEY; } else if (AWS_DYNAMO_VALCMP(AWS_DYNAMO_JSON_ITEM_COUNT, val, len)) { _ctx->parser_state = PARSER_STATE_ITEM_COUNT_KEY; } else if (AWS_DYNAMO_VALCMP(AWS_DYNAMO_JSON_TABLE_SIZE_BYTES, val, len)) { _ctx->parser_state = PARSER_STATE_TABLE_SIZE_BYTES_KEY; } else { char key[len + 1]; snprintf(key, len + 1, "%s", val); Warnx("handle_map_key: Unknown table description key '%s'.", key); return 0; } break; } case PARSER_STATE_PROVISIONED_THROUGHPUT_MAP:{ if (AWS_DYNAMO_VALCMP(AWS_DYNAMO_JSON_READ_CAPACITY_UNITS, val, len)) { _ctx->parser_state = PARSER_STATE_READ_CAPACITY_UNITS_KEY; } else if (AWS_DYNAMO_VALCMP(AWS_DYNAMO_JSON_WRITE_CAPACITY_UNITS, val, len)) { _ctx->parser_state = PARSER_STATE_WRITE_CAPACITY_UNITS_KEY; } else if (AWS_DYNAMO_VALCMP(AWS_DYNAMO_JSON_NUMBER_OF_DECREASES_TODAY, val, len)) { _ctx->parser_state = PARSER_STATE_NUMBER_OF_DECREASES_TODAY_KEY; } else { char key[len + 1]; snprintf(key, len + 1, "%s", val); Warnx("handle_map_key: Unknown provisioned throughput key '%s'.", key); return 0; } break; } case PARSER_STATE_KEY_SCHEMA_MAP:{ if (AWS_DYNAMO_VALCMP(AWS_DYNAMO_JSON_HASH_KEY_ELEMENT, val, len)) { _ctx->parser_state = PARSER_STATE_HASH_KEY_ELEMENT_KEY; } else if (AWS_DYNAMO_VALCMP(AWS_DYNAMO_JSON_RANGE_KEY_ELEMENT, val, len)) { _ctx->parser_state = PARSER_STATE_RANGE_KEY_ELEMENT_KEY; } else { char key[len + 1]; snprintf(key, len + 1, "%s", val); Warnx("handle_map_key: Unknown key schema key '%s'.", key); return 0; } break; } case PARSER_STATE_HASH_KEY_ELEMENT_MAP:{ if (AWS_DYNAMO_VALCMP(AWS_DYNAMO_JSON_ATTRIBUTE_NAME, val, len)) { _ctx->parser_state = PARSER_STATE_HASH_KEY_ATTRIBUTE_NAME_KEY; } else if (AWS_DYNAMO_VALCMP(AWS_DYNAMO_JSON_ATTRIBUTE_TYPE, val, len)) { _ctx->parser_state = PARSER_STATE_HASH_KEY_ATTRIBUTE_TYPE_KEY; } else { char key[len + 1]; snprintf(key, len + 1, "%s", val); Warnx("handle_map_key: Unknown hash key element key '%s'.", key); return 0; } break; } case PARSER_STATE_RANGE_KEY_ELEMENT_MAP:{ if (AWS_DYNAMO_VALCMP(AWS_DYNAMO_JSON_ATTRIBUTE_NAME, val, len)) { _ctx->parser_state = PARSER_STATE_RANGE_KEY_ATTRIBUTE_NAME_KEY; } else if (AWS_DYNAMO_VALCMP(AWS_DYNAMO_JSON_ATTRIBUTE_TYPE, val, len)) { _ctx->parser_state = PARSER_STATE_RANGE_KEY_ATTRIBUTE_TYPE_KEY; } else { char key[len + 1]; snprintf(key, len + 1, "%s", val); Warnx("handle_map_key: Unknown range key element key '%s'.", key); return 0; } break; } default:{ Warnx("handle_map_key - unexpected state %d", _ctx->parser_state); return 0; break; } } #ifdef DEBUG_PARSER Debug("handle_map_key exit %d", _ctx->parser_state); #endif /* DEBUG_PARSER */ return 1; } static int handle_end_map(void *ctx) { struct ctx *_ctx = (struct ctx *)ctx; #ifdef DEBUG_PARSER Debug("handle_end_map enter %d", _ctx->parser_state); #endif /* DEBUG_PARSER */ switch (_ctx->parser_state) { case PARSER_STATE_ROOT_MAP:{ _ctx->parser_state = PARSER_STATE_NONE; break; } case PARSER_STATE_TABLE_DESCRIPTION_MAP:{ _ctx->parser_state = PARSER_STATE_ROOT_MAP; break; } case PARSER_STATE_PROVISIONED_THROUGHPUT_MAP:{ _ctx->parser_state = PARSER_STATE_TABLE_DESCRIPTION_MAP; break; } case PARSER_STATE_HASH_KEY_ELEMENT_MAP:{ _ctx->parser_state = PARSER_STATE_KEY_SCHEMA_MAP; break; } case PARSER_STATE_RANGE_KEY_ELEMENT_MAP:{ _ctx->parser_state = PARSER_STATE_KEY_SCHEMA_MAP; break; } case PARSER_STATE_KEY_SCHEMA_MAP:{ _ctx->parser_state = PARSER_STATE_TABLE_DESCRIPTION_MAP; break; } default:{ Warnx("handle_end_map - unexpected state %d", _ctx->parser_state); return 0; break; } } #ifdef DEBUG_PARSER Debug("handle_end_map exit %d", _ctx->parser_state); #endif /* DEBUG_PARSER */ return 1; } static int handle_start_array(void *ctx) { struct ctx *_ctx = (struct ctx *)ctx; #ifdef DEBUG_PARSER Debug("handle_start_array enter %d", _ctx->parser_state); #endif /* DEBUG_PARSER */ switch (_ctx->parser_state) { default:{ Warnx("handle_start_array - unexpected state %d", _ctx->parser_state); return 0; break; } } #ifdef DEBUG_PARSER Debug("handle_start_array exit %d", _ctx->parser_state); #endif /* DEBUG_PARSER */ return 1; } static int handle_end_array(void *ctx) { struct ctx *_ctx = (struct ctx *)ctx; #ifdef DEBUG_PARSER Debug("handle_end_array enter %d", _ctx->parser_state); #endif /* DEBUG_PARSER */ switch (_ctx->parser_state) { default:{ Warnx("handle_end_array - unexpected state %d", _ctx->parser_state); return 0; break; } } #ifdef DEBUG_PARSER Debug("handle_end_array exit %d", _ctx->parser_state); #endif /* DEBUG_PARSER */ return 1; } static yajl_callbacks handle_callbacks = { .yajl_number = handle_number, .yajl_string = handle_string, .yajl_start_map = handle_start_map, .yajl_map_key = handle_map_key, .yajl_end_map = handle_end_map, .yajl_start_array = handle_start_array, .yajl_end_array = handle_end_array, }; struct aws_dynamo_delete_table_response *aws_dynamo_parse_delete_table_response(const char *response, int response_len) { yajl_handle hand; yajl_status stat; struct ctx _ctx = { 0 }; _ctx.r = calloc(sizeof(*(_ctx.r)), 1); if (_ctx.r == NULL) { Warnx("aws_dynamo_parse_delete_table_response: response alloc failed."); return NULL; } #if YAJL_MAJOR == 2 hand = yajl_alloc(&handle_callbacks, NULL, &_ctx); yajl_parse(hand, response, response_len); stat = yajl_complete_parse(hand); #else hand = yajl_alloc(&handle_callbacks, NULL, NULL, &_ctx); yajl_parse(hand, response, response_len); stat = yajl_parse_complete(hand); #endif if (stat != yajl_status_ok) { unsigned char *str = yajl_get_error(hand, 1, response, response_len); Warnx("aws_dynamo_parse_delete_table_response: json parse failed, '%s'", (const char *)str); yajl_free_error(hand, str); yajl_free(hand); aws_dynamo_free_delete_table_response(_ctx.r); return NULL; } yajl_free(hand); return _ctx.r; } struct aws_dynamo_delete_table_response *aws_dynamo_delete_table(struct aws_handle *aws, const char *request) { const char *response; int response_len; struct aws_dynamo_delete_table_response *r; if (aws_dynamo_request(aws, AWS_DYNAMO_DELETE_TABLE, request) == -1) { return NULL; } response = http_get_data(aws->http, &response_len); if (response == NULL) { Warnx("aws_dynamo_delete_table: Failed to get response."); return NULL; } if ((r = aws_dynamo_parse_delete_table_response(response, response_len)) == NULL) { Warnx("aws_dynamo_delete_table: Failed to parse response: '%s'", response); return NULL; } return r; } void aws_dynamo_dump_delete_table_response(struct aws_dynamo_delete_table_response *r) { #ifdef DEBUG_PARSER if (r == NULL) { Debug("Empty response."); return; } Debug("table_name = %s", r->table_name); Debug("creation_date_time = %d", r->creation_date_time); Debug("hash_key_name = %s", r->hash_key_name); Debug("hash_key_type = %d", r->hash_key_type); if (r->range_key_name != NULL) { Debug("range_key_name = %s", r->range_key_name); Debug("range_key_type = %d", r->range_key_type); } Debug("write_units = %d", r->write_units); Debug("read_units = %d", r->read_units); Debug("status = %d", r->status); #endif } void aws_dynamo_free_delete_table_response(struct aws_dynamo_delete_table_response *r) { if (r == NULL) { return; } free(r->hash_key_name); free(r->range_key_name); free(r->table_name); free(r); }
lgpl-3.0
mexus/vk-messages-loader
manager/src/history-export.cpp
1
1749
#include <manager/history-export.h> #include <boost/date_time/posix_time/posix_time.hpp> #include <fstream> #include <stdexcept> namespace manager { HistoryExport::HistoryExport(const cache::Users& users_cache) : users_cache_(users_cache), locale_(std::cout.getloc(), new boost::posix_time::time_facet("%Y/%m/%d %H:%M:%S")) {} void HistoryExport::ExportToFile( const std::shared_ptr<storage::History>& history, const std::string& path) const { std::ofstream f(path); if (!f) { THROW_AT(util::FileWriteException, path); } auto messages = history->GetData(); for (auto& message : messages) { f << FormateDate(message.date) << " "; f << GetUserName(message.from_user_id) << ": "; f << message.body << "\n"; for (auto& attachment : message.attachments) { f << "[Attachment '" << AttachmentTypeToString(attachment.type) << "']: " << attachment.body << "\n"; } } } std::string HistoryExport::FormateDate(time_t date_time) const { std::stringstream s; s.imbue(locale_); s << boost::posix_time::from_time_t(date_time); return s.str(); } std::string HistoryExport::GetUserName(uint64_t id) const { try { auto user = users_cache_.GetData(id); return user.first_name + " " + user.last_name; } catch (const manager::cache::NoDataException&) { return std::to_string(id); } } std::string HistoryExport::AttachmentTypeToString( storage::AttachmentType attachment_type) { switch (attachment_type) { case storage::PHOTO: return "photo"; case storage::VIDEO: return "video"; case storage::STICKER: return "sticker"; } throw std::logic_error( "Looks like unimplemented enumerator has been encountered"); } }
lgpl-3.0
DynabyteSoftware/DynabyteSoftwareCore
Networking/BoostImplementation/src/IPaddress.cpp
1
1553
#include "BoostImplementation/IPaddress.h" using namespace DynabyteSoftware::Networking; using namespace DynabyteSoftware::Networking::BoostImplementation; using namespace DynabyteSoftware::Networking::Internal; using namespace boost::asio::ip; using namespace std; #pragma region Template Utility Functions template<typename AddressType> vector<byte> convertAddressType(const AddressType& boostAddress) { vector<byte> address; for(const auto& addressByte : boostAddress) address.push_back(static_cast<byte>(addressByte)); return address; } #pragma endregion #pragma region Constructors IPaddress::IPaddress(const array<byte, 4>& bytesIPv4) : _address(make_address_v4(reinterpret_cast<const address_v4::bytes_type&>(bytesIPv4))) { } IPaddress::IPaddress(const array<byte, 8>& bytesIPv6) : _address(make_address_v6(reinterpret_cast<const address_v6::bytes_type&>(bytesIPv6))) { } IPaddress::IPaddress(const string& address) : _address(make_address(address)) { } #pragma endregion #pragma region IPaddress AddressFamily IPaddress::getAddressFamily() const { return _address.is_v4() ? AddressFamily::IPv4 : AddressFamily::IPv6; } vector<byte> IPaddress::getAddressBytes() const { if (_address.is_v4()) return convertAddressType(_address.to_v4().to_bytes()); return convertAddressType(_address.to_v6().to_bytes()); } string IPaddress::toString() const { return _address.to_string(); } unique_ptr<IIPaddress> IPaddress::clone() const { return make_unique<IPaddress>(*this); } #pragma endregion
lgpl-3.0
rgbdemo/rgbdemo
calibration/calibrate_pmdnano.cpp
1
4788
/** * Copyright (C) 2013 ManCTL SARL <contact@manctl.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Author: Nicolas Burrus <nicolas.burrus@manctl.com> */ #include "calibration_common.h" #include <ntk/ntk.h> #include <ntk/camera/calibration.h> #include <ntk/camera/pmd_grabber.h> #include <ntk/geometry/pose_3d.h> #include <ntk/numeric/levenberg_marquart_minimizer.h> #include <fstream> #include <QDir> #include <QDebug> using namespace ntk; using namespace cv; // example command line (for copy-n-paste): // calibrate_pmdnano --pattern-width 8 --pattern-height 6 images namespace global { ntk::arg<const char*> opt_image_directory(0, "RGBD images directory", 0); ntk::arg<const char*> opt_output_file("--output", "Calibration file YAML", "calibration.yml"); ntk::arg<const char*> opt_pattern_type("--pattern-type", "Pattern type (chessboard, circles, asymcircles)", "chessboard"); ntk::arg<int> opt_pattern_width("--pattern-width", "Pattern width (number of inner corners)", 10); ntk::arg<int> opt_pattern_height("--pattern-height", "Pattern height (number of inner corners)", 7); ntk::arg<float> opt_square_size("--pattern-size", "Square size in used defined scale", 0.025); ntk::arg<bool> opt_ignore_distortions("--no-undistort", "Ignore distortions (faster processing)", true); ntk::arg<bool> opt_fix_center("--fix-center", "Do not estimate the central point", true); std::string output_filename; PatternType pattern_type; RGBDCalibration calibration; double initial_focal_length; QDir images_dir; QStringList images_list; } void writeNestkMatrix() { global::calibration.saveToFile(global::opt_output_file()); } int main(int argc, char** argv) { arg_base::set_help_option("--help"); arg_parse(argc, argv); ntk::ntk_debug_level = 1; namedWindow("corners"); if (std::string(global::opt_pattern_type()) == "chessboard") global::pattern_type = PatternChessboard; else if (std::string(global::opt_pattern_type()) == "circles") global::pattern_type = PatternCircles; else if (std::string(global::opt_pattern_type()) == "asymcircles") global::pattern_type = PatternAsymCircles; else fatal_error(format("Invalid pattern type: %s\n", global::opt_pattern_type()).c_str()); global::images_dir = QDir(global::opt_image_directory()); ntk_ensure(global::images_dir.exists(), (global::images_dir.absolutePath() + " is not a directory.").toAscii()); global::images_list = global::images_dir.entryList(QStringList("view????*"), QDir::Dirs, QDir::Name); PmdRgbProcessor processor; std::vector<ntk::RGBDImage> images; loadImageList(global::images_dir, global::images_list, &processor, 0, images); if (images.size() < 1) { ntk_dbg(0) << "No images could be read"; return 1; } global::calibration.raw_rgb_size = images[0].rawRgb().size(); global::calibration.rgb_size = global::calibration.rgb_size; global::calibration.raw_depth_size = global::calibration.raw_rgb_size; global::calibration.depth_size = global::calibration.raw_depth_size; std::vector< std::vector<Point2f> > good_corners; std::vector< std::vector<Point2f> > all_corners; getCalibratedCheckerboardCorners(images, global::opt_pattern_width(), global::opt_pattern_height(), global::pattern_type, all_corners, good_corners, true); calibrate_kinect_rgb(images, good_corners, global::calibration, global::opt_pattern_width(), global::opt_pattern_height(), global::opt_square_size(), global::pattern_type, global::opt_ignore_distortions(), global::opt_fix_center(), 0); ntk_dbg_print(global::calibration.rgb_intrinsics(0,0), 0); global::calibration.rgb_intrinsics.copyTo(global::calibration.depth_intrinsics); global::calibration.rgb_distortion.copyTo(global::calibration.depth_distortion); global::calibration.updatePoses(); writeNestkMatrix(); cv::waitKey(10); return 0; }
lgpl-3.0
Bhattiasif/plumed2
src/crystallization/DFSClustering.cpp
2
5775
/* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Copyright (c) 2014,2015 The plumed team (see the PEOPLE file at the root of the distribution for a list of names) See http://www.plumed-code.org for more information. This file is part of plumed, version 2. plumed is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. plumed is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with plumed. If not, see <http://www.gnu.org/licenses/>. +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ #include "DFSClustering.h" namespace PLMD { namespace crystallization { void DFSClustering::registerKeywords( Keywords& keys ){ multicolvar::AdjacencyMatrixAction::registerKeywords( keys ); } DFSClustering::DFSClustering(const ActionOptions&ao): Action(ao), AdjacencyMatrixAction(ao), number_of_cluster(-1), nneigh(getFullNumberOfBaseTasks()), adj_list(getFullNumberOfBaseTasks(),getFullNumberOfBaseTasks()), cluster_sizes(getFullNumberOfBaseTasks()), which_cluster(getFullNumberOfBaseTasks()), color(getFullNumberOfBaseTasks()) { if( getNumberOfBaseMultiColvars()!=1 ) error("should only be running DFS Clustering with one base multicolvar"); } void DFSClustering::turnOnDerivatives(){ // Check base multicolvar isn't density probably other things shouldn't be allowed here as well if( getBaseMultiColvar(0)->isDensity() ) error("DFS clustering cannot be differentiated if base multicolvar is DENSITY"); // Check for dubious vessels for(unsigned i=0;i<getNumberOfVessels();++i){ if( getPntrToVessel(i)->getName()=="MEAN" ) error("MEAN of cluster is not differentiable"); if( getPntrToVessel(i)->getName()=="VMEAN" ) error("VMEAN of cluster is not differentiable"); } MultiColvarBase::turnOnDerivatives(); } unsigned DFSClustering::getNumberOfQuantities(){ return getBaseMultiColvar(0)->getNumberOfQuantities(); } void DFSClustering::completeCalculation(){ // Get the adjacency matrix retrieveAdjacencyLists( nneigh, adj_list ); // for(unsigned i=0;i<nneigh.size();++i){ // printf("ADJACENCY LIST FOR %d HAS %d MEMBERS : ",i,nneigh[i]); // for(unsigned j=0;j<nneigh[i];++j) printf("%d ",adj_list(i,j) ); // printf("\n"); // } // All the clusters have zero size initially for(unsigned i=0;i<cluster_sizes.size();++i){ cluster_sizes[i].first=0; cluster_sizes[i].second=i;} // Perform clustering number_of_cluster=-1; color.assign(color.size(),0); for(unsigned i=0;i<getFullNumberOfBaseTasks();++i){ if( color[i]==0 ){ number_of_cluster++; color[i]=explore(i); } } // Order the clusters in the system by size (this returns ascending order ) std::sort( cluster_sizes.begin(), cluster_sizes.end() ); // Finish the calculation (what we do depends on what we are inheriting into) doCalculationOnCluster(); // // Work out which atoms are in the largest cluster // unsigned n=0; std::vector<unsigned> myatoms( cluster_sizes[cluster_sizes.size() - clustr].first ); // for(unsigned i=0;i<getFullNumberOfBaseTasks();++i){ // if( which_cluster[i]==cluster_sizes[cluster_sizes.size() - clustr].second ){ myatoms[n]=i; n++; } // } // unsigned size=comm.Get_size(), rank=comm.Get_rank(); // // Now calculate properties of the largest cluster // ActionWithVessel::doJobsRequiredBeforeTaskList(); // Note we loose adjacency data by doing this // // Get size for buffer // unsigned bsize=0; std::vector<double> buffer( getSizeOfBuffer( bsize ), 0.0 ); // std::vector<double> vals( getNumberOfQuantities() ); std::vector<unsigned> der_index; // MultiValue myvals( getNumberOfQuantities(), getNumberOfDerivatives() ); // MultiValue bvals( getNumberOfQuantities(), getNumberOfDerivatives() ); // // Get rid of bogus derivatives // clearDerivatives(); getAdjacencyVessel()->setFinishedTrue(); // for(unsigned j=rank;j<myatoms.size();j+=size){ // // Note loop above over array containing atoms so this is load balanced // unsigned i=myatoms[j]; // // Need to copy values from base action // getVectorForTask( i, false, vals ); // for(unsigned i=0;i<vals.size();++i) myvals.setValue( i, vals[i] ); // if( !doNotCalculateDerivatives() ) getVectorDerivatives( i, false, myvals ); // // Run calculate all vessels // calculateAllVessels( i, myvals, bvals, buffer, der_index ); // myvals.clearAll(); // } // // MPI Gather everything // if( buffer.size()>0 ) comm.Sum( buffer ); // finishComputations( buffer ); } int DFSClustering::explore( const unsigned& index ){ color[index]=1; for(unsigned i=0;i<nneigh[index];++i){ unsigned j=adj_list(index,i); if( color[j]==0 ) color[j]=explore(j); } // Count the size of the cluster cluster_sizes[number_of_cluster].first++; which_cluster[index] = number_of_cluster; return color[index]; } void DFSClustering::retrieveAtomsInCluster( const unsigned& clust, std::vector<unsigned>& myatoms ) const { unsigned n=0; myatoms.resize( cluster_sizes[cluster_sizes.size() - clust].first ); for(unsigned i=0;i<getFullNumberOfBaseTasks();++i){ if( which_cluster[i]==cluster_sizes[cluster_sizes.size() - clust].second ){ myatoms[n]=i; n++; } } } } }
lgpl-3.0
ruijieguo/firtex2
test/src/queryparser/QueryExprBisonParserTestCase.cpp
2
5183
#include "queryparser/QueryExprBisonParserTestCase.h" #include "firtex/queryparser/QueryExprParser.h" using namespace std; FX_NS_DEF(queryparser); SETUP_STREAM_LOGGER(queryparser, QueryExprBisonParserTestCase); CPPUNIT_TEST_SUITE_REGISTRATION(QueryExprBisonParserTestCase); QueryExprBisonParserTestCase::QueryExprBisonParserTestCase() { } QueryExprBisonParserTestCase::~QueryExprBisonParserTestCase() { } void QueryExprBisonParserTestCase::setUp() { } void QueryExprBisonParserTestCase::tearDown() { } void QueryExprBisonParserTestCase::testSimpleQueryExpr() { string str = parseExpr("field:single_term"); CPPUNIT_ASSERT_EQUAL(string("field: single_term"), str); } void QueryExprBisonParserTestCase::testAndQueryExpr() { string str = parseExpr("field1:q1 AND field2:q2"); CPPUNIT_ASSERT_EQUAL(string("<field1: q1> AND <field2: q2>"), str); } void QueryExprBisonParserTestCase::testOrQueryExpr() { string str = parseExpr("field1:q1 OR field2:q2"); CPPUNIT_ASSERT_EQUAL(string("<field1: q1> OR <field2: q2>"), str); } void QueryExprBisonParserTestCase::testAndOrQueryExpr() { string str = parseExpr("field1:q1 AND field2:q2 OR field3:q3"); CPPUNIT_ASSERT_EQUAL(string("<<field1: q1> AND <field2: q2>> OR <field3: q3>"), str); } void QueryExprBisonParserTestCase::testRangeQueryExprWithSingleValue() { string str = parseExpr("field1:123"); CPPUNIT_ASSERT_EQUAL(string("field1: 123"), str); } void QueryExprBisonParserTestCase::testRangeQueryExpr() { string str = parseExpr("field1:[123 TO 1000]"); CPPUNIT_ASSERT_EQUAL(string("field1: [123 TO 1000]"), str); str = parseExpr("field1:[abc TO def]"); CPPUNIT_ASSERT_EQUAL(string("field1: [abc TO def]"), str); } void QueryExprBisonParserTestCase::testRangeQueryExprWithExclusive() { string str = parseExpr("field1:{123 TO 1000}"); CPPUNIT_ASSERT_EQUAL(string("field1: {123 TO 1000}"), str); str = parseExpr("field1:{abc TO def}"); CPPUNIT_ASSERT_EQUAL(string("field1: {abc TO def}"), str); } void QueryExprBisonParserTestCase::testRangeQueryExprOneExclusive() { string str = parseExpr("field1:[123 TO 1000}"); CPPUNIT_ASSERT_EQUAL(string("field1: [123 TO 1000}"), str); str = parseExpr("field1:{123 TO 1000]"); CPPUNIT_ASSERT_EQUAL(string("field1: {123 TO 1000]"), str); str = parseExpr("field1:[abc TO def}"); CPPUNIT_ASSERT_EQUAL(string("field1: [abc TO def}"), str); str = parseExpr("field1:{abc TO def]"); CPPUNIT_ASSERT_EQUAL(string("field1: {abc TO def]"), str); } void QueryExprBisonParserTestCase::testRequiredQueryExpr() { string str = parseExpr("+field1:abc"); CPPUNIT_ASSERT_EQUAL(string("+field1: abc"), str); } void QueryExprBisonParserTestCase::testNotQueryExpr() { string str = parseExpr("NOT field1:abc"); CPPUNIT_ASSERT_EQUAL(string("-field1: abc"), str); str = parseExpr("-field1:abc"); CPPUNIT_ASSERT_EQUAL(string("-field1: abc"), str); } void QueryExprBisonParserTestCase::testDefaultOpQueryExpr() { string str = parseExpr("field1:q1 field2:q2"); CPPUNIT_ASSERT_EQUAL(string("<field1: q1> AND <field2: q2>"), str); } void QueryExprBisonParserTestCase::testGroup() { string str = parseExpr("field1:q1 AND (field2:q2 OR field3:q3)"); CPPUNIT_ASSERT_EQUAL(string("<field1: q1> AND <<field2: q2> OR <field3: q3>>"), str); str = parseExpr("(field1:q1 AND field2:q2) OR field3:q3"); CPPUNIT_ASSERT_EQUAL(string("<<field1: q1> AND <field2: q2>> OR <field3: q3>"), str); str = parseExpr("NOT (field1:q1 AND field2:q2) AND field3:q3"); CPPUNIT_ASSERT_EQUAL(string("<-<<field1: q1> AND <field2: q2>>> AND <field3: q3>"), str); } void QueryExprBisonParserTestCase::testFieldGroup() { string str = parseExpr("field1: (q1 q2 q3)"); CPPUNIT_ASSERT_EQUAL(string("<<field1: q1> AND <field1: q2>> AND <field1: q3>"), str); str = parseExpr("field1: (+q1 -q2)"); CPPUNIT_ASSERT_EQUAL(string("<+field1: q1> AND <-field1: q2>"), str); str = parseExpr("field1: (q1 AND q2 OR q3)"); CPPUNIT_ASSERT_EQUAL(string("<<field1: q1> AND <field1: q2>> OR <field1: q3>"), str); str = parseExpr("field1: (q1 AND field2: q2 OR q3)"); CPPUNIT_ASSERT_EQUAL(string("<<field1: q1> AND <field1: q2>> OR <field1: q3>"), str); } void QueryExprBisonParserTestCase::testPhraseExpr() { string str = parseExpr("field1:\"q1 q2 q3\""); CPPUNIT_ASSERT_EQUAL(string("field1: \"q1 q2 q3\""), str); } void QueryExprBisonParserTestCase::testPhraseExprWithSlop() { string str = parseExpr("field1:\"q1 q2 q3\"~10"); CPPUNIT_ASSERT_EQUAL(string("field1: \"q1 q2 q3\"~10"), str); } void QueryExprBisonParserTestCase::testSingleQuotedExpr() { string str = parseExpr("field1:\'(1+1=2)?$#\'"); CPPUNIT_ASSERT_EQUAL(string("field1: (1+1=2)?$#"), str); } void QueryExprBisonParserTestCase::testAnyQueryExpr() { string str = parseExpr("*:*"); CPPUNIT_ASSERT_EQUAL(string("*:*"), str); } string QueryExprBisonParserTestCase::parseExpr(const string& exprStr) { QueryExprParser parser("def_field"); QueryExprPtr pExpr = parser.parse(exprStr); CPPUNIT_ASSERT(pExpr); return pExpr->toString(); } FX_NS_END
lgpl-3.0
mdaus/nitro
modules/c++/nitf/source/IOStreamWriter.cpp
2
2685
/* ========================================================================= * This file is part of NITRO * ========================================================================= * * (C) Copyright 2004 - 2017, MDA Information Systems LLC * * NITRO is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, If not, * see <http://www.gnu.org/licenses/>. * */ #include <nitf/coda-oss.hpp> #include <nitf/IOStreamWriter.hpp> namespace nitf { IOStreamWriter::IOStreamWriter(std::shared_ptr<io::SeekableOutputStream> stream) : mStream(stream) { } void IOStreamWriter::readImpl(void* , size_t ) { throw except::Exception( Ctxt("IOStreamWriter cannot perform reads. " "It is a write-only handle.")); } void IOStreamWriter::writeImpl(const void* buffer, size_t size) { mStream->write(static_cast<const std::byte*>(buffer), size); } bool IOStreamWriter::canSeekImpl() const noexcept { return true; } nitf::Off IOStreamWriter::seekImpl(nitf::Off offset, int whence) { // This whence does not match io::Seekable::Whence // We need to perform a mapping to the correct values. io::Seekable::Whence ioWhence = io::Seekable::START; switch (whence) { case SEEK_SET: ioWhence = io::Seekable::START; break; case SEEK_CUR: ioWhence = io::Seekable::CURRENT; break; case SEEK_END: ioWhence = io::Seekable::END; break; default: throw except::Exception( Ctxt("Unknown whence value when seeking IOStreamWriter: " + std::to_string(whence))); } return mStream->seek(offset, ioWhence); } nitf::Off IOStreamWriter::tellImpl() const { return mStream->tell(); } nitf::Off IOStreamWriter::getSizeImpl() const { const nitf::Off currentLoc = mStream->tell(); mStream->seek(0, io::Seekable::END); const nitf::Off size = mStream->tell(); mStream->seek(currentLoc, io::Seekable::START); return size; } int IOStreamWriter::getModeImpl() const noexcept { return NITF_ACCESS_WRITEONLY; } void IOStreamWriter::closeImpl() noexcept { } }
lgpl-3.0
bradh/six-library
externals/coda-oss/modules/c++/sys/unittests/test_aligned_alloc.cpp
5
2231
/* ========================================================================= * This file is part of sys-c++ * ========================================================================= * * (C) Copyright 2004 - 2014, MDA Information Systems LLC * * sys-c++ is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; If not, * see <http://www.gnu.org/licenses/>. * */ #include <iostream> #include <sys/Conf.h> #include <sys/Path.h> #include <except/Exception.h> #include <str/Convert.h> #include "TestCase.h" namespace { const size_t numBytes(16384); bool testAlignedAlloc(const size_t numBytes, const size_t alignment) { // Allocate an aligned buffer void* const ptr = sys::alignedAlloc(numBytes, alignment); // Confirm it's a multiple of alignment bool const isAligned(reinterpret_cast<size_t>(ptr) % alignment == 0); sys::alignedFree(ptr); if (!isAligned) { std::cerr << "Error: buffer " << ptr << " isn't aligned as expected!\n"; } return isAligned; } TEST_CASE(testAlignedAlloc8) { TEST_ASSERT(testAlignedAlloc(numBytes, 8)); } TEST_CASE(testAlignedAlloc16) { TEST_ASSERT(testAlignedAlloc(numBytes, 16)); } TEST_CASE(testAlignedAlloc32) { TEST_ASSERT(testAlignedAlloc(numBytes, 32)); } TEST_CASE(testAlignedAlloc64) { TEST_ASSERT(testAlignedAlloc(numBytes, 64)); } TEST_CASE(testAlignedAlloc128) { TEST_ASSERT(testAlignedAlloc(numBytes, 128)); } } int main(int argc, char** argv) { TEST_CHECK(testAlignedAlloc8); TEST_CHECK(testAlignedAlloc16); TEST_CHECK(testAlignedAlloc32); TEST_CHECK(testAlignedAlloc64); TEST_CHECK(testAlignedAlloc128); return 0; }
lgpl-3.0
sonbt56/opencore-aacdec
src/calc_auto_corr.c
21
12776
/* ------------------------------------------------------------------ * Copyright (C) 1998-2009 PacketVideo * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. * See the License for the specific language governing permissions * and limitations under the License. * ------------------------------------------------------------------- */ /* Filename: calc_auto_corr.cpp ------------------------------------------------------------------------------ INPUT AND OUTPUT DEFINITIONS ------------------------------------------------------------------------------ FUNCTION DESCRIPTION ------------------------------------------------------------------------------ REQUIREMENTS ------------------------------------------------------------------------------ REFERENCES SC 29 Software Copyright Licencing Disclaimer: This software module was originally developed by Coding Technologies and edited by - in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards for reference purposes and its performance may not have been optimized. This software module is an implementation of one or more tools as specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards. ISO/IEC gives users free license to this software module or modifications thereof for use in products claiming conformance to audiovisual and image-coding related ITU Recommendations and/or ISO/IEC International Standards. ISO/IEC gives users the same free license to this software module or modifications thereof for research purposes and further ISO/IEC standardisation. Those intending to use this software module in products are advised that its use may infringe existing patents. ISO/IEC have no liability for use of this software module or modifications thereof. Copyright is not released for products that do not conform to audiovisual and image-coding related ITU Recommendations and/or ISO/IEC International Standards. The original developer retains full right to modify and use the code for its own purpose, assign or donate the code to a third party and to inhibit third parties from using the code for products that do not conform to audiovisual and image-coding related ITU Recommendations and/or ISO/IEC International Standards. This copyright notice must be included in all copies or derivative works. Copyright (c) ISO/IEC 2002. ------------------------------------------------------------------------------ PSEUDO-CODE ------------------------------------------------------------------------------ */ /*---------------------------------------------------------------------------- ; INCLUDES ----------------------------------------------------------------------------*/ #include "config.h" #ifdef AAC_PLUS #include "calc_auto_corr.h" #include "aac_mem_funcs.h" /*---------------------------------------------------------------------------- ; MACROS ; Define module specific macros here ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; DEFINES ; Include all pre-processor statements here. Include conditional ; compile variables also. ----------------------------------------------------------------------------*/ #include "fxp_mul32.h" #include "pv_normalize.h" #define N 2 /*---------------------------------------------------------------------------- ; LOCAL FUNCTION DEFINITIONS ; Function Prototype declaration ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; LOCAL STORE/BUFFER/POINTER DEFINITIONS ; Variable declaration - defined here and used outside this module ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; EXTERNAL FUNCTION REFERENCES ; Declare functions defined elsewhere and referenced in this module ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; EXTERNAL GLOBAL STORE/BUFFER/POINTER REFERENCES ; Declare variables used in this module but defined elsewhere ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; FUNCTION CODE ----------------------------------------------------------------------------*/ void calc_auto_corr_LC(struct ACORR_COEFS *ac, Int32 realBuf[][32], Int32 bd, Int32 len) { Int32 j; Int32 temp1; Int32 temp3; Int32 temp5; Int64 temp_r01r; Int64 temp_r02r; Int64 temp_r11r; Int64 temp_r12r; Int64 temp_r22r; Int64 max = 0; temp1 = (realBuf[ 0][bd]) >> N; temp3 = (realBuf[-1][bd]) >> N; temp5 = (realBuf[-2][bd]) >> N; temp_r11r = fxp_mac64_Q31(0, temp3, temp3); /* [j-1]*[j-1] */ temp_r12r = fxp_mac64_Q31(0, temp3, temp5); /* [j-1]*[j-2] */ temp_r22r = fxp_mac64_Q31(0, temp5, temp5); /* [j-2]*[j-2] */ temp_r01r = 0; temp_r02r = 0; for (j = 1; j < len; j++) { temp_r01r = fxp_mac64_Q31(temp_r01r, temp1, temp3); /* [j ]*[j-1] */ temp_r02r = fxp_mac64_Q31(temp_r02r, temp1, temp5); /* [j ]*[j-2] */ temp_r11r = fxp_mac64_Q31(temp_r11r, temp1, temp1); /* [j-1]*[j-1] */ temp5 = temp3; temp3 = temp1; temp1 = (realBuf[j][bd]) >> N; } temp_r22r += temp_r11r; temp_r12r += temp_r01r; /* [j-1]*[j-2] */ temp_r22r = fxp_mac64_Q31(temp_r22r, -temp3, temp3); temp_r01r = fxp_mac64_Q31(temp_r01r, temp1, temp3); temp_r02r = fxp_mac64_Q31(temp_r02r, temp1, temp5); max |= temp_r01r ^(temp_r01r >> 63); max |= temp_r02r ^(temp_r02r >> 63); max |= temp_r11r; max |= temp_r12r ^(temp_r12r >> 63); max |= temp_r22r; if (max) { temp1 = (UInt32)(max >> 32); if (temp1) { temp3 = 33 - pv_normalize(temp1); ac->r01r = (Int32)(temp_r01r >> temp3); ac->r02r = (Int32)(temp_r02r >> temp3); ac->r11r = (Int32)(temp_r11r >> temp3); ac->r12r = (Int32)(temp_r12r >> temp3); ac->r22r = (Int32)(temp_r22r >> temp3); } else { temp3 = pv_normalize(((UInt32)max) >> 1) - 2; if (temp3 > 0) { ac->r01r = (Int32)(temp_r01r << temp3); ac->r02r = (Int32)(temp_r02r << temp3); ac->r11r = (Int32)(temp_r11r << temp3); ac->r12r = (Int32)(temp_r12r << temp3); ac->r22r = (Int32)(temp_r22r << temp3); } else { temp3 = -temp3; ac->r01r = (Int32)(temp_r01r >> temp3); ac->r02r = (Int32)(temp_r02r >> temp3); ac->r11r = (Int32)(temp_r11r >> temp3); ac->r12r = (Int32)(temp_r12r >> temp3); ac->r22r = (Int32)(temp_r22r >> temp3); } } /* * ac->det = ac->r11r*ac->r22r - rel*(ac->r12r*ac->r12r); */ /* 1/(1 + 1e-6) == 1 - 1e-6 */ /* 2^-20 == 1e-6 */ ac->det = fxp_mul32_Q30(ac->r12r, ac->r12r); ac->det -= ac->det >> 20; ac->det = fxp_mul32_Q30(ac->r11r, ac->r22r) - ac->det; } else { pv_memset((void *)ac, 0, sizeof(struct ACORR_COEFS)); } } #ifdef HQ_SBR void calc_auto_corr(struct ACORR_COEFS *ac, Int32 realBuf[][32], Int32 imagBuf[][32], Int32 bd, Int32 len) { Int32 j; Int32 temp1; Int32 temp2; Int32 temp3; Int32 temp4; Int32 temp5; Int32 temp6; Int64 accu1 = 0; Int64 accu2 = 0; Int64 accu3 = 0; Int64 accu4 = 0; Int64 accu5 = 0; Int64 temp_r12r; Int64 temp_r12i; Int64 temp_r22r; Int64 max = 0; temp1 = realBuf[0 ][bd] >> N; temp2 = imagBuf[0 ][bd] >> N; temp3 = realBuf[0-1][bd] >> N; temp4 = imagBuf[0-1][bd] >> N; temp5 = realBuf[0-2][bd] >> N; temp6 = imagBuf[0-2][bd] >> N; temp_r22r = fxp_mac64_Q31(0, temp5, temp5); temp_r22r = fxp_mac64_Q31(temp_r22r, temp6, temp6); temp_r12r = fxp_mac64_Q31(0, temp3, temp5); temp_r12r = fxp_mac64_Q31(temp_r12r, temp4, temp6); temp_r12i = -fxp_mac64_Q31(0, temp3, temp6); temp_r12i = fxp_mac64_Q31(temp_r12i, temp4, temp5); for (j = 1; j < len; j++) { accu1 = fxp_mac64_Q31(accu1, temp3, temp3); accu1 = fxp_mac64_Q31(accu1, temp4, temp4); accu2 = fxp_mac64_Q31(accu2, temp1, temp3); accu2 = fxp_mac64_Q31(accu2, temp2, temp4); accu3 = fxp_mac64_Q31(accu3, temp2, temp3); accu3 = fxp_mac64_Q31(accu3, -temp1, temp4); accu4 = fxp_mac64_Q31(accu4, temp1, temp5); accu4 = fxp_mac64_Q31(accu4, temp2, temp6); accu5 = fxp_mac64_Q31(accu5, temp2, temp5); accu5 = fxp_mac64_Q31(accu5, -temp1, temp6); temp5 = temp3; temp6 = temp4; temp3 = temp1; temp4 = temp2; temp1 = realBuf[j][bd] >> N; temp2 = imagBuf[j][bd] >> N; } temp_r22r += accu1; temp_r12r += accu2; temp_r12i += accu3; accu1 = fxp_mac64_Q31(accu1, temp3, temp3); accu1 = fxp_mac64_Q31(accu1, temp4, temp4); accu2 = fxp_mac64_Q31(accu2, temp1, temp3); accu2 = fxp_mac64_Q31(accu2, temp2, temp4); accu3 = fxp_mac64_Q31(accu3, temp2, temp3); accu3 = fxp_mac64_Q31(accu3, -temp1, temp4); accu4 = fxp_mac64_Q31(accu4, temp1, temp5); accu4 = fxp_mac64_Q31(accu4, temp2, temp6); accu5 = fxp_mac64_Q31(accu5, temp2, temp5); accu5 = fxp_mac64_Q31(accu5, -temp1, temp6); max |= accu5 ^(accu5 >> 63); max |= accu4 ^(accu4 >> 63); max |= accu3 ^(accu3 >> 63); max |= accu2 ^(accu2 >> 63); max |= accu1; max |= temp_r12r ^(temp_r12r >> 63); max |= temp_r12i ^(temp_r12i >> 63); max |= temp_r22r; if (max) { temp1 = (UInt32)(max >> 32); if (temp1) { temp1 = 34 - pv_normalize(temp1); ac->r11r = (Int32)(accu1 >> temp1); ac->r01r = (Int32)(accu2 >> temp1); ac->r01i = (Int32)(accu3 >> temp1); ac->r02r = (Int32)(accu4 >> temp1); ac->r02i = (Int32)(accu5 >> temp1); ac->r12r = (Int32)(temp_r12r >> temp1); ac->r12i = (Int32)(temp_r12i >> temp1); ac->r22r = (Int32)(temp_r22r >> temp1); } else { temp1 = pv_normalize(((UInt32)max) >> 1) - 3; if (temp1 > 0) { ac->r11r = (Int32)(accu1 << temp1); ac->r01r = (Int32)(accu2 << temp1); ac->r01i = (Int32)(accu3 << temp1); ac->r02r = (Int32)(accu4 << temp1); ac->r02i = (Int32)(accu5 << temp1); ac->r12r = (Int32)(temp_r12r << temp1); ac->r12i = (Int32)(temp_r12i << temp1); ac->r22r = (Int32)(temp_r22r << temp1); } else { temp1 = -temp1; ac->r11r = (Int32)(accu1 >> temp1); ac->r01r = (Int32)(accu2 >> temp1); ac->r01i = (Int32)(accu3 >> temp1); ac->r02r = (Int32)(accu4 >> temp1); ac->r02i = (Int32)(accu5 >> temp1); ac->r12r = (Int32)(temp_r12r >> temp1); ac->r12i = (Int32)(temp_r12i >> temp1); ac->r22r = (Int32)(temp_r22r >> temp1); } } /* * ac->det = ac->r11r*ac->r22r - rel*(ac->r12r*ac->r12r); */ /* 1/(1 + 1e-6) == 1 - 1e-6 */ /* 2^-20 == 1e-6 */ ac->det = fxp_mul32_Q29(ac->r12i, ac->r12i); ac->det = fxp_mac32_Q29(ac->r12r, ac->r12r, ac->det); ac->det -= ac->det >> 20; ac->det = -fxp_msu32_Q29(ac->r11r, ac->r22r, ac->det); } else { pv_memset((void *)ac, 0, sizeof(struct ACORR_COEFS)); } } #endif #endif
lgpl-3.0
stoneshaker/libswiftnav
clapack-3.2.1-CMAKE/BLAS/SRC/csrot.c
26
4358
/* csrot.f -- translated by f2c (version 20061008). You must link the resulting object file with libf2c: on Microsoft Windows system, link with libf2c.lib; on Linux or Unix systems, link with .../path/to/libf2c.a -lm or, if you install libf2c.a in a standard place, with -lf2c -lm -- in that order, at the end of the command line, as in cc *.o -lf2c -lm Source for libf2c is in /netlib/f2c/libf2c.zip, e.g., http://www.netlib.org/f2c/libf2c.zip */ #include "f2c.h" #include "blaswrap.h" /* Subroutine */ int csrot_(integer *n, complex *cx, integer *incx, complex * cy, integer *incy, real *c__, real *s) { /* System generated locals */ integer i__1, i__2, i__3, i__4; complex q__1, q__2, q__3; /* Local variables */ integer i__, ix, iy; complex ctemp; /* .. Scalar Arguments .. */ /* .. */ /* .. Array Arguments .. */ /* .. */ /* Purpose */ /* ======= */ /* Applies a plane rotation, where the cos and sin (c and s) are real */ /* and the vectors cx and cy are complex. */ /* jack dongarra, linpack, 3/11/78. */ /* Arguments */ /* ========== */ /* N (input) INTEGER */ /* On entry, N specifies the order of the vectors cx and cy. */ /* N must be at least zero. */ /* Unchanged on exit. */ /* CX (input) COMPLEX array, dimension at least */ /* ( 1 + ( N - 1 )*abs( INCX ) ). */ /* Before entry, the incremented array CX must contain the n */ /* element vector cx. On exit, CX is overwritten by the updated */ /* vector cx. */ /* INCX (input) INTEGER */ /* On entry, INCX specifies the increment for the elements of */ /* CX. INCX must not be zero. */ /* Unchanged on exit. */ /* CY (input) COMPLEX array, dimension at least */ /* ( 1 + ( N - 1 )*abs( INCY ) ). */ /* Before entry, the incremented array CY must contain the n */ /* element vector cy. On exit, CY is overwritten by the updated */ /* vector cy. */ /* INCY (input) INTEGER */ /* On entry, INCY specifies the increment for the elements of */ /* CY. INCY must not be zero. */ /* Unchanged on exit. */ /* C (input) REAL */ /* On entry, C specifies the cosine, cos. */ /* Unchanged on exit. */ /* S (input) REAL */ /* On entry, S specifies the sine, sin. */ /* Unchanged on exit. */ /* ===================================================================== */ /* .. Local Scalars .. */ /* .. */ /* .. Executable Statements .. */ /* Parameter adjustments */ --cy; --cx; /* Function Body */ if (*n <= 0) { return 0; } if (*incx == 1 && *incy == 1) { goto L20; } /* code for unequal increments or equal increments not equal */ /* to 1 */ ix = 1; iy = 1; if (*incx < 0) { ix = (-(*n) + 1) * *incx + 1; } if (*incy < 0) { iy = (-(*n) + 1) * *incy + 1; } i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = ix; q__2.r = *c__ * cx[i__2].r, q__2.i = *c__ * cx[i__2].i; i__3 = iy; q__3.r = *s * cy[i__3].r, q__3.i = *s * cy[i__3].i; q__1.r = q__2.r + q__3.r, q__1.i = q__2.i + q__3.i; ctemp.r = q__1.r, ctemp.i = q__1.i; i__2 = iy; i__3 = iy; q__2.r = *c__ * cy[i__3].r, q__2.i = *c__ * cy[i__3].i; i__4 = ix; q__3.r = *s * cx[i__4].r, q__3.i = *s * cx[i__4].i; q__1.r = q__2.r - q__3.r, q__1.i = q__2.i - q__3.i; cy[i__2].r = q__1.r, cy[i__2].i = q__1.i; i__2 = ix; cx[i__2].r = ctemp.r, cx[i__2].i = ctemp.i; ix += *incx; iy += *incy; /* L10: */ } return 0; /* code for both increments equal to 1 */ L20: i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__; q__2.r = *c__ * cx[i__2].r, q__2.i = *c__ * cx[i__2].i; i__3 = i__; q__3.r = *s * cy[i__3].r, q__3.i = *s * cy[i__3].i; q__1.r = q__2.r + q__3.r, q__1.i = q__2.i + q__3.i; ctemp.r = q__1.r, ctemp.i = q__1.i; i__2 = i__; i__3 = i__; q__2.r = *c__ * cy[i__3].r, q__2.i = *c__ * cy[i__3].i; i__4 = i__; q__3.r = *s * cx[i__4].r, q__3.i = *s * cx[i__4].i; q__1.r = q__2.r - q__3.r, q__1.i = q__2.i - q__3.i; cy[i__2].r = q__1.r, cy[i__2].i = q__1.i; i__2 = i__; cx[i__2].r = ctemp.r, cx[i__2].i = ctemp.i; /* L30: */ } return 0; } /* csrot_ */
lgpl-3.0
tsaikd/MagicKD
tags/1.0.2.1/CxImage/CxImage/ximaenc.cpp
27
25972
// xImaCodec.cpp : Encode Decode functions /* 07/08/2001 v1.00 - Davide Pizzolato - www.xdp.it * CxImage version 5.99c 17/Oct/2004 */ #include "ximage.h" #if CXIMAGE_SUPPORT_JPG #include "ximajpg.h" #endif #if CXIMAGE_SUPPORT_GIF #include "ximagif.h" #endif #if CXIMAGE_SUPPORT_PNG #include "ximapng.h" #endif #if CXIMAGE_SUPPORT_MNG #include "ximamng.h" #endif #if CXIMAGE_SUPPORT_BMP #include "ximabmp.h" #endif #if CXIMAGE_SUPPORT_ICO #include "ximaico.h" #endif #if CXIMAGE_SUPPORT_TIF #include "ximatif.h" #endif #if CXIMAGE_SUPPORT_TGA #include "ximatga.h" #endif #if CXIMAGE_SUPPORT_PCX #include "ximapcx.h" #endif #if CXIMAGE_SUPPORT_WBMP #include "ximawbmp.h" #endif #if CXIMAGE_SUPPORT_WMF #include "ximawmf.h" // <vho> - WMF/EMF support #endif #if CXIMAGE_SUPPORT_J2K #include "ximaj2k.h" #endif #if CXIMAGE_SUPPORT_JBG #include "ximajbg.h" #endif #if CXIMAGE_SUPPORT_JASPER #include "ximajas.h" #endif //////////////////////////////////////////////////////////////////////////////// #if CXIMAGE_SUPPORT_ENCODE //////////////////////////////////////////////////////////////////////////////// bool CxImage::EncodeSafeCheck(CxFile *hFile) { if (hFile==NULL) { strcpy(info.szLastError,CXIMAGE_ERR_NOFILE); return true; } if (pDib==NULL){ strcpy(info.szLastError,CXIMAGE_ERR_NOIMAGE); return true; } return false; } //////////////////////////////////////////////////////////////////////////////// //#ifdef WIN32 //bool CxImage::Save(LPCWSTR filename, DWORD imagetype) //{ // FILE* hFile; //file handle to write the image // if ((hFile=_wfopen(filename,L"wb"))==NULL) return false; // bool bOK = Encode(hFile,imagetype); // fclose(hFile); // return bOK; //} //#endif //WIN32 //////////////////////////////////////////////////////////////////////////////// // For UNICODE support: char -> TCHAR /** * Saves to disk the image in a specific format. * \param filename: file name * \param imagetype: file format, see ENUM_CXIMAGE_FORMATS * \return true if everything is ok */ bool CxImage::Save(const TCHAR * filename, DWORD imagetype) { FILE* hFile; //file handle to write the image #ifdef WIN32 if ((hFile=_tfopen(filename,_T("wb")))==NULL) return false; // For UNICODE support #else if ((hFile=fopen(filename,"wb"))==NULL) return false; #endif bool bOK = Encode(hFile,imagetype); fclose(hFile); return bOK; } //////////////////////////////////////////////////////////////////////////////// /** * Saves to disk the image in a specific format. * \param hFile: file handle, open and enabled for writing. * \param imagetype: file format, see ENUM_CXIMAGE_FORMATS * \return true if everything is ok */ bool CxImage::Encode(FILE *hFile, DWORD imagetype) { CxIOFile file(hFile); return Encode(&file,imagetype); } //////////////////////////////////////////////////////////////////////////////// /** * Saves to memory buffer the image in a specific format. * \param buffer: output memory buffer pointer. Must be NULL, * the function allocates and fill the memory, * the application must free the buffer, see also FreeMemory(). * \param size: output memory buffer size. * \param imagetype: file format, see ENUM_CXIMAGE_FORMATS * \return true if everything is ok */ bool CxImage::Encode(BYTE * &buffer, long &size, DWORD imagetype) { if (buffer!=NULL){ strcpy(info.szLastError,"the buffer must be empty"); return false; } CxMemFile file; file.Open(); if(Encode(&file,imagetype)){ buffer=file.GetBuffer(); size=file.Size(); return true; } return false; } //////////////////////////////////////////////////////////////////////////////// /** * Saves to disk the image in a specific format. * \param hFile: file handle (implemented using CxMemFile or CxIOFile), * open and enabled for writing. * \param imagetype: file format, see ENUM_CXIMAGE_FORMATS * \return true if everything is ok * \sa ENUM_CXIMAGE_FORMATS */ bool CxImage::Encode(CxFile *hFile, DWORD imagetype) { #if CXIMAGE_SUPPORT_BMP if (imagetype==CXIMAGE_FORMAT_BMP){ CxImageBMP newima; newima.Ghost(this); if (newima.Encode(hFile)){ return true; } else { strcpy(info.szLastError,newima.GetLastError()); return false; } } #endif #if CXIMAGE_SUPPORT_ICO if (imagetype==CXIMAGE_FORMAT_ICO){ CxImageICO newima; newima.Ghost(this); if (newima.Encode(hFile)){ return true; } else { strcpy(info.szLastError,newima.GetLastError()); return false; } } #endif #if CXIMAGE_SUPPORT_TIF if (imagetype==CXIMAGE_FORMAT_TIF){ CxImageTIF newima; newima.Ghost(this); if (newima.Encode(hFile)){ return true; } else { strcpy(info.szLastError,newima.GetLastError()); return false; } } #endif #if CXIMAGE_SUPPORT_JPG if (imagetype==CXIMAGE_FORMAT_JPG){ CxImageJPG newima; newima.Ghost(this); if (newima.Encode(hFile)){ return true; } else { strcpy(info.szLastError,newima.GetLastError()); return false; } } #endif #if CXIMAGE_SUPPORT_GIF if (imagetype==CXIMAGE_FORMAT_GIF){ CxImageGIF newima; newima.Ghost(this); if (newima.Encode(hFile)){ return true; } else { strcpy(info.szLastError,newima.GetLastError()); return false; } } #endif #if CXIMAGE_SUPPORT_PNG if (imagetype==CXIMAGE_FORMAT_PNG){ CxImagePNG newima; newima.Ghost(this); if (newima.Encode(hFile)){ return true; } else { strcpy(info.szLastError,newima.GetLastError()); return false; } } #endif #if CXIMAGE_SUPPORT_MNG if (imagetype==CXIMAGE_FORMAT_MNG){ CxImageMNG newima; newima.Ghost(this); if (newima.Encode(hFile)){ return true; } else { strcpy(info.szLastError,newima.GetLastError()); return false; } } #endif #if CXIMAGE_SUPPORT_TGA if (imagetype==CXIMAGE_FORMAT_TGA){ CxImageTGA newima; newima.Ghost(this); if (newima.Encode(hFile)){ return true; } else { strcpy(info.szLastError,newima.GetLastError()); return false; } } #endif #if CXIMAGE_SUPPORT_PCX if (imagetype==CXIMAGE_FORMAT_PCX){ CxImagePCX newima; newima.Ghost(this); if (newima.Encode(hFile)){ return true; } else { strcpy(info.szLastError,newima.GetLastError()); return false; } } #endif #if CXIMAGE_SUPPORT_WBMP if (imagetype==CXIMAGE_FORMAT_WBMP){ CxImageWBMP newima; newima.Ghost(this); if (newima.Encode(hFile)){ return true; } else { strcpy(info.szLastError,newima.GetLastError()); return false; } } #endif #if CXIMAGE_SUPPORT_WMF && CXIMAGE_SUPPORT_WINDOWS // <vho> - WMF/EMF support if (imagetype==CXIMAGE_FORMAT_WMF){ CxImageWMF newima; newima.Ghost(this); if (newima.Encode(hFile)){ return true; } else { strcpy(info.szLastError,newima.GetLastError()); return false; } } #endif #if CXIMAGE_SUPPORT_J2K if (imagetype==CXIMAGE_FORMAT_J2K){ CxImageJ2K newima; newima.Ghost(this); if (newima.Encode(hFile)){ return true; } else { strcpy(info.szLastError,newima.GetLastError()); return false; } } #endif #if CXIMAGE_SUPPORT_JBG if (imagetype==CXIMAGE_FORMAT_JBG){ CxImageJBG newima; newima.Ghost(this); if (newima.Encode(hFile)){ return true; } else { strcpy(info.szLastError,newima.GetLastError()); return false; } } #endif #if CXIMAGE_SUPPORT_JASPER if ( #if CXIMAGE_SUPPORT_JP2 imagetype==CXIMAGE_FORMAT_JP2 || #endif #if CXIMAGE_SUPPORT_JPC imagetype==CXIMAGE_FORMAT_JPC || #endif #if CXIMAGE_SUPPORT_PGX imagetype==CXIMAGE_FORMAT_PGX || #endif #if CXIMAGE_SUPPORT_PNM imagetype==CXIMAGE_FORMAT_PNM || #endif #if CXIMAGE_SUPPORT_RAS imagetype==CXIMAGE_FORMAT_RAS || #endif false ){ CxImageJAS newima; newima.Ghost(this); if (newima.Encode(hFile,imagetype)){ return true; } else { strcpy(info.szLastError,newima.GetLastError()); return false; } } #endif strcpy(info.szLastError,"Encode: Unknown format"); return false; } //////////////////////////////////////////////////////////////////////////////// /** * Saves to disk or memory pagecount images, referenced by an array of CxImage pointers. * \param hFile: file handle. * \param pImages: array of CxImage pointers. * \param pagecount: number of images. * \param imagetype: can be CXIMAGE_FORMAT_TIF or CXIMAGE_FORMAT_GIF. * \return true if everything is ok */ bool CxImage::Encode(FILE * hFile, CxImage ** pImages, int pagecount, DWORD imagetype) { CxIOFile file(hFile); return Encode(&file, pImages, pagecount,imagetype); } //////////////////////////////////////////////////////////////////////////////// /** * Saves to disk or memory pagecount images, referenced by an array of CxImage pointers. * \param hFile: file handle (implemented using CxMemFile or CxIOFile). * \param pImages: array of CxImage pointers. * \param pagecount: number of images. * \param imagetype: can be CXIMAGE_FORMAT_TIF or CXIMAGE_FORMAT_GIF. * \return true if everything is ok */ bool CxImage::Encode(CxFile * hFile, CxImage ** pImages, int pagecount, DWORD imagetype) { #if CXIMAGE_SUPPORT_TIF if (imagetype==CXIMAGE_FORMAT_TIF){ CxImageTIF newima; newima.Ghost(this); if (newima.Encode(hFile,pImages,pagecount)){ return true; } else { strcpy(info.szLastError,newima.GetLastError()); return false; } } #endif #if CXIMAGE_SUPPORT_GIF if (imagetype==CXIMAGE_FORMAT_GIF){ CxImageGIF newima; newima.Ghost(this); if (newima.Encode(hFile,pImages,pagecount)){ return true; } else { strcpy(info.szLastError,newima.GetLastError()); return false; } } #endif strcpy(info.szLastError,"Multipage Encode, Unsupported operation for this format"); return false; } //////////////////////////////////////////////////////////////////////////////// /** * exports the image into a RGBA buffer, Useful for OpenGL applications. * \param buffer: output memory buffer pointer. Must be NULL, * the function allocates and fill the memory, * the application must free the buffer, see also FreeMemory(). * \param size: output memory buffer size. * \return true if everything is ok */ bool CxImage::Encode2RGBA(BYTE * &buffer, long &size) { if (buffer!=NULL){ strcpy(info.szLastError,"the buffer must be empty"); return false; } CxMemFile file; file.Open(); if(Encode2RGBA(&file)){ buffer=file.GetBuffer(); size=file.Size(); return true; } return false; } //////////////////////////////////////////////////////////////////////////////// /** * exports the image into a RGBA buffer, Useful for OpenGL applications. * \param hFile: file handle (implemented using CxMemFile or CxIOFile). * \return true if everything is ok */ bool CxImage::Encode2RGBA(CxFile *hFile) { if (EncodeSafeCheck(hFile)) return false; for (DWORD y = 0; y<GetHeight(); y++) { for(DWORD x = 0; x<GetWidth(); x++) { RGBQUAD color = BlindGetPixelColor(x,y); hFile->PutC(color.rgbRed); hFile->PutC(color.rgbGreen); hFile->PutC(color.rgbBlue); hFile->PutC(color.rgbReserved); } } return true; } //////////////////////////////////////////////////////////////////////////////// #endif //CXIMAGE_SUPPORT_ENCODE //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// #if CXIMAGE_SUPPORT_DECODE //////////////////////////////////////////////////////////////////////////////// // For UNICODE support: char -> TCHAR /** * Reads from disk the image in a specific format. * - If decoding fails using the specified image format, * the function will try the automatic file format recognition. * * \param filename: file name * \param imagetype: file format, see ENUM_CXIMAGE_FORMATS * \return true if everything is ok */ bool CxImage::Load(const TCHAR * filename, DWORD imagetype) //bool CxImage::Load(const char * filename, DWORD imagetype) { /*FILE* hFile; //file handle to read the image if ((hFile=fopen(filename,"rb"))==NULL) return false; bool bOK = Decode(hFile,imagetype); fclose(hFile);*/ /* automatic file type recognition */ bool bOK = false; if ( imagetype > 0 && imagetype < CMAX_IMAGE_FORMATS ){ FILE* hFile; //file handle to read the image #ifdef WIN32 if ((hFile=_tfopen(filename,_T("rb")))==NULL) return false; // For UNICODE support #else if ((hFile=fopen(filename,"rb"))==NULL) return false; #endif bOK = Decode(hFile,imagetype); fclose(hFile); if (bOK) return bOK; } char szError[256]; strcpy(szError,info.szLastError); //save the first error // if failed, try automatic recognition of the file... FILE* hFile; #ifdef WIN32 if ((hFile=_tfopen(filename,_T("rb")))==NULL) return false; // For UNICODE support #else if ((hFile=fopen(filename,"rb"))==NULL) return false; #endif bOK = Decode(hFile,CXIMAGE_FORMAT_UNKNOWN); fclose(hFile); if (!bOK && imagetype > 0) strcpy(info.szLastError,szError); //restore the first error return bOK; } //////////////////////////////////////////////////////////////////////////////// #ifdef WIN32 //bool CxImage::Load(LPCWSTR filename, DWORD imagetype) //{ // /*FILE* hFile; //file handle to read the image // if ((hFile=_wfopen(filename, L"rb"))==NULL) return false; // bool bOK = Decode(hFile,imagetype); // fclose(hFile);*/ // // /* automatic file type recognition */ // bool bOK = false; // if ( imagetype > 0 && imagetype < CMAX_IMAGE_FORMATS ){ // FILE* hFile; //file handle to read the image // if ((hFile=_wfopen(filename,L"rb"))==NULL) return false; // bOK = Decode(hFile,imagetype); // fclose(hFile); // if (bOK) return bOK; // } // // char szError[256]; // strcpy(szError,info.szLastError); //save the first error // // // if failed, try automatic recognition of the file... // FILE* hFile; //file handle to read the image // if ((hFile=_wfopen(filename,L"rb"))==NULL) return false; // bOK = Decode(hFile,CXIMAGE_FORMAT_UNKNOWN); // fclose(hFile); // // if (!bOK && imagetype > 0) strcpy(info.szLastError,szError); //restore the first error // // return bOK; //} //////////////////////////////////////////////////////////////////////////////// /** * Loads an image from the application resources. * \param hRes: the resource handle returned by FindResource(). * \param imagetype: file format, see ENUM_CXIMAGE_FORMATS. * \param hModule: NULL for internal resource, or external application/DLL hinstance returned by LoadLibray. * \return true if everything is ok */ bool CxImage::LoadResource(HRSRC hRes, DWORD imagetype, HMODULE hModule) { DWORD rsize=SizeofResource(hModule,hRes); HGLOBAL hMem=::LoadResource(hModule,hRes); if (hMem){ char* lpVoid=(char*)LockResource(hMem); if (lpVoid){ // FILE* fTmp=tmpfile(); doesn't work with network /*char tmpPath[MAX_PATH] = {0}; char tmpFile[MAX_PATH] = {0}; GetTempPath(MAX_PATH,tmpPath); GetTempFileName(tmpPath,"IMG",0,tmpFile); FILE* fTmp=fopen(tmpFile,"w+b"); if (fTmp){ fwrite(lpVoid,rsize,1,fTmp); fseek(fTmp,0,SEEK_SET); bool bOK = Decode(fTmp,imagetype); fclose(fTmp); DeleteFile(tmpFile); return bOK; }*/ CxMemFile fTmp((BYTE*)lpVoid,rsize); return Decode(&fTmp,imagetype); } } else strcpy(info.szLastError,"Unable to load resource!"); return false; } #endif //WIN32 //////////////////////////////////////////////////////////////////////////////// /** * Constructor from file name, see Load() * \param filename: file name * \param imagetype: file format, see ENUM_CXIMAGE_FORMATS */ // // > filename: file name // > imagetype: specify the image format (CXIMAGE_FORMAT_BMP,...) // For UNICODE support: char -> TCHAR CxImage::CxImage(const TCHAR * filename, DWORD imagetype) //CxImage::CxImage(const char * filename, DWORD imagetype) { Startup(imagetype); Load(filename,imagetype); } //////////////////////////////////////////////////////////////////////////////// /** * Constructor from file handle, see Decode() * \param stream: file handle, with read access. * \param imagetype: file format, see ENUM_CXIMAGE_FORMATS */ CxImage::CxImage(FILE * stream, DWORD imagetype) { Startup(imagetype); Decode(stream,imagetype); } //////////////////////////////////////////////////////////////////////////////// /** * Constructor from CxFile object, see Decode() * \param stream: file handle (implemented using CxMemFile or CxIOFile), with read access. * \param imagetype: file format, see ENUM_CXIMAGE_FORMATS */ CxImage::CxImage(CxFile * stream, DWORD imagetype) { Startup(imagetype); Decode(stream,imagetype); } //////////////////////////////////////////////////////////////////////////////// /** * Constructor from memory buffer, see Decode() * \param buffer: memory buffer * \param size: size of buffer * \param imagetype: file format, see ENUM_CXIMAGE_FORMATS */ CxImage::CxImage(BYTE * buffer, DWORD size, DWORD imagetype) { Startup(imagetype); CxMemFile stream(buffer,size); Decode(&stream,imagetype); } //////////////////////////////////////////////////////////////////////////////// /** * Loads an image from memory buffer * \param buffer: memory buffer * \param size: size of buffer * \param imagetype: file format, see ENUM_CXIMAGE_FORMATS * \return true if everything is ok */ bool CxImage::Decode(BYTE * buffer, DWORD size, DWORD imagetype) { CxMemFile file(buffer,size); return Decode(&file,imagetype); } //////////////////////////////////////////////////////////////////////////////// /** * Loads an image from file handle. * \param hFile: file handle, with read access. * \param imagetype: file format, see ENUM_CXIMAGE_FORMATS * \return true if everything is ok */ bool CxImage::Decode(FILE *hFile, DWORD imagetype) { CxIOFile file(hFile); return Decode(&file,imagetype); } //////////////////////////////////////////////////////////////////////////////// /** * Loads an image from CxFile object * \param hFile: file handle (implemented using CxMemFile or CxIOFile), with read access. * \param imagetype: file format, see ENUM_CXIMAGE_FORMATS * \return true if everything is ok * \sa ENUM_CXIMAGE_FORMATS */ bool CxImage::Decode(CxFile *hFile, DWORD imagetype) { if (imagetype==CXIMAGE_FORMAT_UNKNOWN){ DWORD pos = hFile->Tell(); #if CXIMAGE_SUPPORT_BMP { CxImageBMP newima; newima.CopyInfo(*this); if (newima.Decode(hFile)) { Transfer(newima); return true; } else hFile->Seek(pos,SEEK_SET); } #endif #if CXIMAGE_SUPPORT_JPG { CxImageJPG newima; newima.CopyInfo(*this); if (newima.Decode(hFile)) { Transfer(newima); return true; } else hFile->Seek(pos,SEEK_SET); } #endif #if CXIMAGE_SUPPORT_ICO { CxImageICO newima; newima.CopyInfo(*this); if (newima.Decode(hFile)) { Transfer(newima); return true; } else hFile->Seek(pos,SEEK_SET); } #endif #if CXIMAGE_SUPPORT_GIF { CxImageGIF newima; newima.CopyInfo(*this); if (newima.Decode(hFile)) { Transfer(newima); return true; } else hFile->Seek(pos,SEEK_SET); } #endif #if CXIMAGE_SUPPORT_PNG { CxImagePNG newima; newima.CopyInfo(*this); if (newima.Decode(hFile)) { Transfer(newima); return true; } else hFile->Seek(pos,SEEK_SET); } #endif #if CXIMAGE_SUPPORT_TIF { CxImageTIF newima; newima.CopyInfo(*this); if (newima.Decode(hFile)) { Transfer(newima); return true; } else hFile->Seek(pos,SEEK_SET); } #endif #if CXIMAGE_SUPPORT_MNG { CxImageMNG newima; newima.CopyInfo(*this); if (newima.Decode(hFile)) { Transfer(newima); return true; } else hFile->Seek(pos,SEEK_SET); } #endif #if CXIMAGE_SUPPORT_TGA { CxImageTGA newima; newima.CopyInfo(*this); if (newima.Decode(hFile)) { Transfer(newima); return true; } else hFile->Seek(pos,SEEK_SET); } #endif #if CXIMAGE_SUPPORT_PCX { CxImagePCX newima; newima.CopyInfo(*this); if (newima.Decode(hFile)) { Transfer(newima); return true; } else hFile->Seek(pos,SEEK_SET); } #endif #if CXIMAGE_SUPPORT_WBMP { CxImageWBMP newima; newima.CopyInfo(*this); if (newima.Decode(hFile)) { Transfer(newima); return true; } else hFile->Seek(pos,SEEK_SET); } #endif #if CXIMAGE_SUPPORT_WMF && CXIMAGE_SUPPORT_WINDOWS { CxImageWMF newima; newima.CopyInfo(*this); if (newima.Decode(hFile)) { Transfer(newima); return true; } else hFile->Seek(pos,SEEK_SET); } #endif #if CXIMAGE_SUPPORT_J2K { CxImageJ2K newima; newima.CopyInfo(*this); if (newima.Decode(hFile)) { Transfer(newima); return true; } else hFile->Seek(pos,SEEK_SET); } #endif #if CXIMAGE_SUPPORT_JBG { CxImageJBG newima; newima.CopyInfo(*this); if (newima.Decode(hFile)) { Transfer(newima); return true; } else hFile->Seek(pos,SEEK_SET); } #endif #if CXIMAGE_SUPPORT_JASPER { CxImageJAS newima; newima.CopyInfo(*this); if (newima.Decode(hFile)) { Transfer(newima); return true; } else hFile->Seek(pos,SEEK_SET); } #endif } #if CXIMAGE_SUPPORT_BMP if (imagetype==CXIMAGE_FORMAT_BMP){ CxImageBMP newima; newima.CopyInfo(*this); if (newima.Decode(hFile)){ Transfer(newima); return true; } else { strcpy(info.szLastError,newima.GetLastError()); return false; } } #endif #if CXIMAGE_SUPPORT_JPG if (imagetype==CXIMAGE_FORMAT_JPG){ CxImageJPG newima; newima.CopyInfo(*this); // <ignacio> if (newima.Decode(hFile)){ Transfer(newima); return true; } else { strcpy(info.szLastError,newima.GetLastError()); return false; } } #endif #if CXIMAGE_SUPPORT_ICO if (imagetype==CXIMAGE_FORMAT_ICO){ CxImageICO newima; newima.CopyInfo(*this); if (newima.Decode(hFile)){ Transfer(newima); return true; } else { info.nNumFrames = newima.info.nNumFrames; strcpy(info.szLastError,newima.GetLastError()); return false; } } #endif #if CXIMAGE_SUPPORT_GIF if (imagetype==CXIMAGE_FORMAT_GIF){ CxImageGIF newima; newima.CopyInfo(*this); if (newima.Decode(hFile)){ Transfer(newima); return true; } else { info.nNumFrames = newima.info.nNumFrames; strcpy(info.szLastError,newima.GetLastError()); return false; } } #endif #if CXIMAGE_SUPPORT_PNG if (imagetype==CXIMAGE_FORMAT_PNG){ CxImagePNG newima; newima.CopyInfo(*this); if (newima.Decode(hFile)){ Transfer(newima); return true; } else { strcpy(info.szLastError,newima.GetLastError()); return false; } } #endif #if CXIMAGE_SUPPORT_TIF if (imagetype==CXIMAGE_FORMAT_TIF){ CxImageTIF newima; newima.CopyInfo(*this); if (newima.Decode(hFile)){ Transfer(newima); return true; } else { info.nNumFrames = newima.info.nNumFrames; strcpy(info.szLastError,newima.GetLastError()); return false; } } #endif #if CXIMAGE_SUPPORT_MNG if (imagetype==CXIMAGE_FORMAT_MNG){ CxImageMNG newima; newima.CopyInfo(*this); if (newima.Decode(hFile)){ Transfer(newima); return true; } else { info.nNumFrames = newima.info.nNumFrames; strcpy(info.szLastError,newima.GetLastError()); return false; } } #endif #if CXIMAGE_SUPPORT_TGA if (imagetype==CXIMAGE_FORMAT_TGA){ CxImageTGA newima; newima.CopyInfo(*this); if (newima.Decode(hFile)){ Transfer(newima); return true; } else { strcpy(info.szLastError,newima.GetLastError()); return false; } } #endif #if CXIMAGE_SUPPORT_PCX if (imagetype==CXIMAGE_FORMAT_PCX){ CxImagePCX newima; newima.CopyInfo(*this); if (newima.Decode(hFile)){ Transfer(newima); return true; } else { strcpy(info.szLastError,newima.GetLastError()); return false; } } #endif #if CXIMAGE_SUPPORT_WBMP if (imagetype==CXIMAGE_FORMAT_WBMP){ CxImageWBMP newima; newima.CopyInfo(*this); if (newima.Decode(hFile)){ Transfer(newima); return true; } else { strcpy(info.szLastError,newima.GetLastError()); return false; } } #endif #if CXIMAGE_SUPPORT_WMF && CXIMAGE_SUPPORT_WINDOWS // vho - WMF support if (imagetype == CXIMAGE_FORMAT_WMF){ CxImageWMF newima; newima.CopyInfo(*this); if (newima.Decode(hFile)){ Transfer(newima); return true; } else { strcpy(info.szLastError,newima.GetLastError()); return false; } } #endif #if CXIMAGE_SUPPORT_J2K if (imagetype==CXIMAGE_FORMAT_J2K){ CxImageJ2K newima; newima.CopyInfo(*this); if (newima.Decode(hFile)){ Transfer(newima); return true; } else { strcpy(info.szLastError,newima.GetLastError()); return false; } } #endif #if CXIMAGE_SUPPORT_JBG if (imagetype==CXIMAGE_FORMAT_JBG){ CxImageJBG newima; newima.CopyInfo(*this); if (newima.Decode(hFile)){ Transfer(newima); return true; } else { strcpy(info.szLastError,newima.GetLastError()); return false; } } #endif #if CXIMAGE_SUPPORT_JASPER if ( #if CXIMAGE_SUPPORT_JP2 imagetype==CXIMAGE_FORMAT_JP2 || #endif #if CXIMAGE_SUPPORT_JPC imagetype==CXIMAGE_FORMAT_JPC || #endif #if CXIMAGE_SUPPORT_PGX imagetype==CXIMAGE_FORMAT_PGX || #endif #if CXIMAGE_SUPPORT_PNM imagetype==CXIMAGE_FORMAT_PNM || #endif #if CXIMAGE_SUPPORT_RAS imagetype==CXIMAGE_FORMAT_RAS || #endif false ){ CxImageJAS newima; newima.CopyInfo(*this); if (newima.Decode(hFile,imagetype)){ Transfer(newima); return true; } else { strcpy(info.szLastError,newima.GetLastError()); return false; } } #endif strcpy(info.szLastError,"Decode: Unknown or wrong format"); return false; } //////////////////////////////////////////////////////////////////////////////// #endif //CXIMAGE_SUPPORT_DECODE ////////////////////////////////////////////////////////////////////////////////
lgpl-3.0
sysalexis/kbengine
kbe/src/lib/python/Modules/_ctypes/libffi/testsuite/libffi.call/cls_ushort.c
812
1096
/* Area: closure_call Purpose: Check return value ushort. Limitations: none. PR: none. Originator: <andreast@gcc.gnu.org> 20030828 */ /* { dg-do run } */ #include "ffitest.h" static void cls_ret_ushort_fn(ffi_cif* cif __UNUSED__, void* resp, void** args, void* userdata __UNUSED__) { *(ffi_arg*)resp = *(unsigned short *)args[0]; printf("%d: %d\n",*(unsigned short *)args[0], (int)*(ffi_arg *)(resp)); } typedef unsigned short (*cls_ret_ushort)(unsigned short); int main (void) { ffi_cif cif; void *code; ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); ffi_type * cl_arg_types[2]; unsigned short res; cl_arg_types[0] = &ffi_type_ushort; cl_arg_types[1] = NULL; /* Initialize the cif */ CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1, &ffi_type_ushort, cl_arg_types) == FFI_OK); CHECK(ffi_prep_closure_loc(pcl, &cif, cls_ret_ushort_fn, NULL, code) == FFI_OK); res = (*((cls_ret_ushort)code))(65535); /* { dg-output "65535: 65535" } */ printf("res: %d\n",res); /* { dg-output "\nres: 65535" } */ exit(0); }
lgpl-3.0
bottompawn/kbengine
kbe/src/lib/dependencies/apr/locks/beos/thread_mutex.c
75
4412
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*Read/Write locking implementation based on the MultiLock code from * Stephen Beaulieu <hippo@be.com> */ #include "apr_arch_thread_mutex.h" #include "apr_strings.h" #include "apr_portable.h" static apr_status_t _thread_mutex_cleanup(void * data) { apr_thread_mutex_t *lock = (apr_thread_mutex_t*)data; if (lock->LockCount != 0) { /* we're still locked... */ while (atomic_add(&lock->LockCount , -1) > 1){ /* OK we had more than one person waiting on the lock so * the sem is also locked. Release it until we have no more * locks left. */ release_sem (lock->Lock); } } delete_sem(lock->Lock); return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_thread_mutex_create(apr_thread_mutex_t **mutex, unsigned int flags, apr_pool_t *pool) { apr_thread_mutex_t *new_m; apr_status_t stat = APR_SUCCESS; new_m = (apr_thread_mutex_t *)apr_pcalloc(pool, sizeof(apr_thread_mutex_t)); if (new_m == NULL){ return APR_ENOMEM; } if ((stat = create_sem(0, "APR_Lock")) < B_NO_ERROR) { _thread_mutex_cleanup(new_m); return stat; } new_m->LockCount = 0; new_m->Lock = stat; new_m->pool = pool; /* Optimal default is APR_THREAD_MUTEX_UNNESTED, * no additional checks required for either flag. */ new_m->nested = flags & APR_THREAD_MUTEX_NESTED; apr_pool_cleanup_register(new_m->pool, (void *)new_m, _thread_mutex_cleanup, apr_pool_cleanup_null); (*mutex) = new_m; return APR_SUCCESS; } #if APR_HAS_CREATE_LOCKS_NP APR_DECLARE(apr_status_t) apr_thread_mutex_create_np(apr_thread_mutex_t **mutex, const char *fname, apr_lockmech_e_np mech, apr_pool_t *pool) { return APR_ENOTIMPL; } #endif APR_DECLARE(apr_status_t) apr_thread_mutex_lock(apr_thread_mutex_t *mutex) { int32 stat; thread_id me = find_thread(NULL); if (mutex->nested && mutex->owner == me) { mutex->owner_ref++; return APR_SUCCESS; } if (atomic_add(&mutex->LockCount, 1) > 0) { if ((stat = acquire_sem(mutex->Lock)) < B_NO_ERROR) { /* Oh dear, acquire_sem failed!! */ atomic_add(&mutex->LockCount, -1); return stat; } } mutex->owner = me; mutex->owner_ref = 1; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_thread_mutex_trylock(apr_thread_mutex_t *mutex) { return APR_ENOTIMPL; } APR_DECLARE(apr_status_t) apr_thread_mutex_unlock(apr_thread_mutex_t *mutex) { int32 stat; if (mutex->nested && mutex->owner == find_thread(NULL)) { mutex->owner_ref--; if (mutex->owner_ref > 0) return APR_SUCCESS; } if (atomic_add(&mutex->LockCount, -1) > 1) { if ((stat = release_sem(mutex->Lock)) < B_NO_ERROR) { atomic_add(&mutex->LockCount, 1); return stat; } } mutex->owner = -1; mutex->owner_ref = 0; return APR_SUCCESS; } APR_DECLARE(apr_status_t) apr_thread_mutex_destroy(apr_thread_mutex_t *mutex) { apr_status_t stat; if ((stat = _thread_mutex_cleanup(mutex)) == APR_SUCCESS) { apr_pool_cleanup_kill(mutex->pool, mutex, _thread_mutex_cleanup); return APR_SUCCESS; } return stat; } APR_POOL_IMPLEMENT_ACCESSOR(thread_mutex)
lgpl-3.0
tsaikd/MagicKD
tags/1.0.3.2/CxImage/jpeg/jcmaster.c
110
20479
/* * jcmaster.c * * Copyright (C) 1991-1997, Thomas G. Lane. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains master control logic for the JPEG compressor. * These routines are concerned with parameter validation, initial setup, * and inter-pass control (determining the number of passes and the work * to be done in each pass). */ #define JPEG_INTERNALS #include "jinclude.h" #include "jpeglib.h" /* Private state */ typedef enum { main_pass, /* input data, also do first output step */ huff_opt_pass, /* Huffman code optimization pass */ output_pass /* data output pass */ } c_pass_type; typedef struct { struct jpeg_comp_master pub; /* public fields */ c_pass_type pass_type; /* the type of the current pass */ int pass_number; /* # of passes completed */ int total_passes; /* total # of passes needed */ int scan_number; /* current index in scan_info[] */ } my_comp_master; typedef my_comp_master * my_master_ptr; /* * Support routines that do various essential calculations. */ LOCAL(void) initial_setup (j_compress_ptr cinfo) /* Do computations that are needed before master selection phase */ { int ci; jpeg_component_info *compptr; long samplesperrow; JDIMENSION jd_samplesperrow; /* Sanity check on image dimensions */ if (cinfo->image_height <= 0 || cinfo->image_width <= 0 || cinfo->num_components <= 0 || cinfo->input_components <= 0) ERREXIT(cinfo, JERR_EMPTY_IMAGE); /* Make sure image isn't bigger than I can handle */ if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION || (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION) ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION); /* Width of an input scanline must be representable as JDIMENSION. */ samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components; jd_samplesperrow = (JDIMENSION) samplesperrow; if ((long) jd_samplesperrow != samplesperrow) ERREXIT(cinfo, JERR_WIDTH_OVERFLOW); /* For now, precision must match compiled-in value... */ if (cinfo->data_precision != BITS_IN_JSAMPLE) ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision); /* Check that number of components won't exceed internal array sizes */ if (cinfo->num_components > MAX_COMPONENTS) ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components, MAX_COMPONENTS); /* Compute maximum sampling factors; check factor validity */ cinfo->max_h_samp_factor = 1; cinfo->max_v_samp_factor = 1; for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; ci++, compptr++) { if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR || compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR) ERREXIT(cinfo, JERR_BAD_SAMPLING); cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor, compptr->h_samp_factor); cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor, compptr->v_samp_factor); } /* Compute dimensions of components */ for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; ci++, compptr++) { /* Fill in the correct component_index value; don't rely on application */ compptr->component_index = ci; /* For compression, we never do DCT scaling. */ compptr->DCT_scaled_size = DCTSIZE; /* Size in DCT blocks */ compptr->width_in_blocks = (JDIMENSION) jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor, (long) (cinfo->max_h_samp_factor * DCTSIZE)); compptr->height_in_blocks = (JDIMENSION) jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor, (long) (cinfo->max_v_samp_factor * DCTSIZE)); /* Size in samples */ compptr->downsampled_width = (JDIMENSION) jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor, (long) cinfo->max_h_samp_factor); compptr->downsampled_height = (JDIMENSION) jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor, (long) cinfo->max_v_samp_factor); /* Mark component needed (this flag isn't actually used for compression) */ compptr->component_needed = TRUE; } /* Compute number of fully interleaved MCU rows (number of times that * main controller will call coefficient controller). */ cinfo->total_iMCU_rows = (JDIMENSION) jdiv_round_up((long) cinfo->image_height, (long) (cinfo->max_v_samp_factor*DCTSIZE)); } #ifdef C_MULTISCAN_FILES_SUPPORTED LOCAL(void) validate_script (j_compress_ptr cinfo) /* Verify that the scan script in cinfo->scan_info[] is valid; also * determine whether it uses progressive JPEG, and set cinfo->progressive_mode. */ { const jpeg_scan_info * scanptr; int scanno, ncomps, ci, coefi, thisi; int Ss, Se, Ah, Al; boolean component_sent[MAX_COMPONENTS]; #ifdef C_PROGRESSIVE_SUPPORTED int * last_bitpos_ptr; int last_bitpos[MAX_COMPONENTS][DCTSIZE2]; /* -1 until that coefficient has been seen; then last Al for it */ #endif if (cinfo->num_scans <= 0) ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0); /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1; * for progressive JPEG, no scan can have this. */ scanptr = cinfo->scan_info; if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) { #ifdef C_PROGRESSIVE_SUPPORTED cinfo->progressive_mode = TRUE; last_bitpos_ptr = & last_bitpos[0][0]; for (ci = 0; ci < cinfo->num_components; ci++) for (coefi = 0; coefi < DCTSIZE2; coefi++) *last_bitpos_ptr++ = -1; #else ERREXIT(cinfo, JERR_NOT_COMPILED); #endif } else { cinfo->progressive_mode = FALSE; for (ci = 0; ci < cinfo->num_components; ci++) component_sent[ci] = FALSE; } for (scanno = 1; scanno <= cinfo->num_scans; scanptr++, scanno++) { /* Validate component indexes */ ncomps = scanptr->comps_in_scan; if (ncomps <= 0 || ncomps > MAX_COMPS_IN_SCAN) ERREXIT2(cinfo, JERR_COMPONENT_COUNT, ncomps, MAX_COMPS_IN_SCAN); for (ci = 0; ci < ncomps; ci++) { thisi = scanptr->component_index[ci]; if (thisi < 0 || thisi >= cinfo->num_components) ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno); /* Components must appear in SOF order within each scan */ if (ci > 0 && thisi <= scanptr->component_index[ci-1]) ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno); } /* Validate progression parameters */ Ss = scanptr->Ss; Se = scanptr->Se; Ah = scanptr->Ah; Al = scanptr->Al; if (cinfo->progressive_mode) { #ifdef C_PROGRESSIVE_SUPPORTED /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that * seems wrong: the upper bound ought to depend on data precision. * Perhaps they really meant 0..N+1 for N-bit precision. * Here we allow 0..10 for 8-bit data; Al larger than 10 results in * out-of-range reconstructed DC values during the first DC scan, * which might cause problems for some decoders. */ #if BITS_IN_JSAMPLE == 8 #define MAX_AH_AL 10 #else #define MAX_AH_AL 13 #endif if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 || Ah < 0 || Ah > MAX_AH_AL || Al < 0 || Al > MAX_AH_AL) ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno); if (Ss == 0) { if (Se != 0) /* DC and AC together not OK */ ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno); } else { if (ncomps != 1) /* AC scans must be for only one component */ ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno); } for (ci = 0; ci < ncomps; ci++) { last_bitpos_ptr = & last_bitpos[scanptr->component_index[ci]][0]; if (Ss != 0 && last_bitpos_ptr[0] < 0) /* AC without prior DC scan */ ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno); for (coefi = Ss; coefi <= Se; coefi++) { if (last_bitpos_ptr[coefi] < 0) { /* first scan of this coefficient */ if (Ah != 0) ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno); } else { /* not first scan */ if (Ah != last_bitpos_ptr[coefi] || Al != Ah-1) ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno); } last_bitpos_ptr[coefi] = Al; } } #endif } else { /* For sequential JPEG, all progression parameters must be these: */ if (Ss != 0 || Se != DCTSIZE2-1 || Ah != 0 || Al != 0) ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno); /* Make sure components are not sent twice */ for (ci = 0; ci < ncomps; ci++) { thisi = scanptr->component_index[ci]; if (component_sent[thisi]) ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno); component_sent[thisi] = TRUE; } } } /* Now verify that everything got sent. */ if (cinfo->progressive_mode) { #ifdef C_PROGRESSIVE_SUPPORTED /* For progressive mode, we only check that at least some DC data * got sent for each component; the spec does not require that all bits * of all coefficients be transmitted. Would it be wiser to enforce * transmission of all coefficient bits?? */ for (ci = 0; ci < cinfo->num_components; ci++) { if (last_bitpos[ci][0] < 0) ERREXIT(cinfo, JERR_MISSING_DATA); } #endif } else { for (ci = 0; ci < cinfo->num_components; ci++) { if (! component_sent[ci]) ERREXIT(cinfo, JERR_MISSING_DATA); } } } #endif /* C_MULTISCAN_FILES_SUPPORTED */ LOCAL(void) select_scan_parameters (j_compress_ptr cinfo) /* Set up the scan parameters for the current scan */ { int ci; #ifdef C_MULTISCAN_FILES_SUPPORTED if (cinfo->scan_info != NULL) { /* Prepare for current scan --- the script is already validated */ my_master_ptr master = (my_master_ptr) cinfo->master; const jpeg_scan_info * scanptr = cinfo->scan_info + master->scan_number; cinfo->comps_in_scan = scanptr->comps_in_scan; for (ci = 0; ci < scanptr->comps_in_scan; ci++) { cinfo->cur_comp_info[ci] = &cinfo->comp_info[scanptr->component_index[ci]]; } cinfo->Ss = scanptr->Ss; cinfo->Se = scanptr->Se; cinfo->Ah = scanptr->Ah; cinfo->Al = scanptr->Al; } else #endif { /* Prepare for single sequential-JPEG scan containing all components */ if (cinfo->num_components > MAX_COMPS_IN_SCAN) ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components, MAX_COMPS_IN_SCAN); cinfo->comps_in_scan = cinfo->num_components; for (ci = 0; ci < cinfo->num_components; ci++) { cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci]; } cinfo->Ss = 0; cinfo->Se = DCTSIZE2-1; cinfo->Ah = 0; cinfo->Al = 0; } } LOCAL(void) per_scan_setup (j_compress_ptr cinfo) /* Do computations that are needed before processing a JPEG scan */ /* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */ { int ci, mcublks, tmp; jpeg_component_info *compptr; if (cinfo->comps_in_scan == 1) { /* Noninterleaved (single-component) scan */ compptr = cinfo->cur_comp_info[0]; /* Overall image size in MCUs */ cinfo->MCUs_per_row = compptr->width_in_blocks; cinfo->MCU_rows_in_scan = compptr->height_in_blocks; /* For noninterleaved scan, always one block per MCU */ compptr->MCU_width = 1; compptr->MCU_height = 1; compptr->MCU_blocks = 1; compptr->MCU_sample_width = DCTSIZE; compptr->last_col_width = 1; /* For noninterleaved scans, it is convenient to define last_row_height * as the number of block rows present in the last iMCU row. */ tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor); if (tmp == 0) tmp = compptr->v_samp_factor; compptr->last_row_height = tmp; /* Prepare array describing MCU composition */ cinfo->blocks_in_MCU = 1; cinfo->MCU_membership[0] = 0; } else { /* Interleaved (multi-component) scan */ if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN) ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan, MAX_COMPS_IN_SCAN); /* Overall image size in MCUs */ cinfo->MCUs_per_row = (JDIMENSION) jdiv_round_up((long) cinfo->image_width, (long) (cinfo->max_h_samp_factor*DCTSIZE)); cinfo->MCU_rows_in_scan = (JDIMENSION) jdiv_round_up((long) cinfo->image_height, (long) (cinfo->max_v_samp_factor*DCTSIZE)); cinfo->blocks_in_MCU = 0; for (ci = 0; ci < cinfo->comps_in_scan; ci++) { compptr = cinfo->cur_comp_info[ci]; /* Sampling factors give # of blocks of component in each MCU */ compptr->MCU_width = compptr->h_samp_factor; compptr->MCU_height = compptr->v_samp_factor; compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height; compptr->MCU_sample_width = compptr->MCU_width * DCTSIZE; /* Figure number of non-dummy blocks in last MCU column & row */ tmp = (int) (compptr->width_in_blocks % compptr->MCU_width); if (tmp == 0) tmp = compptr->MCU_width; compptr->last_col_width = tmp; tmp = (int) (compptr->height_in_blocks % compptr->MCU_height); if (tmp == 0) tmp = compptr->MCU_height; compptr->last_row_height = tmp; /* Prepare array describing MCU composition */ mcublks = compptr->MCU_blocks; if (cinfo->blocks_in_MCU + mcublks > C_MAX_BLOCKS_IN_MCU) ERREXIT(cinfo, JERR_BAD_MCU_SIZE); while (mcublks-- > 0) { cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci; } } } /* Convert restart specified in rows to actual MCU count. */ /* Note that count must fit in 16 bits, so we provide limiting. */ if (cinfo->restart_in_rows > 0) { long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row; cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L); } } /* * Per-pass setup. * This is called at the beginning of each pass. We determine which modules * will be active during this pass and give them appropriate start_pass calls. * We also set is_last_pass to indicate whether any more passes will be * required. */ METHODDEF(void) prepare_for_pass (j_compress_ptr cinfo) { my_master_ptr master = (my_master_ptr) cinfo->master; switch (master->pass_type) { case main_pass: /* Initial pass: will collect input data, and do either Huffman * optimization or data output for the first scan. */ select_scan_parameters(cinfo); per_scan_setup(cinfo); if (! cinfo->raw_data_in) { (*cinfo->cconvert->start_pass) (cinfo); (*cinfo->downsample->start_pass) (cinfo); (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU); } (*cinfo->fdct->start_pass) (cinfo); (*cinfo->entropy->start_pass) (cinfo, cinfo->optimize_coding); (*cinfo->coef->start_pass) (cinfo, (master->total_passes > 1 ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU)); (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU); if (cinfo->optimize_coding) { /* No immediate data output; postpone writing frame/scan headers */ master->pub.call_pass_startup = FALSE; } else { /* Will write frame/scan headers at first jpeg_write_scanlines call */ master->pub.call_pass_startup = TRUE; } break; #ifdef ENTROPY_OPT_SUPPORTED case huff_opt_pass: /* Do Huffman optimization for a scan after the first one. */ select_scan_parameters(cinfo); per_scan_setup(cinfo); if (cinfo->Ss != 0 || cinfo->Ah == 0 || cinfo->arith_code) { (*cinfo->entropy->start_pass) (cinfo, TRUE); (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST); master->pub.call_pass_startup = FALSE; break; } /* Special case: Huffman DC refinement scans need no Huffman table * and therefore we can skip the optimization pass for them. */ master->pass_type = output_pass; master->pass_number++; /*FALLTHROUGH*/ #endif case output_pass: /* Do a data-output pass. */ /* We need not repeat per-scan setup if prior optimization pass did it. */ if (! cinfo->optimize_coding) { select_scan_parameters(cinfo); per_scan_setup(cinfo); } (*cinfo->entropy->start_pass) (cinfo, FALSE); (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST); /* We emit frame/scan headers now */ if (master->scan_number == 0) (*cinfo->marker->write_frame_header) (cinfo); (*cinfo->marker->write_scan_header) (cinfo); master->pub.call_pass_startup = FALSE; break; default: ERREXIT(cinfo, JERR_NOT_COMPILED); } master->pub.is_last_pass = (master->pass_number == master->total_passes-1); /* Set up progress monitor's pass info if present */ if (cinfo->progress != NULL) { cinfo->progress->completed_passes = master->pass_number; cinfo->progress->total_passes = master->total_passes; } } /* * Special start-of-pass hook. * This is called by jpeg_write_scanlines if call_pass_startup is TRUE. * In single-pass processing, we need this hook because we don't want to * write frame/scan headers during jpeg_start_compress; we want to let the * application write COM markers etc. between jpeg_start_compress and the * jpeg_write_scanlines loop. * In multi-pass processing, this routine is not used. */ METHODDEF(void) pass_startup (j_compress_ptr cinfo) { cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */ (*cinfo->marker->write_frame_header) (cinfo); (*cinfo->marker->write_scan_header) (cinfo); } /* * Finish up at end of pass. */ METHODDEF(void) finish_pass_master (j_compress_ptr cinfo) { my_master_ptr master = (my_master_ptr) cinfo->master; /* The entropy coder always needs an end-of-pass call, * either to analyze statistics or to flush its output buffer. */ (*cinfo->entropy->finish_pass) (cinfo); /* Update state for next pass */ switch (master->pass_type) { case main_pass: /* next pass is either output of scan 0 (after optimization) * or output of scan 1 (if no optimization). */ master->pass_type = output_pass; if (! cinfo->optimize_coding) master->scan_number++; break; case huff_opt_pass: /* next pass is always output of current scan */ master->pass_type = output_pass; break; case output_pass: /* next pass is either optimization or output of next scan */ if (cinfo->optimize_coding) master->pass_type = huff_opt_pass; master->scan_number++; break; } master->pass_number++; } /* * Initialize master compression control. */ GLOBAL(void) jinit_c_master_control (j_compress_ptr cinfo, boolean transcode_only) { my_master_ptr master; master = (my_master_ptr) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(my_comp_master)); cinfo->master = (struct jpeg_comp_master *) master; master->pub.prepare_for_pass = prepare_for_pass; master->pub.pass_startup = pass_startup; master->pub.finish_pass = finish_pass_master; master->pub.is_last_pass = FALSE; /* Validate parameters, determine derived values */ initial_setup(cinfo); if (cinfo->scan_info != NULL) { #ifdef C_MULTISCAN_FILES_SUPPORTED validate_script(cinfo); #else ERREXIT(cinfo, JERR_NOT_COMPILED); #endif } else { cinfo->progressive_mode = FALSE; cinfo->num_scans = 1; } if (cinfo->progressive_mode) /* TEMPORARY HACK ??? */ cinfo->optimize_coding = TRUE; /* assume default tables no good for progressive mode */ /* Initialize my private state */ if (transcode_only) { /* no main pass in transcoding */ if (cinfo->optimize_coding) master->pass_type = huff_opt_pass; else master->pass_type = output_pass; } else { /* for normal compression, first pass is always this type: */ master->pass_type = main_pass; } master->scan_number = 0; master->pass_number = 0; if (cinfo->optimize_coding) master->total_passes = cinfo->num_scans * 2; else master->total_passes = cinfo->num_scans; }
lgpl-3.0
MITHyperloopTeam/software_core
software/externals/sam/CMSIS/CMSIS/DSP_Lib/Source/FilteringFunctions/arm_lms_norm_q15.c
225
11003
/* ---------------------------------------------------------------------- * Copyright (C) 2010 ARM Limited. All rights reserved. * * $Date: 15. July 2011 * $Revision: V1.0.10 * * Project: CMSIS DSP Library * Title: arm_lms_norm_q15.c * * Description: Q15 NLMS filter. * * Target Processor: Cortex-M4/Cortex-M3/Cortex-M0 * * Version 1.0.10 2011/7/15 * Big Endian support added and Merged M0 and M3/M4 Source code. * * Version 1.0.3 2010/11/29 * Re-organized the CMSIS folders and updated documentation. * * Version 1.0.2 2010/11/11 * Documentation updated. * * Version 1.0.1 2010/10/05 * Production release and review comments incorporated. * * Version 1.0.0 2010/09/20 * Production release and review comments incorporated * * Version 0.0.7 2010/06/10 * Misra-C changes done * -------------------------------------------------------------------- */ #include "arm_math.h" /** * @ingroup groupFilters */ /** * @addtogroup LMS_NORM * @{ */ /** * @brief Processing function for Q15 normalized LMS filter. * @param[in] *S points to an instance of the Q15 normalized LMS filter structure. * @param[in] *pSrc points to the block of input data. * @param[in] *pRef points to the block of reference data. * @param[out] *pOut points to the block of output data. * @param[out] *pErr points to the block of error data. * @param[in] blockSize number of samples to process. * @return none. * * <b>Scaling and Overflow Behavior:</b> * \par * The function is implemented using a 64-bit internal accumulator. * Both coefficients and state variables are represented in 1.15 format and * multiplications yield a 2.30 result. The 2.30 intermediate results are * accumulated in a 64-bit accumulator in 34.30 format. * There is no risk of internal overflow with this approach and the full * precision of intermediate multiplications is preserved. After all additions * have been performed, the accumulator is truncated to 34.15 format by * discarding low 15 bits. Lastly, the accumulator is saturated to yield a * result in 1.15 format. * * \par * In this filter, filter coefficients are updated for each sample and the updation of filter cofficients are saturted. * */ void arm_lms_norm_q15( arm_lms_norm_instance_q15 * S, q15_t * pSrc, q15_t * pRef, q15_t * pOut, q15_t * pErr, uint32_t blockSize) { q15_t *pState = S->pState; /* State pointer */ q15_t *pCoeffs = S->pCoeffs; /* Coefficient pointer */ q15_t *pStateCurnt; /* Points to the current sample of the state */ q15_t *px, *pb; /* Temporary pointers for state and coefficient buffers */ q15_t mu = S->mu; /* Adaptive factor */ uint32_t numTaps = S->numTaps; /* Number of filter coefficients in the filter */ uint32_t tapCnt, blkCnt; /* Loop counters */ q31_t energy; /* Energy of the input */ q63_t acc; /* Accumulator */ q15_t e = 0, d = 0; /* error, reference data sample */ q15_t w = 0, in; /* weight factor and state */ q15_t x0; /* temporary variable to hold input sample */ uint32_t shift = (uint32_t) S->postShift + 1u; /* Shift to be applied to the output */ q15_t errorXmu, oneByEnergy; /* Temporary variables to store error and mu product and reciprocal of energy */ q15_t postShift; /* Post shift to be applied to weight after reciprocal calculation */ q31_t coef; /* Teporary variable for coefficient */ energy = S->energy; x0 = S->x0; /* S->pState points to buffer which contains previous frame (numTaps - 1) samples */ /* pStateCurnt points to the location where the new input data should be written */ pStateCurnt = &(S->pState[(numTaps - 1u)]); /* Loop over blockSize number of values */ blkCnt = blockSize; #ifndef ARM_MATH_CM0 /* Run the below code for Cortex-M4 and Cortex-M3 */ while(blkCnt > 0u) { /* Copy the new input sample into the state buffer */ *pStateCurnt++ = *pSrc; /* Initialize pState pointer */ px = pState; /* Initialize coeff pointer */ pb = (pCoeffs); /* Read the sample from input buffer */ in = *pSrc++; /* Update the energy calculation */ energy -= (((q31_t) x0 * (x0)) >> 15); energy += (((q31_t) in * (in)) >> 15); /* Set the accumulator to zero */ acc = 0; /* Loop unrolling. Process 4 taps at a time. */ tapCnt = numTaps >> 2; while(tapCnt > 0u) { /* Perform the multiply-accumulate */ acc = __SMLALD(*__SIMD32(px)++, (*__SIMD32(pb)++), acc); acc = __SMLALD(*__SIMD32(px)++, (*__SIMD32(pb)++), acc); /* Decrement the loop counter */ tapCnt--; } /* If the filter length is not a multiple of 4, compute the remaining filter taps */ tapCnt = numTaps % 0x4u; while(tapCnt > 0u) { /* Perform the multiply-accumulate */ acc += (((q31_t) * px++ * (*pb++))); /* Decrement the loop counter */ tapCnt--; } /* Converting the result to 1.15 format */ acc = __SSAT((acc >> (16u - shift)), 16u); /* Store the result from accumulator into the destination buffer. */ *pOut++ = (q15_t) acc; /* Compute and store error */ d = *pRef++; e = d - (q15_t) acc; *pErr++ = e; /* Calculation of 1/energy */ postShift = arm_recip_q15((q15_t) energy + DELTA_Q15, &oneByEnergy, S->recipTable); /* Calculation of e * mu value */ errorXmu = (q15_t) (((q31_t) e * mu) >> 15); /* Calculation of (e * mu) * (1/energy) value */ acc = (((q31_t) errorXmu * oneByEnergy) >> (15 - postShift)); /* Weighting factor for the normalized version */ w = (q15_t) __SSAT((q31_t) acc, 16); /* Initialize pState pointer */ px = pState; /* Initialize coeff pointer */ pb = (pCoeffs); /* Loop unrolling. Process 4 taps at a time. */ tapCnt = numTaps >> 2; /* Update filter coefficients */ while(tapCnt > 0u) { coef = *pb + (((q31_t) w * (*px++)) >> 15); *pb++ = (q15_t) __SSAT((coef), 16); coef = *pb + (((q31_t) w * (*px++)) >> 15); *pb++ = (q15_t) __SSAT((coef), 16); coef = *pb + (((q31_t) w * (*px++)) >> 15); *pb++ = (q15_t) __SSAT((coef), 16); coef = *pb + (((q31_t) w * (*px++)) >> 15); *pb++ = (q15_t) __SSAT((coef), 16); /* Decrement the loop counter */ tapCnt--; } /* If the filter length is not a multiple of 4, compute the remaining filter taps */ tapCnt = numTaps % 0x4u; while(tapCnt > 0u) { /* Perform the multiply-accumulate */ coef = *pb + (((q31_t) w * (*px++)) >> 15); *pb++ = (q15_t) __SSAT((coef), 16); /* Decrement the loop counter */ tapCnt--; } /* Read the sample from state buffer */ x0 = *pState; /* Advance state pointer by 1 for the next sample */ pState = pState + 1u; /* Decrement the loop counter */ blkCnt--; } /* Save energy and x0 values for the next frame */ S->energy = (q15_t) energy; S->x0 = x0; /* Processing is complete. Now copy the last numTaps - 1 samples to the satrt of the state buffer. This prepares the state buffer for the next function call. */ /* Points to the start of the pState buffer */ pStateCurnt = S->pState; /* Calculation of count for copying integer writes */ tapCnt = (numTaps - 1u) >> 2; while(tapCnt > 0u) { *__SIMD32(pStateCurnt)++ = *__SIMD32(pState)++; *__SIMD32(pStateCurnt)++ = *__SIMD32(pState)++; tapCnt--; } /* Calculation of count for remaining q15_t data */ tapCnt = (numTaps - 1u) % 0x4u; /* copy data */ while(tapCnt > 0u) { *pStateCurnt++ = *pState++; /* Decrement the loop counter */ tapCnt--; } #else /* Run the below code for Cortex-M0 */ while(blkCnt > 0u) { /* Copy the new input sample into the state buffer */ *pStateCurnt++ = *pSrc; /* Initialize pState pointer */ px = pState; /* Initialize pCoeffs pointer */ pb = pCoeffs; /* Read the sample from input buffer */ in = *pSrc++; /* Update the energy calculation */ energy -= (((q31_t) x0 * (x0)) >> 15); energy += (((q31_t) in * (in)) >> 15); /* Set the accumulator to zero */ acc = 0; /* Loop over numTaps number of values */ tapCnt = numTaps; while(tapCnt > 0u) { /* Perform the multiply-accumulate */ acc += (((q31_t) * px++ * (*pb++))); /* Decrement the loop counter */ tapCnt--; } /* Converting the result to 1.15 format */ acc = __SSAT((acc >> (16u - shift)), 16u); /* Store the result from accumulator into the destination buffer. */ *pOut++ = (q15_t) acc; /* Compute and store error */ d = *pRef++; e = d - (q15_t) acc; *pErr++ = e; /* Calculation of 1/energy */ postShift = arm_recip_q15((q15_t) energy + DELTA_Q15, &oneByEnergy, S->recipTable); /* Calculation of e * mu value */ errorXmu = (q15_t) (((q31_t) e * mu) >> 15); /* Calculation of (e * mu) * (1/energy) value */ acc = (((q31_t) errorXmu * oneByEnergy) >> (15 - postShift)); /* Weighting factor for the normalized version */ w = (q15_t) __SSAT((q31_t) acc, 16); /* Initialize pState pointer */ px = pState; /* Initialize coeff pointer */ pb = (pCoeffs); /* Loop over numTaps number of values */ tapCnt = numTaps; while(tapCnt > 0u) { /* Perform the multiply-accumulate */ coef = *pb + (((q31_t) w * (*px++)) >> 15); *pb++ = (q15_t) __SSAT((coef), 16); /* Decrement the loop counter */ tapCnt--; } /* Read the sample from state buffer */ x0 = *pState; /* Advance state pointer by 1 for the next sample */ pState = pState + 1u; /* Decrement the loop counter */ blkCnt--; } /* Save energy and x0 values for the next frame */ S->energy = (q15_t) energy; S->x0 = x0; /* Processing is complete. Now copy the last numTaps - 1 samples to the satrt of the state buffer. This prepares the state buffer for the next function call. */ /* Points to the start of the pState buffer */ pStateCurnt = S->pState; /* copy (numTaps - 1u) data */ tapCnt = (numTaps - 1u); /* copy data */ while(tapCnt > 0u) { *pStateCurnt++ = *pState++; /* Decrement the loop counter */ tapCnt--; } #endif /* #ifndef ARM_MATH_CM0 */ } /** * @} end of LMS_NORM group */
lgpl-3.0
cvmanjoo/RTC
src/PCF8523.cpp
1
13944
/* * PCF8523.cpp - Library to set & get time from RTC PCF8523 * Created by Manjunath CV. August 15, 2022, 08:07 PM * Released into the public domain. */ #include <time.h> #include <Arduino.h> #include <Wire.h> #include <I2C_RTC.h> #define R_CONTROL_1 0x00 #define R_CONTROL_2 0x01 #define R_CONTROL_3 0x02 #define R_SECONDS 0x03 #define R_MINUTES 0x04 #define R_HOURS 0x05 #define R_DAYS 0x06 #define R_WEEKDAYS 0x07 #define R_MONTHS 0x08 #define R_YEARS 0x09 bool PCF8523::begin() { Wire.begin(); // join i2c bus Wire.beginTransmission (PCF8523_ADDR); return (Wire.endTransmission() == 0 ? true : false); } bool PCF8523::isRunning(void) { uint8_t data; bool flag; Wire.beginTransmission(PCF8523_ADDR); Wire.write(R_CONTROL_1); Wire.endTransmission(); Wire.requestFrom(PCF8523_ADDR, 1); data = Wire.read(); flag = bitRead(data,5); return (!flag); } void PCF8523::startClock(void) { uint8_t data; Wire.beginTransmission(PCF8523_ADDR); Wire.write(R_CONTROL_1); Wire.endTransmission(); Wire.requestFrom(PCF8523_ADDR, 1); data = Wire.read(); bitClear(data, 5); Wire.beginTransmission(PCF8523_ADDR); Wire.write(R_CONTROL_1); // Seconds Register Wire.write(data); Wire.endTransmission(); } void PCF8523::stopClock(void) { uint8_t data; Wire.beginTransmission(PCF8523_ADDR); Wire.write(R_CONTROL_1); Wire.endTransmission(); Wire.requestFrom(PCF8523_ADDR, 1); data = Wire.read(); bitSet(data, 5); Wire.beginTransmission(PCF8523_ADDR); Wire.write(R_CONTROL_1); // Seconds Register Wire.write(data); Wire.endTransmission(); } void PCF8523::setHourMode(uint8_t h_mode) { uint8_t data; if(h_mode == CLOCK_H12 || h_mode == CLOCK_H24) { Wire.beginTransmission(PCF8523_ADDR); Wire.write(R_CONTROL_1); Wire.endTransmission(); Wire.requestFrom(PCF8523_ADDR, 1); data = Wire.read(); bitWrite(data, 3, h_mode); Wire.beginTransmission(PCF8523_ADDR); Wire.write(R_CONTROL_1); // Hour Register Wire.write(data); Wire.endTransmission(); } } uint8_t PCF8523::getHourMode() { bool h_mode; uint8_t data; Wire.beginTransmission(PCF8523_ADDR); Wire.write(R_CONTROL_1); Wire.endTransmission(); Wire.requestFrom(PCF8523_ADDR, 1); data = Wire.read(); h_mode = bitRead(data, 3); return (h_mode); } void PCF8523::setMeridiem(uint8_t meridiem) { uint8_t data; if(meridiem == HOUR_AM || meridiem == HOUR_PM) { if (getHourMode() == CLOCK_H12) { Wire.beginTransmission(PCF8523_ADDR); Wire.write(R_HOURS); // Hour Register Wire.endTransmission(); Wire.requestFrom(PCF8523_ADDR, 1); data = Wire.read(); bitWrite(data, 5, meridiem); Wire.beginTransmission(PCF8523_ADDR); Wire.write(R_HOURS); // Hour Register Wire.write(data); Wire.endTransmission(); } } } uint8_t PCF8523::getMeridiem() { bool flag; uint8_t data; if (getHourMode() == CLOCK_H12) { Wire.beginTransmission(PCF8523_ADDR); Wire.write(R_HOURS); Wire.endTransmission(); Wire.requestFrom(PCF8523_ADDR, 1); data = Wire.read(); flag = bitRead(data, 5); return (flag); } else return (HOUR_24); } /*----------------------------------------------------------- get & set Second -----------------------------------------------------------*/ uint8_t PCF8523::getSeconds() { uint8_t seconds; Wire.beginTransmission(PCF8523_ADDR); Wire.write(R_SECONDS); // Seconds Register Wire.endTransmission(); Wire.requestFrom(PCF8523_ADDR, 1); seconds = Wire.read(); bitClear(seconds, 7); // Clearing OS Bit if Set. return (bcd2bin(seconds)); } void PCF8523::setSeconds(uint8_t seconds) { uint8_t data, os_bit; if (seconds >= 00 && seconds <= 59) { Wire.beginTransmission(PCF8523_ADDR); Wire.write(R_SECONDS); // Second Register Wire.write(bin2bcd(seconds)); Wire.endTransmission(); } } /*----------------------------------------------------------- getMinutes -----------------------------------------------------------*/ uint8_t PCF8523::getMinutes() { uint8_t minutes; Wire.beginTransmission(PCF8523_ADDR); Wire.write(R_MINUTES); // Minute Register Wire.endTransmission(); Wire.requestFrom(PCF8523_ADDR, 1); minutes = Wire.read(); return (bcd2bin(minutes)); } void PCF8523::setMinutes(uint8_t minutes) { if(minutes >= 00 && minutes <= 59) { Wire.beginTransmission(PCF8523_ADDR); Wire.write(R_MINUTES); // Minute Register Wire.write(bin2bcd(minutes)); Wire.endTransmission(); } } /*----------------------------------------------------------- getHours -----------------------------------------------------------*/ uint8_t PCF8523::getHours() { uint8_t hours; bool h_mode; h_mode = getHourMode(); Wire.beginTransmission(PCF8523_ADDR); Wire.write(R_HOURS); // Hour Register Wire.endTransmission(); Wire.requestFrom(PCF8523_ADDR, 1); hours = Wire.read(); if (h_mode == CLOCK_H24) { return (bcd2bin(hours)); } else if (h_mode == CLOCK_H12) { bitClear(hours, 5); return (bcd2bin(hours)); } } void PCF8523::setHours(uint8_t hours) { bool h_mode; if (hours >= 00 && hours <= 23) { h_mode = getHourMode(); Wire.beginTransmission(PCF8523_ADDR); Wire.write(R_HOURS); // Hour Register if (h_mode == CLOCK_H24) { Wire.write(bin2bcd(hours)); } else if (h_mode == CLOCK_H12) { if (hours > 12) { hours = hours % 12; hours = bin2bcd(hours); bitSet(hours, 5); Wire.write(hours); } else { hours = bin2bcd(hours); bitClear(hours, 5); Wire.write(hours); } } Wire.endTransmission(); } } /*----------------------------------------------------------- getWeek -----------------------------------------------------------*/ uint8_t PCF8523::getWeek() { uint8_t week; Wire.beginTransmission(PCF8523_ADDR); Wire.write(R_WEEKDAYS); // Week Register Wire.endTransmission(); Wire.requestFrom(PCF8523_ADDR, 1); week = Wire.read(); return week+1; } void PCF8523::setWeek(uint8_t week) { Wire.beginTransmission(PCF8523_ADDR); Wire.write(R_WEEKDAYS); // Week Register Wire.write(week-1); Wire.endTransmission(); } void PCF8523::updateWeek() { uint16_t y; uint8_t m, d, weekday; y=getYear(); m=getMonth(); d=getDay(); weekday = (d += m < 3 ? y-- : y - 2, 23*m/9 + d + 4 + y/4- y/100 + y/400)%7; if (weekday >= 1 && weekday <= 7) { Wire.beginTransmission(PCF8523_ADDR); Wire.write(0x07); // Week Register Wire.write(weekday-1); Wire.endTransmission(); } } /*----------------------------------------------------------- getDay -----------------------------------------------------------*/ uint8_t PCF8523::getDay() { uint8_t day; Wire.beginTransmission(PCF8523_ADDR); Wire.write(R_DAYS); // Day Register Wire.endTransmission(); Wire.requestFrom(PCF8523_ADDR, 1); day = Wire.read(); return (bcd2bin(day)); } void PCF8523::setDay(uint8_t day) { Wire.beginTransmission(PCF8523_ADDR); Wire.write(R_DAYS); // Day Register Wire.write(bin2bcd(day)); Wire.endTransmission(); } /*----------------------------------------------------------- getMonth() -----------------------------------------------------------*/ uint8_t PCF8523::getMonth() { uint8_t month; Wire.beginTransmission(PCF8523_ADDR); Wire.write(R_MONTHS); // Month Register Wire.endTransmission(); Wire.requestFrom(PCF8523_ADDR, 1); month = Wire.read(); return (bcd2bin(month)); } /*----------------------------------------------------------- setMonth() -----------------------------------------------------------*/ void PCF8523::setMonth(uint8_t month) { uint8_t data, century_bit; if (month >= 1 && month <= 12) { Wire.beginTransmission(PCF8523_ADDR); Wire.write(R_MONTHS); // Month Register Wire.write(month); Wire.endTransmission(); } } /*----------------------------------------------------------- getYear (Completed) * Always return 4 Digit year * Takes Care of Century. -----------------------------------------------------------*/ uint16_t PCF8523::getYear() { uint16_t year; Wire.beginTransmission(PCF8523_ADDR); Wire.write(R_YEARS); // Read Month register for Century Wire.endTransmission(); Wire.requestFrom(PCF8523_ADDR,1); year = Wire.read(); return (bcd2bin(year) + 2000); } /*----------------------------------------------------------- setYear (Completed) * Accepts both 2 and 4 Digit Years. -----------------------------------------------------------*/ void PCF8523::setYear(uint16_t year) { if((year >= 00 && year <= 99) || (year >= 2000 && year <= 2099)) { year = year % 100; //Converting to 2 Digit // Write 2 Digit year to Year Register Wire.beginTransmission(PCF8523_ADDR); Wire.write(R_YEARS); Wire.write(bin2bcd(year)); Wire.endTransmission(); } } /*----------------------------------------------------------- setTime -----------------------------------------------------------*/ void PCF8523::setTime(uint8_t hour, uint8_t minute, uint8_t second) { Wire.beginTransmission(PCF8523_ADDR); Wire.write(R_SECONDS); Wire.write(bin2bcd(second)); //0x02 Seconds Wire.write(bin2bcd(minute)); //0x03 Minutes Wire.write(bin2bcd(hour)); //0x04 Hours Wire.endTransmission(); } /*----------------------------------------------------------- setDate (Should be Optimised) Not working -----------------------------------------------------------*/ void PCF8523::setDate(uint8_t day, uint8_t month, uint16_t year) { uint8_t century, data; // If year is 2 digits. if(year < 100) year = year + 2000; century = year / 100; // Find Century year = year % 100; //Converting to 2 Digit Wire.beginTransmission(PCF8523_ADDR); Wire.write(0x05); Wire.write(bin2bcd(day)); //0x05 Day Wire.write(0); //0x06 Weekday Wire.write(bin2bcd(month)); //0x07 Months Wire.write(bin2bcd(year)); //0x08 Years Wire.endTransmission(); Wire.beginTransmission(PCF8523_ADDR); Wire.write(0x07); // Century and month Register Wire.endTransmission(); Wire.requestFrom(PCF8523_ADDR, 1); data = Wire.read(); // Set century bit to 1 for year > 2000; if(century == 20) bitSet(data,7); else bitClear(data,7); // Write Century bit to Month Register(0x07) Wire.beginTransmission(PCF8523_ADDR); Wire.write(0x07); // Wire.write(data); Wire.endTransmission(); } /*----------------------------------------------------------- setDateTime() Taken from https://github.com/adafruit/RTClib/ -----------------------------------------------------------*/ void PCF8523::setDateTime(char* date, char* time) { uint8_t day, month, hour, minute, second; uint16_t year; // sample input: date = "Dec 26 2009", time = "12:34:56" year = atoi(date + 9); setYear(year); // Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec switch (date[0]) { case 'J': month = (date[1] == 'a') ? 1 : ((date[2] == 'n') ? 6 : 7); break; case 'F': month = 2; break; case 'A': month = date[2] == 'r' ? 4 : 8; break; case 'M': month = date[2] == 'r' ? 3 : 5; break; case 'S': month = 9; break; case 'O': month = 10; break; case 'N': month = 11; break; case 'D': month = 12; break; } setMonth(month); day = atoi(date + 4); setDay(day); hour = atoi(time); setHours(hour); minute = atoi(time + 3); setMinutes(minute); second = atoi(time + 6); setSeconds(second); } /*----------------------------------------------------------- setEpoch() * Weekday Might not work properly * Remove Century -----------------------------------------------------------*/ void PCF8523::setEpoch(time_t epoch) { uint8_t data, century; uint16_t year; struct tm epoch_tm, *ptr_epoch_tm; ptr_epoch_tm = gmtime(&epoch); epoch_tm = *ptr_epoch_tm; century = (epoch_tm.tm_year + 1870) / 100; // Find Century year = (epoch_tm.tm_year + 1870) % 100; //Converting to 2 Digit Wire.beginTransmission(PCF8523_ADDR); Wire.write(R_SECONDS); // Seconds Register Wire.write(bin2bcd(epoch_tm.tm_sec)); //0x02 Wire.write(bin2bcd(epoch_tm.tm_min)); //0x03 Wire.write(bin2bcd(epoch_tm.tm_hour)); //0x04 Wire.write(bin2bcd(epoch_tm.tm_mday)); //0x05 Wire.write(bin2bcd(epoch_tm.tm_wday)); //0x06 Wire.write(bin2bcd(epoch_tm.tm_mon+1)); //0x07 Wire.write(bin2bcd(year)); //0x08 Wire.endTransmission(); Wire.beginTransmission(PCF8523_ADDR); Wire.write(0x07); // Century and month Register Wire.endTransmission(); Wire.requestFrom(PCF8523_ADDR, 1); data = Wire.read(); // Set century bit to 1 for year > 2000; if(century == 20) bitSet(data,7); else bitClear(data,7); // Write Century bit to Month Register(0x07) Wire.beginTransmission(PCF8523_ADDR); Wire.write(0x07); // Wire.write(data); Wire.endTransmission(); } /*----------------------------------------------------------- getEpoch() * Weekday Might not work properly -----------------------------------------------------------*/ time_t PCF8523::getEpoch() { uint8_t century_bit; uint16_t century; time_t epoch; struct tm epoch_tm; Wire.beginTransmission(PCF8523_ADDR); Wire.write(0x02); // Seconds Register Wire.endTransmission(); Wire.requestFrom(PCF8523_ADDR,7); epoch_tm.tm_sec = bcd2bin(Wire.read()); //0x02 Seconds epoch_tm.tm_min = bcd2bin(Wire.read()); //0x03 Minutes epoch_tm.tm_hour = bcd2bin(Wire.read()); //0x04 Hours epoch_tm.tm_mday = bcd2bin(Wire.read()); //0x05 Day epoch_tm.tm_wday = bcd2bin(Wire.read()); //0x06 Weekday epoch_tm.tm_mon = Wire.read(); //0x07 Months epoch_tm.tm_year = bcd2bin(Wire.read()); //0x08 Years // Read Century Bit from Month Register century_bit = bitRead(epoch_tm.tm_mon, 7); bitClear(epoch_tm.tm_mon,7); epoch_tm.tm_mon = bcd2bin(epoch_tm.tm_mon)-1; if(century_bit == 0) century = 1900; else century = 2000; epoch_tm.tm_year = epoch_tm.tm_year + century - 1870; epoch = mktime(&epoch_tm); return (epoch); } /* Helpers */ uint8_t PCF8523::bcd2bin (uint8_t val) { return val - 6 * (val >> 4); } uint8_t PCF8523::bin2bcd (uint8_t val) { return val + 6 * (val / 10); }
unlicense
jasonhutchens/kranzky_ice
girder.cpp
1
3619
//============================================================================== #include <girder.hpp> #include <engine.hpp> #include <entity_manager.hpp> #include <hgesprite.h> #include <Box2D.h> #include <sqlite3.h> #include <Database.h> #include <Query.h> //============================================================================== Girder::Girder( float scale ) : Entity( scale ), m_dimensions(), m_shield( false ) { } //------------------------------------------------------------------------------ Girder::~Girder() { } //------------------------------------------------------------------------------ void Girder::collide( Entity * entity, b2ContactPoint * point ) { } //------------------------------------------------------------------------------ void Girder::persistToDatabase() { char * rows[] = { "x", "%f", "y", "%f", "angle", "%f", "scale", "%f", "sprite_id", "%d" }; m_id = Engine::em()->persistToDatabase( this, rows, m_body->GetPosition().x, m_body->GetPosition().y, m_body->GetAngle(), m_scale, m_sprite_id ); } //------------------------------------------------------------------------------ void Girder::setDimensions( const b2Vec2 & dimensions ) { m_dimensions = dimensions; } //------------------------------------------------------------------------------ void Girder::setShield( bool shield ) { m_shield = shield; } //------------------------------------------------------------------------------ bool Girder::getShield() const { return m_shield; } //------------------------------------------------------------------------------ // static: //------------------------------------------------------------------------------ void Girder::registerEntity() { Engine::em()->registerEntity( Girder::TYPE, Girder::factory, "girders", "id, x, y, angle, scale, sprite_id" ); } //------------------------------------------------------------------------------ // protected: //------------------------------------------------------------------------------ void Girder::doInit() { b2PolygonDef shapeDef; shapeDef.SetAsBox( m_dimensions.x * m_scale, m_dimensions.y * m_scale ); shapeDef.friction = 0.0f; b2BodyDef bodyDef; bodyDef.userData = static_cast< void * >( this ); m_body = Engine::b2d()->CreateStaticBody( & bodyDef ); m_body->CreateShape( & shapeDef ); } //------------------------------------------------------------------------------ void Girder::doUpdate( float dt ) { } //------------------------------------------------------------------------------ void Girder::doRender( float scale ) { } //------------------------------------------------------------------------------ void Girder::initFromQuery( Query & query ) { b2Vec2 position( 0.0f, 0.0f ); float angle( 0.0f ); m_id = static_cast< sqlite_int64 >( query.getnum() ); position.x = static_cast< float >( query.getnum() ); position.y = static_cast< float >( query.getnum() ); angle = static_cast< float >( query.getnum() ); m_scale = static_cast< float >( query.getnum() ); setSpriteID( static_cast< sqlite_int64 >( query.getnum() ) ); init(); m_body->SetXForm( position, angle ); } //==============================================================================
unlicense
ytailor/42sh
libft/ft_memset.c
4
1053
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_memset.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mmartin <mmartin@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2013/11/19 15:08:49 by mmartin #+# #+# */ /* Updated: 2013/12/06 17:25:36 by mmartin ### ########.fr */ /* */ /* ************************************************************************** */ #include <string.h> void *ft_memset(void *b, int c, size_t len) { size_t i; char *save; i = -1; save = b; while (++i < len) save[i] = c; return (b); }
unlicense
cd80/UtilizedLLVM
tools/clang/test/SemaCXX/class-layout.cpp
20
9117
// RUN: %clang_cc1 -triple x86_64-unknown-unknown %s -fsyntax-only -verify -std=c++98 -Wno-inaccessible-base // RUN: %clang_cc1 -triple x86_64-unknown-unknown %s -fsyntax-only -verify -std=c++11 -Wno-inaccessible-base // expected-no-diagnostics #define SA(n, p) int a##n[(p) ? 1 : -1] struct A { int a; char b; }; SA(0, sizeof(A) == 8); struct B : A { char c; }; SA(1, sizeof(B) == 12); struct C { // Make fields private so C won't be a POD type. private: int a; char b; }; SA(2, sizeof(C) == 8); struct D : C { char c; }; SA(3, sizeof(D) == 8); struct __attribute__((packed)) E { char b; int a; }; SA(4, sizeof(E) == 5); struct __attribute__((packed)) F : E { char d; }; SA(5, sizeof(F) == 6); struct G { G(); }; struct H : G { }; SA(6, sizeof(H) == 1); struct I { char b; int a; } __attribute__((packed)); SA(6_1, sizeof(I) == 5); // PR5580 namespace PR5580 { class A { bool iv0 : 1; }; SA(7, sizeof(A) == 1); class B : A { bool iv0 : 1; }; SA(8, sizeof(B) == 2); struct C { bool iv0 : 1; }; SA(9, sizeof(C) == 1); struct D : C { bool iv0 : 1; }; SA(10, sizeof(D) == 2); } namespace Test1 { // Test that we don't assert on this hierarchy. struct A { }; struct B : A { virtual void b(); }; class C : virtual A { int c; }; struct D : virtual B { }; struct E : C, virtual D { }; class F : virtual E { }; struct G : virtual E, F { }; SA(0, sizeof(G) == 24); } namespace Test2 { // Test that this somewhat complex class structure is laid out correctly. struct A { }; struct B : A { virtual void b(); }; struct C : virtual B { }; struct D : virtual A { }; struct E : virtual B, D { }; struct F : E, virtual C { }; struct G : virtual F, A { }; struct H { G g; }; SA(0, sizeof(H) == 24); } namespace PR16537 { namespace test1 { struct pod_in_11_only { private: long long x; }; struct tail_padded_pod_in_11_only { pod_in_11_only pod11; char tail_padding; }; struct might_use_tail_padding : public tail_padded_pod_in_11_only { char may_go_into_tail_padding; }; SA(0, sizeof(might_use_tail_padding) == 16); } namespace test2 { struct pod_in_11_only { private: long long x; }; struct tail_padded_pod_in_11_only { pod_in_11_only pod11 __attribute__((aligned(16))); }; struct might_use_tail_padding : public tail_padded_pod_in_11_only { char may_go_into_tail_padding; }; SA(0, sizeof(might_use_tail_padding) == 16); } namespace test3 { struct pod_in_11_only { private: long long x; }; struct tail_padded_pod_in_11_only { pod_in_11_only pod11; char tail_padding; }; struct second_base { char foo; }; struct might_use_tail_padding : public tail_padded_pod_in_11_only, public second_base { }; SA(0, sizeof(might_use_tail_padding) == 16); } namespace test4 { struct pod_in_11_only { private: long long x; }; struct tail_padded_pod_in_11_only { pod_in_11_only pod11; char tail_padding; }; struct second_base { char foo; }; struct might_use_tail_padding : public tail_padded_pod_in_11_only, public second_base { char may_go_into_tail_padding; }; SA(0, sizeof(might_use_tail_padding) == 16); } namespace test5 { struct pod_in_11_only { private: long long x; }; struct pod_in_11_only2 { private: long long x; }; struct tail_padded_pod_in_11_only { pod_in_11_only pod11; char tail_padding; }; struct second_base { pod_in_11_only2 two; char foo; }; struct might_use_tail_padding : public tail_padded_pod_in_11_only, public second_base { char may_go_into_tail_padding; }; SA(0, sizeof(might_use_tail_padding) == 32); } namespace test6 { struct pod_in_11_only { private: long long x; }; struct pod_in_11_only2 { private: long long x; }; struct tail_padded_pod_in_11_only { pod_in_11_only pod11; char tail_padding; }; struct second_base { pod_in_11_only2 two; char foo; }; struct might_use_tail_padding : public tail_padded_pod_in_11_only, public second_base { char may_go_into_tail_padding; }; SA(0, sizeof(might_use_tail_padding) == 32); } namespace test7 { struct pod_in_11_only { private: long long x; }; struct tail_padded_pod_in_11_only { pod_in_11_only pod11; pod_in_11_only pod12; char tail_padding; }; struct might_use_tail_padding : public tail_padded_pod_in_11_only { char may_go_into_tail_padding; }; SA(0, sizeof(might_use_tail_padding) == 24); } namespace test8 { struct pod_in_11_only { private: long long x; }; struct tail_padded_pod_in_11_only { pod_in_11_only pod11; char tail_padding; }; struct another_layer { tail_padded_pod_in_11_only pod; char padding; }; struct might_use_tail_padding : public another_layer { char may_go_into_tail_padding; }; SA(0, sizeof(might_use_tail_padding) == 24); } namespace test9 { struct pod_in_11_only { private: long long x; }; struct tail_padded_pod_in_11_only { pod_in_11_only pod11; char tail_padding; }; struct another_layer : tail_padded_pod_in_11_only { }; struct might_use_tail_padding : public another_layer { char may_go_into_tail_padding; }; SA(0, sizeof(might_use_tail_padding) == 16); } namespace test10 { struct pod_in_11_only { private: long long x; }; struct A { pod_in_11_only a; char apad; }; struct B { char b; }; struct C { pod_in_11_only c; char cpad; }; struct D { char d; }; struct might_use_tail_padding : public A, public B, public C, public D { }; SA(0, sizeof(might_use_tail_padding) == 32); } namespace test11 { struct pod_in_11_only { private: long long x; }; struct A { pod_in_11_only a; char apad; }; struct B { char b_pre; pod_in_11_only b; char bpad; }; struct C { char c_pre; pod_in_11_only c; char cpad; }; struct D { char d_pre; pod_in_11_only d; char dpad; }; struct might_use_tail_padding : public A, public B, public C, public D { char m; }; SA(0, sizeof(might_use_tail_padding) == 88); } namespace test12 { struct pod_in_11_only { private: long long x; }; struct A { pod_in_11_only a __attribute__((aligned(128))); }; struct B { char bpad; }; struct C { char cpad; }; struct D { char dpad; }; struct might_use_tail_padding : public A, public B, public C, public D { char m; }; SA(0, sizeof(might_use_tail_padding) == 128); } namespace test13 { struct pod_in_11_only { private: long long x; }; struct A { pod_in_11_only a; char apad; }; struct B { }; struct C { char c_pre; pod_in_11_only c; char cpad; }; struct D { }; struct might_use_tail_padding : public A, public B, public C, public D { char m; }; SA(0, sizeof(might_use_tail_padding) == 40); } namespace test14 { struct pod_in_11_only { private: long long x; }; struct A { pod_in_11_only a; char apad; }; struct might_use_tail_padding : public A { struct { int : 0; } x; }; SA(0, sizeof(might_use_tail_padding) == 16); } namespace test15 { struct pod_in_11_only { private: long long x; }; struct A { pod_in_11_only a; char apad; }; struct might_use_tail_padding : public A { struct { char a:1; char b:2; char c:2; char d:2; char e:1; } x; }; SA(0, sizeof(might_use_tail_padding) == 16); } namespace test16 { struct pod_in_11_only { private: long long x; }; struct A { pod_in_11_only a; char apad; }; struct B { char bpod; pod_in_11_only b; char bpad; }; struct C : public A, public B { }; struct D : public C { }; struct might_use_tail_padding : public D { char m; }; SA(0, sizeof(might_use_tail_padding) == 40); } namespace test17 { struct pod_in_11_only { private: long long x; }; struct A { pod_in_11_only a __attribute__((aligned(512))); }; struct B { char bpad; pod_in_11_only foo; char btail; }; struct C { char cpad; }; struct D { char dpad; }; struct might_use_tail_padding : public A, public B, public C, public D { char a; }; SA(0, sizeof(might_use_tail_padding) == 512); } namespace test18 { struct pod_in_11_only { private: long long x; }; struct A { pod_in_11_only a; char apad; }; struct B { char bpod; pod_in_11_only b; char bpad; }; struct A1 { pod_in_11_only a; char apad; }; struct B1 { char bpod; pod_in_11_only b; char bpad; }; struct C : public A, public B { }; struct D : public A1, public B1 { }; struct E : public D, public C { }; struct F : public E { }; struct might_use_tail_padding : public F { char m; }; SA(0, sizeof(might_use_tail_padding) == 80); } } // namespace PR16537
unlicense