コード例 #1
0
ファイル: url.c プロジェクト: Myleft/cphalcon7
/**
 * Generates a URL
 *
 *<code>
 *
 * //Generate a URL appending the URI to the base URI
 * echo $url->get('products/edit/1');
 *
 * //Generate a URL for a predefined route
 * echo $url->get(array('for' => 'blog-post', 'title' => 'some-cool-stuff', 'year' => '2012'));
 * echo $url->get(array('for' => 'blog-post', 'hostname' => true, 'title' => 'some-cool-stuff', 'year' => '2012'));
 *
 *</code>
 *
 * @param string|array $uri
 * @param array|object args Optional arguments to be appended to the query string
 * @param bool|null $local
 * @return string
 */
PHP_METHOD(Phalcon_Mvc_Url, get){

	zval *uri = NULL, *args = NULL, *local = NULL, *base_uri = NULL, *router = NULL, *dependency_injector;
	zval *service, *route_name, *hostname, *route = NULL, *exception_message;
	zval *pattern = NULL, *paths = NULL, *processed_uri = NULL, *query_string;
	zval *matched, *regexp;
	zval *generator = NULL, *arguments;

	PHALCON_MM_GROW();

	phalcon_fetch_params(1, 0, 3, &uri, &args, &local);

	if (!uri) {
		uri = &PHALCON_GLOBAL(z_null);
	}

	if (!args) {
		args = &PHALCON_GLOBAL(z_null);
	}

	if (!local) {
		local = &PHALCON_GLOBAL(z_null);
	} else {
		PHALCON_SEPARATE_PARAM(local);
	}

	PHALCON_CALL_METHOD(&base_uri, getThis(), "getbaseuri");

	if (Z_TYPE_P(uri) == IS_STRING) {
		if (strstr(Z_STRVAL_P(uri), ":")) {
			PHALCON_INIT_VAR(matched);
			PHALCON_INIT_VAR(regexp);
			ZVAL_STRING(regexp, "/^[^:\\/?#]++:/");
			RETURN_MM_ON_FAILURE(phalcon_preg_match(matched, regexp, uri, NULL));
			if (zend_is_true(matched)) {
				PHALCON_INIT_NVAR(local);
				ZVAL_FALSE(local);
			}
		}

		if (Z_TYPE_P(local) == IS_NULL || zend_is_true(local)) {
			PHALCON_CONCAT_VV(return_value, base_uri, uri);
		} else {
			ZVAL_ZVAL(return_value, uri, 1, 0);
		}
	} else if (Z_TYPE_P(uri) == IS_ARRAY) {
		if (!phalcon_array_isset_str_fetch(&route_name, uri, SL("for"))) {
			PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_url_exception_ce, "It's necessary to define the route name with the parameter \"for\"");
			return;
		}

		router = phalcon_read_property(getThis(), SL("_router"), PH_NOISY);

		/**
		 * Check if the router has not previously set
		 */
		if (Z_TYPE_P(router) != IS_OBJECT) {
			dependency_injector = phalcon_read_property(getThis(), SL("_dependencyInjector"), PH_NOISY);
			if (!zend_is_true(dependency_injector)) {
				PHALCON_THROW_EXCEPTION_STR(phalcon_mvc_url_exception_ce, "A dependency injector container is required to obtain the \"url\" service");
				return;
			}

			PHALCON_INIT_VAR(service);
			ZVAL_STR(service, IS(router));

			router = NULL;
			PHALCON_CALL_METHOD(&router, dependency_injector, "getshared", service);
			PHALCON_VERIFY_INTERFACE(router, phalcon_mvc_routerinterface_ce);
			phalcon_update_property_this(getThis(), SL("_router"), router);
		}

		/**
		 * Every route is uniquely identified by a name
		 */
		PHALCON_CALL_METHOD(&route, router, "getroutebyname", route_name);
		if (Z_TYPE_P(route) != IS_OBJECT) {
			PHALCON_INIT_VAR(exception_message);
			PHALCON_CONCAT_SVS(exception_message, "Cannot obtain a route using the name \"", route_name, "\"");
			PHALCON_THROW_EXCEPTION_ZVAL(phalcon_mvc_url_exception_ce, exception_message);
			return;
		}

		PHALCON_CALL_METHOD(&pattern, route, "getpattern");

		/**
		 * Return the reversed paths
		 */
		PHALCON_CALL_METHOD(&paths, route, "getreversedpaths");

		/**
		 * Return the Url Generator
		 */
		PHALCON_CALL_METHOD(&generator, route, "geturlgenerator");

		if (phalcon_is_callable(generator) ||
			(Z_TYPE_P(generator) == IS_OBJECT && instanceof_function(Z_OBJCE_P(generator), zend_ce_closure))) {
			PHALCON_INIT_VAR(arguments);
			array_init_size(arguments, 3);
			phalcon_array_append(arguments, base_uri, PH_COPY);
			phalcon_array_append(arguments, paths, PH_COPY);
			phalcon_array_append(arguments, uri, PH_COPY);
			PHALCON_CALL_USER_FUNC_ARRAY(&return_value, generator, arguments);
		} else {
			/**
			 * Replace the patterns by its variables
			 */
			PHALCON_INIT_NVAR(processed_uri);
			phalcon_replace_paths(processed_uri, pattern, paths, uri);

			PHALCON_CONCAT_VV(return_value, base_uri, processed_uri);

			if (phalcon_array_isset_str_fetch(&hostname, uri, SL("hostname"))) {
				if (zend_is_true(hostname)) {
					PHALCON_CALL_METHOD(&hostname, route, "gethostname");

					PHALCON_INIT_NVAR(processed_uri);
					PHALCON_CONCAT_VV(processed_uri, hostname, return_value);

					ZVAL_ZVAL(return_value, processed_uri, 1, 0);
				}
			}
		}
	}

	if (zend_is_true(args)) {
		PHALCON_INIT_VAR(query_string);
		phalcon_http_build_query(query_string, args, "&");
		if (Z_TYPE_P(query_string) == IS_STRING && Z_STRLEN_P(query_string)) {
			if (phalcon_memnstr_str(return_value, "?", 1)) {
				PHALCON_SCONCAT_SV(return_value, "&", query_string);
			}
			else {
				PHALCON_SCONCAT_SV(return_value, "?", query_string);
			}
		}
	}

	RETURN_MM();
}
コード例 #2
0
void do_tests() {
    mixed x, y;
    foreach (x, y in values) {
        IS(x, y);
    }
コード例 #3
0
ファイル: cookie.c プロジェクト: Myleft/cphalcon7
/**
 * Returns the cookie's value
 *
 * @param string|array $filters
 * @param string $defaultValue
 * @return mixed
 */
PHP_METHOD(Phalcon_Http_Cookie, getValue){

	zval *filters = NULL, *default_value = NULL, *restored, *dependency_injector = NULL;
	zval *readed, *name, *_COOKIE, *value = NULL, *encryption;
	zval *service = NULL, *crypt = NULL, *decrypted_value = NULL, *filter = NULL;

	PHALCON_MM_GROW();

	phalcon_fetch_params(0, 0, 2, &filters, &default_value);

	if (!filters) {
		filters = &PHALCON_GLOBAL(z_null);
	}

	if (!default_value) {
		default_value = &PHALCON_GLOBAL(z_null);
	}

	restored = phalcon_read_property(getThis(), SL("_restored"), PH_NOISY);
	if (!zend_is_true(restored)) {
		PHALCON_CALL_METHOD(NULL, getThis(), "restore");
	}

	PHALCON_INIT_VAR(dependency_injector);

	readed = phalcon_read_property(getThis(), SL("_readed"), PH_NOISY);
	if (PHALCON_IS_FALSE(readed)) {
		name = phalcon_read_property(getThis(), SL("_name"), PH_NOISY);

		_COOKIE = phalcon_get_global(SL("_COOKIE"));
		if (phalcon_array_isset_fetch(&value, _COOKIE, name)) {
			encryption = phalcon_read_property(getThis(), SL("_useEncryption"), PH_NOISY);
			if (zend_is_true(encryption)) {
				dependency_injector = phalcon_read_property(getThis(), SL("_dependencyInjector"), PH_NOISY);
				if (Z_TYPE_P(dependency_injector) != IS_OBJECT) {
					PHALCON_THROW_EXCEPTION_STR(phalcon_http_cookie_exception_ce, "A dependency injection object is required to access the 'filter' service");
					return;
				}

				PHALCON_INIT_VAR(service);
				ZVAL_STRING(service, "crypt");

				PHALCON_CALL_METHOD(&crypt, dependency_injector, "getshared", service);
				PHALCON_VERIFY_INTERFACE(crypt, phalcon_cryptinterface_ce);

				/** 
				 * Decrypt the value also decoding it with base64
				 */
				PHALCON_CALL_METHOD(&decrypted_value, crypt, "decryptbase64", value);
			} else {
				PHALCON_CPY_WRT(decrypted_value, value);
			}

			/** 
			 * Update the decrypted value
			 */
			phalcon_update_property_this(getThis(), SL("_value"), decrypted_value);
			if (Z_TYPE_P(filters) != IS_NULL) {
				filter = phalcon_read_property(getThis(), SL("_filter"), PH_NOISY);
				if (Z_TYPE_P(filter) != IS_OBJECT) {
					if (Z_TYPE_P(dependency_injector) == IS_NULL) {
						dependency_injector = phalcon_read_property(getThis(), SL("_dependencyInjector"), PH_NOISY);
						PHALCON_VERIFY_INTERFACE_EX(dependency_injector, phalcon_diinterface_ce, phalcon_http_cookie_exception_ce, 1);
					}

					PHALCON_INIT_NVAR(service);
					ZVAL_STR(service, IS(filter));

					PHALCON_CALL_METHOD(&filter, dependency_injector, "getshared", service);
					PHALCON_VERIFY_INTERFACE(filter, phalcon_filterinterface_ce);
					phalcon_update_property_this(getThis(), SL("_filter"), filter);
				}

				PHALCON_RETURN_CALL_METHOD(filter, "sanitize", decrypted_value, filters);
				RETURN_MM();
			}

			/** 
			 * Return the value without filtering
			 */

			RETURN_CTOR(decrypted_value);
		}

		RETURN_CTOR(default_value);
	}

	value = phalcon_read_property(getThis(), SL("_value"), PH_NOISY);

	RETURN_CTOR(value);
}
コード例 #4
0
ファイル: lua_compiler.c プロジェクト: NaughtyCode/slua
static int pmain(lua_State* L) {
  struct Smain* s = (struct Smain*)lua_touserdata(L, 1);
  int argc=s->argc;
  char** argv=s->argv;
  Proto* f;
  int scripts=0;
  int i;
  if (!lua_checkstack(L,argc)) fatal("too many input files");
  lua_gc(L, LUA_GCSTOP, 0);  /* stop collector during initialization */
  luaL_openlibs(L);  /* open libraries */
  lua_gc(L, LUA_GCRESTART, 0);
  /* compile each script from command line into a Lua function. */
  for (i=0; i<argc; i++) {
    const char* filename=IS("-") ? NULL : argv[i];
    if(IS("-L")) break;
    if (luaL_loadfile(L,filename)!=0) fatal(lua_tostring(L,-1));
    scripts++;
  }
  /* compile each preload library from the command line into a Lua function. */
  for (i=0; i<preloads; i++) {
    char* filename=preload_libs[i];
    char* p;
    /* try loading library as if it is a normal file. */
    if (luaL_loadfile(L,filename)!=0) {
      /* try pre-loading library with 'require' module loading system. */
      lua_getglobal(L, "require");
      lua_pushstring(L, filename);
      lua_pushboolean(L, 1);
      lua_call(L, 2, 1);
      if (lua_iscfunction(L, -1)) { /* make sure it is not a C-Function. */
        lua_pop(L, 1);
        lua_pushfstring(L, "\nCan't preload C module: '%s'\n", filename);
        lua_concat(L, 2);  /* accumulate with error from luaL_findfile */
        fatal(lua_tostring(L,-1));
      }
      if (!lua_isfunction(L, -1)) { /* did we get an error? */
        lua_pushliteral(L, "\n");
        lua_concat(L, 3);  /* accumulate with error from luaL_findfile */
        fatal(lua_tostring(L,-1));
      } else {
        lua_remove(L, -2); /* remove error from luaL_findfile. */
      }
    } else {
      /* convert filename into package name. */
      p= filename + strlen(filename);
      for(;p >= filename; p--) {
        if(p[0] == '.') { /* Remove file extension. */
          p[0] = '\0';
          continue;
        }
        if(p[0] == '/') { /* Remove file path. */
          preload_libs[i] = p+1;
          break;
        }
      }
    }
  }
  /* generate a new Lua function to combine all of the compiled scripts. */
  f=combine(L, scripts);
  if (listing) luaU_print(f,listing>1);
  if (c_code && !parse_only) {
    FILE* D= (output==NULL) ? stdout : fopen(output,"wb");
    if (D==NULL) cannot("open");
    lua_lock(L);
    slua_dumper_dump(D, output, L, f, stripping);
    lua_unlock(L);
    if (ferror(D)) cannot("write");
    if (fclose(D)) cannot("close");
  }
  if (dumping && !parse_only) {
    FILE* D= (output==NULL) ? stdout : fopen(output,"wb");
    if (D==NULL) cannot("open");
    lua_lock(L);
    luaU_dump(L,f,writer,D,stripping);
    lua_unlock(L);
    if (ferror(D)) cannot("write");
    if (fclose(D)) cannot("close");
  }
  return 0;
}
コード例 #5
0
ファイル: uart_dev_imx.c プロジェクト: 2asoft/freebsd
static int
imx_uart_rxready(struct uart_bas *bas)
{

	return ((IS(bas, USR2, RDR)) ? 1 : 0);
}
コード例 #6
0
ファイル: alert.c プロジェクト: bruce2008github/monit
/**
 * Notify registred users about the event
 * @param E An Event object
 * @return If failed, return HANDLER_ALERT flag or HANDLER_SUCCEEDED if succeeded
 */
int handle_alert(Event_T E) {
  Service_T s;
  int rv = HANDLER_SUCCEEDED;

  ASSERT(E);

  s= Event_get_source(E);
  if(!s) {
    LogError("Aborting alert\n");
    return rv;
  }

  if(s->maillist || Run.maillist) {
    Mail_T m;
    Mail_T n;
    Mail_T list= NULL;
    /*
     * Build a mail-list with local recipients that has registered interest
     * for this event.
     */
    for(m= s->maillist; m; m= m->next) {
      
      if(
        /* particular event notification type is allowed for given recipient */
        IS_EVENT_SET(m->events, Event_get_id(E)) &&
        (
          /* state change notification is sent always */
          E->state_changed       ||
          /* in the case that the state is failed for more cycles we check
           * whether we should send the reminder */
          (E->state && m->reminder && E->count % m->reminder == 0)
        )
      )
      {
        Mail_T tmp= NULL;

        NEW(tmp);
        copy_mail(tmp, m);
        substitute(&tmp, E);
        replace_bare_linefeed(&tmp);
        tmp->next= list;
        list= tmp;

        DEBUG("%s notification is sent to %s\n", Event_get_description(E), m->to);

      }

    }

    /*
     * Build a mail-list with global recipients that has registered interest
     * for this event. Recipients which are defined in the service localy
     * overrides the same recipient events which are registered globaly.
     */
    for(m= Run.maillist; m; m= m->next) {
      int skip= FALSE;

      for(n= s->maillist; n; n= n->next) {
        if(IS(m->to, n->to)) {
          skip= TRUE;
          break;
        }
      }

      if(
        /* the local service alert definition has not overrided the global one */
        !skip &&
        /* particular event notification type is allowed for given recipient */
        IS_EVENT_SET(m->events, Event_get_id(E)) &&
        (
          /* state change notification is sent always */
          E->state_changed       ||
          /* in the case that the state is failed for more cycles we check
           * whether we should send the reminder */
          (E->state && m->reminder && E->count % m->reminder == 0)
        )
      )
      {

        Mail_T tmp= NULL;

        NEW(tmp);
        copy_mail(tmp, m);
        substitute(&tmp, E);
        replace_bare_linefeed(&tmp);
        tmp->next= list;
        list= tmp;

        DEBUG("%s notification is sent to %s\n", Event_get_description(E), m->to);

      }

    }

    if(list) {

      if(!sendmail(list))
        rv = HANDLER_ALERT;
      gc_mail_list(&list);

    }

  }

  return rv;

}
コード例 #7
0
ファイル: esil.c プロジェクト: djpohly/radare2
static int emulate (RAnalEsil *c, char *buf, int *tkns) {
	ut64 num = 0;
	char *op = NULL;
	char *str;
	int i, type;
	c->opstack = r_list_new ();
	c->stack = r_list_new ();
	c->opsize = 0;
	c->rightside = 0;
	for (i=0; tkns[i]; i+=2) {
		TOKEN_GET (type, str);
		eprintf ("(%d) (%s)\n", type, str);

		switch (type) {
		// case 0 handled in for conditional
		case 1: /* special command */
			if (!strcmp (str, "[")) {
				int curstack = r_list_length (c->stack);
eprintf ("STACK POINTER %d\n", curstack);
				c->opsize = (int)num;
				// TODO: test for size
				// read tokens until ']'
				// TOKEN_UNTIL (1, "]");
				for (i+=2; tkns[i]; i+=2) {
					TOKEN_GET (type, str);
					eprintf ("--- %d (%s)\n", tkns[i], buf+tkns[i+1]);
					switch (tkns[i]) {
					case 1:
						if (!strcmp (str, "]")) {
							if (!c->opsize) c->opsize = 
								c->anal->bits==64?8:4;
							//int j, len = r_list_length (c->stack) - curstack;
							char *a;
							OPUSH (op);
							while ((a = OPOP ())) {
								// eprintf ("---> op %s\n", op);
								esil_commit (c, a);
							}
							//op = NULL;
							printf ("   %s (size %d)\n", c->rightside?"GET":"SET", (int)num);
							goto dungeon;
							// set destination for write
							// expect '='
						}
						break;
					case 2:
						op = str;
						OPUSH (op);
						break;
					case 3:
						PUSH (str);
						break;
					}
				}
				if (!tkns[i]) {
					printf ("Unexpected eof\n");
					return 1;
				}
			} else
			if (!strcmp (str, "?")) {
				printf ("   CONDITIONAL\n");
				i += 2;
				TOKEN_GET (type, str);
				if (!type) {
					eprintf ("   UNEXPECTED EOF\n");
					return 1;
				}
				if (type!=3) {
					printf ("   UNEXPECTED TOKEN\n");
					return 1;
				}
				//while () { i += 2; }
			}
			break;
		case 2:
			if (op) {
				//eprintf (" XXX Redefine op %s\n", op);
				if (!strcmp (op, "*")) { // prio
					esil_commit (c, op);
				} else OPUSH (op);
			}
			op = str;
			if (IS ("=")) {
				c->rightside = 1;
			}
			break;
		case 3:
			num = c->num (c, str); // 
	//		eprintf ("; push %s\n" , str);
			PUSH (str);
			break;
		case 4:
			esil_commit (c, op);
			op = NULL;
			break;
		case 5:
// newcontext();
			//esil_push_scope (c);
			eprintf ("OPEN SCOPE\n");
			break;
		case 6:
			{
			//char *res = esil_pop_scope (c);
			// if scope > 0 : 
			//PUSH (res);
			esil_commit (c, op);
			// free (res);
			// commit()
			// closecontext()
			// push result
			eprintf ("CLOSE SCOPE\n");
			}
			break;
		}
		dungeon:
		{/*trick*/int/*label*/x/*parsing*/=/*fix*/0;}
	}
	eprintf (";;; COMMIT (%s) (%s)\n", op, str);
	esil_commit (c, op);
	if (r_list_length (c->opstack)>0) {
		char *a;
		while ((a = OPOP ())) {
			esil_commit (c, a);
		}
	}
	op = NULL;
	return 0;
}
コード例 #8
0
ファイル: cvt_data.c プロジェクト: bambooeric/ia32rtools
static const struct parsed_proto *check_var(FILE *fhdr,
  const char *sym, const char *varname)
{
  const struct parsed_proto *pp, *pp_sym;
  char fp_sym[256], fp_var[256], *p;
  int i;

  pp = proto_parse(fhdr, varname, 1);
  if (pp == NULL) {
    if (IS_START(varname, "sub_"))
      awarn("sub_ sym missing proto: '%s'\n", varname);
    return NULL;
  }

  if (!pp->is_func && !pp->is_fptr)
    return NULL;

  pp_print(fp_var, sizeof(fp_var), pp);

  if (pp->argc_reg == 0)
    goto check_sym;
  if (pp->argc_reg == 1 && pp->argc_stack == 0
    && IS(pp->arg[0].reg, "ecx"))
  {
    goto check_sym;
  }
  if (!g_cconv_novalidate
    && (pp->argc_reg != 2
       || !IS(pp->arg[0].reg, "ecx")
       || !IS(pp->arg[1].reg, "edx")))
  {
    awarn("unhandled reg call: %s\n", fp_var);
  }

check_sym:
  // fptrs must use 32bit args, callsite might have no information and
  // lack a cast to smaller types, which results in incorrectly masked
  // args passed (callee may assume masked args, it does on ARM)
  for (i = 0; i < pp->argc; i++) {
    if (pp->arg[i].type.is_ptr)
      continue;
    p = pp->arg[i].type.name;
    if (strstr(p, "int8") || strstr(p, "int16")
      || strstr(p, "char") || strstr(p, "short"))
    {
      awarn("reference to %s with arg%d '%s'\n", pp->name, i + 1, p);
    }
  }

  sprint_pp_short(pp, g_comment, sizeof(g_comment));

  if (sym != NULL) {
    g_func_sym_pp = NULL;
    pp_sym = proto_parse(fhdr, sym, 1);
    if (pp_sym == NULL)
      return pp;
    if (!pp_sym->is_fptr)
      aerr("func ptr data, but label '%s' !is_fptr\n", pp_sym->name);
    g_func_sym_pp = pp_sym;
  }
  else {
    pp_sym = g_func_sym_pp;
    if (pp_sym == NULL)
      return pp;
  }

  if (pp_cmp_func(pp, pp_sym)) {
    pp_print(fp_sym, sizeof(fp_sym), pp_sym);
    anote("var: %s\n", fp_var);
    anote("sym: %s\n", fp_sym);
    awarn("^ mismatch\n");
  }

  return pp;
}
コード例 #9
0
ファイル: cvt_data.c プロジェクト: bambooeric/ia32rtools
int main(int argc, char *argv[])
{
  FILE *fout, *fasm, *fhdr = NULL, *frlist;
  const struct parsed_proto *pp;
  int no_decorations = 0;
  char comment_char = '#';
  char words[20][256];
  char word[256];
  char line[256];
  char last_sym[32];
  unsigned long val;
  unsigned long cnt;
  const char *sym;
  enum dx_type type;
  char **pub_syms;
  int pub_sym_cnt = 0;
  int pub_sym_alloc;
  char **rlist;
  int rlist_cnt = 0;
  int rlist_alloc;
  int header_mode = 0;
  int is_ro = 0;
  int is_label;
  int is_bss;
  int wordc;
  int first;
  int arg_out;
  int arg = 1;
  int len;
  int w, i;
  char *p;
  char *p2;

  if (argc < 4) {
    // -nd: no symbol decorations
    printf("usage:\n%s [-nd] [-i] [-a] <.s> <.asm> <hdrf> [rlist]*\n"
           "%s -hdr <.h> <.asm>\n",
      argv[0], argv[0]);
    return 1;
  }

  for (arg = 1; arg < argc; arg++) {
    if (IS(argv[arg], "-nd"))
      no_decorations = 1;
    else if (IS(argv[arg], "-i"))
      g_cconv_novalidate = 1;
    else if (IS(argv[arg], "-a")) {
      comment_char = '@';
      g_arm_mode = 1;
    }
    else if (IS(argv[arg], "-hdr"))
      header_mode = 1;
    else
      break;
  }

  arg_out = arg++;

  asmfn = argv[arg++];
  fasm = fopen(asmfn, "r");
  my_assert_not(fasm, NULL);

  if (!header_mode) {
    hdrfn = argv[arg++];
    fhdr = fopen(hdrfn, "r");
    my_assert_not(fhdr, NULL);
  }

  fout = fopen(argv[arg_out], "w");
  my_assert_not(fout, NULL);

  pub_sym_alloc = 64;
  pub_syms = malloc(pub_sym_alloc * sizeof(pub_syms[0]));
  my_assert_not(pub_syms, NULL);

  rlist_alloc = 64;
  rlist = malloc(rlist_alloc * sizeof(rlist[0]));
  my_assert_not(rlist, NULL);

  for (; arg < argc; arg++) {
    frlist = fopen(argv[arg], "r");
    my_assert_not(frlist, NULL);

    while (my_fgets(line, sizeof(line), frlist)) {
      p = sskip(line);
      if (*p == 0 || *p == ';')
        continue;

      p = next_word(words[0], sizeof(words[0]), p);
      if (words[0][0] == 0)
        continue;

      if (rlist_cnt >= rlist_alloc) {
        rlist_alloc = rlist_alloc * 2 + 64;
        rlist = realloc(rlist, rlist_alloc * sizeof(rlist[0]));
        my_assert_not(rlist, NULL);
      }
      rlist[rlist_cnt++] = strdup(words[0]);
    }

    fclose(frlist);
    frlist = NULL;
  }

  if (rlist_cnt > 0)
    qsort(rlist, rlist_cnt, sizeof(rlist[0]), cmpstringp);

  qsort(unwanted_syms, ARRAY_SIZE(unwanted_syms),
    sizeof(unwanted_syms[0]), cmpstringp);

  last_sym[0] = 0;

  while (1) {
    next_section(fasm, line);
    if (feof(fasm))
      break;
    if (IS(line + 1, "text"))
      continue;

    if (IS(line + 1, "rdata")) {
      is_ro = 1;
      if (!header_mode)
        fprintf(fout, "\n.section .rodata\n");
    }
    else if (IS(line + 1, "data")) {
      is_ro = 0;
      if (!header_mode)
        fprintf(fout, "\n.data\n");
    }
    else
      aerr("unhandled section: '%s'\n", line);

    if (!header_mode)
      fprintf(fout, ".align %d\n", align_value(4));

    while (my_fgets(line, sizeof(line), fasm))
    {
      sym = NULL;
      asmln++;

      p = sskip(line);
      if (*p == 0)
        continue;

      if (*p == ';') {
        if (IS_START(p, ";org") && sscanf(p + 5, "%Xh", &i) == 1) {
          // ;org is only seen at section start, so assume . addr 0
          i &= 0xfff;
          if (i != 0 && !header_mode)
            fprintf(fout, "\t\t  .skip 0x%x\n", i);
        }
        continue;
      }

      for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
        p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
        if (*p == 0 || *p == ';') {
          wordc++;
          break;
        }
        if (*p == ',') {
          p = sskip(p + 1);
        }
      }

      if (*p == ';') {
        p = sskip(p + 1);
        if (IS_START(p, "sctclrtype"))
          g_func_sym_pp = NULL;
      }

      if (wordc == 2 && IS(words[1], "ends"))
        break;
      if (wordc <= 2 && IS(words[0], "end"))
        break;
      if (wordc < 2)
        aerr("unhandled: '%s'\n", words[0]);

      // don't cares
      if (IS(words[0], "assume"))
        continue;

      if (IS(words[0], "align")) {
        if (header_mode)
          continue;

        val = parse_number(words[1]);
        fprintf(fout, "\t\t  .align %d", align_value(val));
        goto fin;
      }

      w = 1;
      type = parse_dx_directive(words[0]);
      if (type == DXT_UNSPEC) {
        type = parse_dx_directive(words[1]);
        sym = words[0];
        w = 2;
      }
      if (type == DXT_UNSPEC)
        aerr("unhandled decl: '%s %s'\n", words[0], words[1]);

      if (sym != NULL)
      {
        if (header_mode) {
          int is_str = 0;

          fprintf(fout, "extern ");
          if (is_ro)
            fprintf(fout, "const ");

          switch (type) {
          case DXT_BYTE:
            for (i = w; i < wordc; i++)
              if (words[i][0] == '\'')
                is_str = 1;
            if (is_str)
              fprintf(fout, "char     %s[];\n", sym);
            else
              fprintf(fout, "uint8_t  %s;\n", sym);
            break;

          case DXT_WORD:
            fprintf(fout, "uint16_t %s;\n", sym);
            break;

          case DXT_DWORD:
            fprintf(fout, "uint32_t %s;\n", sym);
            break;

          default:
            fprintf(fout, "_UNKNOWN %s;\n", sym);
            break;
          }

          continue;
        }

        snprintf(last_sym, sizeof(last_sym), "%s", sym);

        pp = proto_parse(fhdr, sym, 1);
        if (pp != NULL) {
          g_func_sym_pp = NULL;

          // public/global name
          if (pub_sym_cnt >= pub_sym_alloc) {
            pub_sym_alloc *= 2;
            pub_syms = realloc(pub_syms, pub_sym_alloc * sizeof(pub_syms[0]));
            my_assert_not(pub_syms, NULL);
          }
          pub_syms[pub_sym_cnt++] = strdup(sym);
        }

        len = strlen(sym);
        fprintf(fout, "%s%s:", no_decorations ? "" : "_", sym);

        len += 2;
        if (len < 8)
          fprintf(fout, "\t");
        if (len < 16)
          fprintf(fout, "\t");
        if (len <= 16)
          fprintf(fout, "  ");
        else
          fprintf(fout, " ");
      }
      else {
        if (header_mode)
          continue;

        fprintf(fout, "\t\t  ");
      }

      // fill out some unwanted strings with zeroes..
      if (type == DXT_BYTE && words[w][0] == '\''
        && is_unwanted_sym(last_sym))
      {
        len = 0;
        for (; w < wordc; w++) {
          if (words[w][0] == '\'') {
            p = words[w] + 1;
            for (; *p && *p != '\''; p++)
              len++;
          }
          else {
            // assume encoded byte
            len++;
          }
        }
        fprintf(fout, ".skip %d", len);
        goto fin;
      }
      else if (type == DXT_BYTE
        && (words[w][0] == '\''
            || (w + 1 < wordc && words[w + 1][0] == '\'')))
      {
        // string; use asciz for most common case
        if (w == wordc - 2 && IS(words[w + 1], "0")) {
          fprintf(fout, ".asciz \"");
          wordc--;
        }
        else
          fprintf(fout, ".ascii \"");

        for (; w < wordc; w++) {
          if (words[w][0] == '\'') {
            p = words[w] + 1;
            p2 = strchr(p, '\'');
            if (p2 == NULL)
              aerr("unterminated string? '%s'\n", p);
            memcpy(word, p, p2 - p);
            word[p2 - p] = 0;
            fprintf(fout, "%s", escape_string(word));
          }
          else {
            val = parse_number(words[w]);
            if (val & ~0xff)
              aerr("bad string trailing byte?\n");
            // unfortunately \xHH is unusable - gas interprets
            // things like \x27b as 0x7b, so have to use octal here
            fprintf(fout, "\\%03lo", val);
          }
        }
        fprintf(fout, "\"");
        goto fin;
      }

      if (w == wordc - 2) {
        if (IS_START(words[w + 1], "dup(")) {
          cnt = parse_number(words[w]);
          p = words[w + 1] + 4;
          p2 = strchr(p, ')');
          if (p2 == NULL)
            aerr("bad dup?\n");
          memmove(word, p, p2 - p);
          word[p2 - p] = 0;

          val = 0;
          if (!IS(word, "?"))
            val = parse_number(word);

          fprintf(fout, ".fill 0x%02lx,%d,0x%02lx",
            cnt, type_size(type), val);
          goto fin;
        }
      }

      if (type == DXT_DWORD && words[w][0] == '\''
        && words[w][5] == '\'' && strlen(words[w]) == 6)
      {
        if (w != wordc - 1)
          aerr("TODO\n");

        p = words[w];
        val = (p[1] << 24) | (p[2] << 16) | (p[3] << 8) | p[4];
        fprintf(fout, ".long 0x%lx", val);
        snprintf(g_comment, sizeof(g_comment), "%s", words[w]);
        goto fin;
      }

      if (type >= DXT_DWORD && strchr(words[w], '.'))
      {
        if (w != wordc - 1)
          aerr("TODO\n");

        if (g_arm_mode && type == DXT_TEN) {
          fprintf(fout, ".fill 10");
          snprintf(g_comment, sizeof(g_comment), "%s %s",
            type_name_float(type), words[w]);
        }
        else
          fprintf(fout, "%s %s", type_name_float(type), words[w]);
        goto fin;
      }

      first = 1;
      fprintf(fout, "%s ", type_name(type));
      for (; w < wordc; w++)
      {
        if (!first)
          fprintf(fout, ", ");

        is_label = is_bss = 0;
        if (w <= wordc - 2 && IS(words[w], "offset")) {
          is_label = 1;
          w++;
        }
        else if (IS(words[w], "?")) {
          is_bss = 1;
        }
        else if (type == DXT_DWORD
                 && !('0' <= words[w][0] && words[w][0] <= '9'))
        {
          // assume label
          is_label = 1;
        }

        if (is_bss) {
          fprintf(fout, "0");
        }
        else if (is_label) {
          p = words[w];
          if (IS_START(p, "loc_") || IS_START(p, "__imp")
             || strchr(p, '?') || strchr(p, '@')
             || bsearch(&p, rlist, rlist_cnt, sizeof(rlist[0]),
                  cmpstringp))
          {
            fprintf(fout, "0");
            snprintf(g_comment, sizeof(g_comment), "%s", p);
          }
          else {
            pp = check_var(fhdr, sym, p);
            if (pp == NULL) {
              fprintf(fout, "%s%s",
                (no_decorations || p[0] == '_') ? "" : "_", p);
            }
            else {
              if (no_decorations)
                fprintf(fout, "%s", pp->name);
              else
                output_decorated_pp(fout, pp);
            }
          }
        }
        else {
          val = parse_number(words[w]);
          if (val < 10)
            fprintf(fout, "%ld", val);
          else
            fprintf(fout, "0x%lx", val);
        }

        first = 0;
      }

fin:
      if (g_comment[0] != 0) {
        fprintf(fout, "\t\t%c %s", comment_char, g_comment);
        g_comment[0] = 0;
      }
      fprintf(fout, "\n");
    }
  }

  fprintf(fout, "\n");

  // dump public syms
  for (i = 0; i < pub_sym_cnt; i++)
    fprintf(fout, ".global %s%s\n",
      no_decorations ? "" : "_", pub_syms[i]);

  fclose(fout);
  fclose(fasm);
  if (fhdr != NULL)
    fclose(fhdr);

  return 0;
}
コード例 #10
0
bool ShieldDiceDragHandler::dragEnded(ActionDiceDragData* data,
                                      GameplayLayer* layer,
                                      DockableContainer* dockableContainer) {
  auto docked = false;
  
  auto sprite = data->getSprite();
  auto touch = data->getTouch();
  
  for (auto node : layer->getChildren()) {
    if (IS(node, ActionDiceSprite)) {
      auto diceSprite = (ActionDiceSprite*) node;
      auto dice = diceSprite->getDice();
      
      if (DiceUtil::isSwordDice(dice)) {
        auto rect = node->getBoundingBox();
        
        if (rect.containsPoint(touch->getLocation())) {
          node->setColor(Color3B::WHITE);
          
          auto swordAndShield = DiceFace::create(IMG_DICE_ACTION_SWORD_AND_SHIELD);
          dice->setSelectedFace(swordAndShield, false);
          
          docked = true;
          break;
        }
      }
    }
  }
  
  auto game = Game::getInstance();
  if (game->getDamageTaken() > 0) {
    auto character = game->getPlayer()->getCharacter();
    auto characterSprite = character->getSprite();
    
    auto rect = characterSprite->getBoundingBox();
    if (rect.containsPoint(touch->getLocation())) {
      auto turn = game->getTurn();
      if (IS(turn, PlayerTurn)) {
        auto playerTurn = (PlayerTurn*) turn;
        playerTurn->protectDamage(1);
      }
      docked = true;
    }
    
    auto scene = (GameplayScene*) layer->getScene();
    auto dungeonLayer = scene->getDungeonLayer();
    
    auto dungeonRoom = dungeonLayer->getRoomSpriteForCharacterCoordinate();
    
    characterSprite->setLocalZOrder(CHARACTER_DICE_Z_ORDER);
    characterSprite->setColor(Color3B::WHITE);
    
    auto position = characterSprite->getPosition() +
        Vec2(TILE_DIMENSION / 2, TILE_DIMENSION / 2) -
        dungeonRoom->getPosition() -
        dungeonLayer->getParent()->getPosition();
    characterSprite->setPosition(position);
    
    characterSprite->retain();
    characterSprite->removeFromParent();
    dungeonRoom->addChild(characterSprite);
    characterSprite->release();
  }
  
  if (docked) {
    layer->dockActionDice(sprite);
  }
  
  return docked;
}
コード例 #11
0
ファイル: restore_variable.c プロジェクト: Sluggy/SluggyMUD
 foreach (x, y in values) {
 IS(x, y);
 }
コード例 #12
0
ファイル: lexruler.c プロジェクト: Pendrokar/ilmentufa
token *GIhEK_root_991_1()
	{
	INIT;
	IS(GIhA_541);
	RETURN;
	}
コード例 #13
0
ファイル: id3tag.c プロジェクト: FLYKingdom/vlc
static void ParseAPEvXTag( demux_meta_t *p_demux_meta, const uint8_t *p_data, int i_data )
{
    vlc_meta_t       *p_meta;
    bool b_start;
    bool b_end;
    const uint8_t *p_header = NULL;
    int i_entry;

    if( i_data < APE_TAG_HEADERSIZE )
        return;

    b_start = !strncmp( (char*)&p_data[0], "APETAGEX", 8 );
    b_end = !strncmp( (char*)&p_data[i_data-APE_TAG_HEADERSIZE], "APETAGEX", 8 );
    if( !b_end && !b_start )
        return;

    if( !p_demux_meta->p_meta )
        p_demux_meta->p_meta = vlc_meta_New();
    p_meta = p_demux_meta->p_meta;

    if( b_start )
    {
        p_header = &p_data[0];
        p_data += APE_TAG_HEADERSIZE;
        i_data -= APE_TAG_HEADERSIZE;
    }
    if( b_end )
    {
        p_header = &p_data[i_data-APE_TAG_HEADERSIZE];
        i_data -= APE_TAG_HEADERSIZE;
    }
    if( i_data <= 0 )
        return;

    i_entry = GetDWLE( &p_header[8+4+4] );
    if( i_entry <= 0 )
        return;

    while( i_entry > 0 && i_data >= 10 )
    {
        const int i_size = GetDWLE( &p_data[0] );
        const uint32_t flags = GetDWLE( &p_data[4] );
        char psz_name[256];
        int n;

        strlcpy( psz_name, (char*)&p_data[8], sizeof(psz_name) );
        n = strlen( psz_name );
        if( n <= 0 )
            break;

        p_data += 8+n+1;
        i_data -= 8+n+1;
        if( i_data < i_size )
            break;

        /* Retreive UTF-8 fields only */
        if( ((flags>>1) & 0x03) == 0x00 )
        {
            /* FIXME list are separated by '\0' */
            char *psz_value = strndup( (char*)&p_data[0], i_size );

            EnsureUTF8( psz_name );
            EnsureUTF8( psz_value );
#define IS(s) (!strcasecmp( psz_name, s ) )
            if( IS( "Title" ) )
                vlc_meta_SetTitle( p_meta, psz_value );
            else  if( IS( "Artist" ) )
                vlc_meta_SetArtist( p_meta, psz_value );
            else  if( IS( "Album" ) )
                vlc_meta_SetAlbum( p_meta, psz_value );
            else  if( IS( "Publisher" ) )
                vlc_meta_SetPublisher( p_meta, psz_value );
            else  if( IS( "Track" ) )
            {
                char *p = strchr( psz_value, '/' );
                if( p )
                    *p++ = '\0';
                vlc_meta_SetTrackNum( p_meta, psz_value );
            }
            else  if( IS( "Comment" ) )
                vlc_meta_SetDescription( p_meta, psz_value );
            else  if( IS( "Copyright" ) )
                vlc_meta_SetCopyright( p_meta, psz_value );
            else  if( IS( "Year" ) )
                vlc_meta_SetDate( p_meta, psz_value );
            else  if( IS( "Genre" ) )
                vlc_meta_SetGenre( p_meta, psz_value );
            else  if( IS( "Language" ) )
                vlc_meta_SetLanguage( p_meta, psz_value );
            else
                vlc_meta_AddExtra( p_meta, psz_name, psz_value );
#undef IS
            free( psz_value );
        }

        p_data += i_size;
        i_data -= i_size;
        i_entry--;
    }
}
コード例 #14
0
ファイル: pool.c プロジェクト: SteffenBaresel/id2sc
static void testPool(const char *testURL) {
        URL_T url;
        char *schema;
        ConnectionPool_T pool;
        char *data[]= {"Fry", "Leela", "Bender", "Farnsworth",
                "Zoidberg", "Amy", "Hermes", "Nibbler", "Cubert",
                "Zapp", "Joey Mousepad", "ЯΣ༆", 0}; 
        
        if (Str_startsWith(testURL, "mysql")) {
                schema = SCHEMA_MYSQL;
        } else if (Str_startsWith(testURL, "postgresql")) {
                schema = SCHEMA_POSTGRESQL;
        } else if (Str_startsWith(testURL, "sqlite")) {
                schema = SCHEMA_SQLITE;
        } else if (Str_startsWith(testURL, "oracle")) {
                schema = SCHEMA_ORACLE;
        }
        else {
                printf("Unsupported database protocol\n");
                exit(1);
        }

        printf("=> Test1: create/destroy\n");
        {
                pool = ConnectionPool_new(URL_new(testURL));
                assert(pool);
                url = ConnectionPool_getURL(pool);
                ConnectionPool_free(&pool);
                assert(! pool);
                URL_free(&url);
        }
        printf("=> Test1: OK\n\n");
        
        printf("=> Test2: NULL value\n");
        {
                url = URL_new(NULL);
                assert(! url);
                pool = ConnectionPool_new(url);
                assert(! pool);
        }
        printf("=> Test2: OK\n\n");
        
        printf("=> Test3: start/stop\n");
        {
                url = URL_new(testURL);
                pool = ConnectionPool_new(url);
                assert(pool);
                ConnectionPool_start(pool);
                ConnectionPool_stop(pool);
                ConnectionPool_free(&pool);
                assert(pool==NULL);
                URL_free(&url);
                // Test that exception is thrown on start error
                TRY
                {
                        url = URL_new("not://a/database");
                        pool = ConnectionPool_new(url);
                        assert(pool);
                        ConnectionPool_start(pool);
                        printf("\tResult: Test failed -- exception not thrown\n");
                        exit(1);
                }
                CATCH(SQLException) {
                        // OK
                }
                FINALLY {
                        ConnectionPool_free(&pool);
                        assert(pool==NULL);
                        URL_free(&url);
                }
                END_TRY;
        }
        printf("=> Test3: OK\n\n");
        
        printf("=> Test4: Connection execute & transaction\n");
        {
                int i;
                Connection_T con;
                url = URL_new(testURL);
                pool = ConnectionPool_new(url);
                assert(pool);
                ConnectionPool_setAbortHandler(pool, TabortHandler);
                ConnectionPool_start(pool);
                con = ConnectionPool_getConnection(pool);
                assert(con);
                TRY Connection_execute(con, "drop table zild_t;"); ELSE END_TRY;
                Connection_execute(con, "%s", schema);
                Connection_beginTransaction(con);
                /* Insert values into database and assume that auto increment of id works */
                for (i = 0; data[i]; i++) 
                        Connection_execute(con, "insert into zild_t (name, percent) values('%s', %d.%d);", data[i], i+1, i);
                // Assert that the last insert statement added one row
                assert(Connection_rowsChanged(con) == 1);
                /* Assert that last row id works for MySQL and SQLite. Neither Oracle nor PostgreSQL
                 support last row id directly. The way to do this in PostgreSQL is to use 
                 currval() or return the id on insert. */
                if (IS(URL_getProtocol(url), "sqlite") || IS(URL_getProtocol(url), "mysql")) 
                        assert(Connection_lastRowId(con) == 12);
                Connection_commit(con);
                printf("\tResult: table zild_t successfully created\n");
                Connection_close(con);
        }
        printf("=> Test4: OK\n\n");     
        
        
        printf("=> Test5: Prepared Statement\n");
        {
                int i;
                char blob[8192];
                char *images[]= {"Ceci n'est pas une pipe", "Mona Lisa",
                        "Bryllup i Hardanger", "The Scream",
                        "Vampyre", "Balcony", "Cycle", "Day & Night", 
                        "Hand with Reflecting Sphere",
                        "Drawing Hands", "Ascending and Descending", 0}; 
                Connection_T con = ConnectionPool_getConnection(pool);
                assert(con);
                // 1. Prepared statement, perform a nonsense update to test rowsChanged
                PreparedStatement_T p1 = Connection_prepareStatement(con, "update zild_t set image=?;");
                PreparedStatement_setString(p1, 1, "");
                PreparedStatement_execute(p1);
                printf("\tRows changed: %lld\n", PreparedStatement_rowsChanged(p1));
                // Assert that all 12 rows in the data set was changed
                assert(PreparedStatement_rowsChanged(p1) == 12);
                // 2. Prepared statement, update the table proper with "images". 
                PreparedStatement_T pre = Connection_prepareStatement(con, "update zild_t set image=? where id=?;");
                assert(pre);
                for (i = 0; images[i]; i++) {
                        PreparedStatement_setBlob(pre, 1, images[i], (int)strlen(images[i])+1);
                        PreparedStatement_setInt(pre, 2, i + 1);
                        PreparedStatement_execute(pre);
                }
                // The last execute changed one row only
                assert(PreparedStatement_rowsChanged(pre) == 1);
                /* Add a database null blob value */
                PreparedStatement_setBlob(pre, 1, NULL, 0);
                PreparedStatement_setInt(pre, 2, 5);
                PreparedStatement_execute(pre);
                /* Add a database null string value */
                PreparedStatement_setString(pre, 1, NULL);
                PreparedStatement_setInt(pre, 2, 1);
                PreparedStatement_execute(pre);
                /* Add a large blob */
                memset(blob, 'x', 8192);
                blob[8191] = 0;
                /* Mark start and end */
                *blob='S'; blob[8190] = 'E';
                PreparedStatement_setBlob(pre, 1, blob, 8192);
                PreparedStatement_setInt(pre, 2, i + 1);
                PreparedStatement_execute(pre);
                printf("\tResult: prepared statement successfully executed\n");
                Connection_close(con);
        }
        printf("=> Test5: OK\n\n");     
        
        
        printf("=> Test6: Result Sets\n");
        {
                int i;
                int imagesize = 0;
                Connection_T con;
                ResultSet_T rset;
                ResultSet_T names;
                PreparedStatement_T pre;
                con = ConnectionPool_getConnection(pool);
                assert(con);
                rset = Connection_executeQuery(con, "select id, name, percent, image from zild_t where id < %d order by id;", 100);
                assert(rset);
                printf("\tResult:\n");
                printf("\tNumber of columns in resultset: %d\n\t", ResultSet_getColumnCount(rset));
                assert(4==ResultSet_getColumnCount(rset));
                i = 1;
                printf("%-5s", ResultSet_getColumnName(rset, i++));
                printf("%-16s", ResultSet_getColumnName(rset, i++));
                printf("%-10s", ResultSet_getColumnName(rset, i++));
                printf("%-16s", ResultSet_getColumnName(rset, i++));
                printf("\n\t------------------------------------------------------\n");
                while (ResultSet_next(rset)) {
                        int id = ResultSet_getIntByName(rset, "id");
                        const char *name = ResultSet_getString(rset, 2);
                        double percent = ResultSet_getDoubleByName(rset, "percent");
                        const char *blob = (char*)ResultSet_getBlob(rset, 4, &imagesize);
                        printf("\t%-5d%-16s%-10.2f%-16.38s\n", id, name ? name : "null", percent, imagesize ? blob : "");
                }
                rset = Connection_executeQuery(con, "select image from zild_t where id=12;");
                assert(1==ResultSet_getColumnCount(rset));
                // Assert that types are interchangeable (to some degree) and that all data is returned
                while (ResultSet_next(rset)) {
                        const char *image = ResultSet_getStringByName(rset, "image");
                        const void *blob = ResultSet_getBlobByName(rset, "image", &imagesize);
                        assert(image && blob);
                        assert(strlen(image) + 1 == 8192);
                        assert(imagesize == 8192);
                }
                printf("\tResult: check max rows..");
                Connection_setMaxRows(con, 3);
                rset = Connection_executeQuery(con, "select id from zild_t;");
                assert(rset);
                i = 0;
                while (ResultSet_next(rset)) i++;
                assert((i)==3);
                printf("success\n");
                printf("\tResult: check prepared statement resultset..");
                Connection_setMaxRows(con, 0);
                pre = Connection_prepareStatement(con, "select name from zild_t where id=?");
                assert(pre);
                PreparedStatement_setInt(pre, 1, 2);
                names = PreparedStatement_executeQuery(pre);
                assert(names);
                assert(ResultSet_next(names));
                assert(Str_isEqual("Leela", ResultSet_getString(names, 1)));
                printf("success\n");
                printf("\tResult: check prepared statement re-execute..");
                PreparedStatement_setInt(pre, 1, 1);
                names = PreparedStatement_executeQuery(pre);
                assert(names);
                assert(ResultSet_next(names));
                assert(Str_isEqual("Fry", ResultSet_getString(names, 1)));
                printf("success\n");
                printf("\tResult: check prepared statement without in-params..");
                pre = Connection_prepareStatement(con, "select name from zild_t;");
                assert(pre);
                names = PreparedStatement_executeQuery(pre);
                assert(names);
                for (i = 0; ResultSet_next(names); i++);
                assert(i==12);
                printf("success\n");
                /* Need to close and release statements before
                   we can drop the table, sqlite need this */
                Connection_clear(con);
                Connection_execute(con, "drop table zild_t;");
                Connection_close(con);
                ConnectionPool_stop(pool);
                ConnectionPool_free(&pool);
                assert(pool==NULL);
                URL_free(&url);
        }
        printf("=> Test6: OK\n\n");
        
        
        printf("=> Test7: reaper start/stop\n");
        {
                int i;
                Vector_T v = Vector_new(20);
                url = URL_new(testURL);
                pool = ConnectionPool_new(url);
                assert(pool);
                ConnectionPool_setInitialConnections(pool, 4);
                ConnectionPool_setMaxConnections(pool, 20);
                ConnectionPool_setConnectionTimeout(pool, 4);
                ConnectionPool_setReaper(pool, 4);
                ConnectionPool_setAbortHandler(pool, TabortHandler);
                ConnectionPool_start(pool);
                assert(4==ConnectionPool_size(pool));
                printf("Creating 20 Connections..");
                for (i = 0; i<20; i++)
                        Vector_push(v, ConnectionPool_getConnection(pool));
                assert(ConnectionPool_size(pool) == 20);
                assert(ConnectionPool_active(pool) == 20);
                printf("success\n");
                printf("Closing Connections down to initial..");
                while (! Vector_isEmpty(v))
                        Connection_close(Vector_pop(v));
                assert(ConnectionPool_active(pool) == 0);
                assert(ConnectionPool_size(pool) == 20);
                printf("success\n");
                printf("Please wait 10 sec for reaper to harvest closed connections..");
                Connection_T con = ConnectionPool_getConnection(pool); // Activate one connection to verify the reaper does not close any active
                fflush(stdout);
                sleep(10);
                assert(5 == ConnectionPool_size(pool)); // 4 initial connections + the one active we got above
                assert(1 == ConnectionPool_active(pool));
                printf("success\n");
                Connection_close(con);
                ConnectionPool_stop(pool);
                ConnectionPool_free(&pool);
                Vector_free(&v);
                assert(pool==NULL);
                URL_free(&url);
        }
        printf("=> Test7: OK\n\n");

        printf("=> Test8: Exceptions handling\n");
        {
                int i;
                Connection_T con;
                ResultSet_T result;
                url = URL_new(testURL);
                pool = ConnectionPool_new(url);
                assert(pool);
                ConnectionPool_setAbortHandler(pool, TabortHandler);
                ConnectionPool_start(pool);
                con = ConnectionPool_getConnection(pool);
                assert(con);
                /* 
                 * The following should work without throwing exceptions 
                 */
                TRY
                {
                        Connection_execute(con, "%s", schema);
                }
                ELSE
                {
                        printf("\tResult: Creating table zild_t failed -- %s\n", Exception_frame.message);
                        assert(false); // Should not fail
                }
                END_TRY;
                TRY
                {
                        Connection_beginTransaction(con);
                        for (i = 0; data[i]; i++) 
                                Connection_execute(con, "insert into zild_t (name, percent) values('%s', %d.%d);", data[i], i+1, i);
                        Connection_commit(con);
                        printf("\tResult: table zild_t successfully created\n");
                }
                ELSE
                {
                        printf("\tResult: Test failed -- %s\n", Exception_frame.message);
                        assert(false); // Should not fail
                }
                FINALLY
                {
                        Connection_close(con);
                }
                END_TRY;
                assert((con = ConnectionPool_getConnection(pool)));
                TRY
                {
                        int i, j;
                        const char *bg[]= {"Starbuck", "Sharon Valerii",
                                "Number Six", "Gaius Baltar", "William Adama",
                                "Lee \"Apollo\" Adama", "Laura Roslin", 0};
                        PreparedStatement_T p = Connection_prepareStatement
                        (con, "insert into zild_t (name) values(?);");
                        /* If we did not get a statement, an SQLException is thrown
                           and we will not get here. So we can safely use the 
                           statement now. Likewise, below, we do not have to 
                           check return values from the statement since any error
                           will throw an SQLException and transfer the control
                           to the exception handler
                        */
                        for (i = 0, j = 42; bg[i]; i++, j++) {
                                PreparedStatement_setString(p, 1, bg[i]);
                                PreparedStatement_execute(p);
                        }
                }
                CATCH(SQLException)
                {
                        printf("\tResult: prepare statement failed -- %s\n", Exception_frame.message);
                        assert(false);
                }
                END_TRY;
                TRY
                {
                        printf("\t\tBattlestar Galactica: \n");
                        result = Connection_executeQuery(con, "select name from zild_t where id > 12;");
                        while (ResultSet_next(result))
                                printf("\t\t%s\n", ResultSet_getString(result, 1));
                }
                CATCH(SQLException)
                {
                        printf("\tResult: resultset failed -- %s\n", Exception_frame.message);
                       assert(false);
                }
                FINALLY
                {
                        Connection_close(con);
                }
                END_TRY;
                /* 
                 * The following should fail and throw exceptions. The exception error 
                 * message can be obtained with Exception_frame.message, or from 
                 * Connection_getLastError(con). Exception_frame.message contains both
                 * SQL errors or api errors such as prepared statement parameter index
                 * out of range, while Connection_getLastError(con) only has SQL errors
                 */
                TRY
                {
                        assert((con = ConnectionPool_getConnection(pool)));
                        Connection_execute(con, "%s", schema);
                        /* Creating the table again should fail and we 
                        should not come here */
                        printf("\tResult: Test failed -- exception not thrown\n");
                        exit(1);
                }
                CATCH(SQLException)
                {
                        Connection_close(con);
                }
                END_TRY;
                TRY
                {
                        assert((con = ConnectionPool_getConnection(pool)));
                        printf("\tTesting: Query with errors.. ");
                        Connection_executeQuery(con, "blablabala;");
                        printf("\tResult: Test failed -- exception not thrown\n");
                        exit(1);
                }
                CATCH(SQLException)
                {
                        printf("ok\n");
                        Connection_close(con);
                }
                END_TRY;
                TRY
                {
                        printf("\tTesting: Prepared statement query with errors.. ");
                        assert((con = ConnectionPool_getConnection(pool)));
                        PreparedStatement_T p = Connection_prepareStatement(con, "blablabala;");
                        ResultSet_T r = PreparedStatement_executeQuery(p);
                        while(ResultSet_next(r));
                        printf("\tResult: Test failed -- exception not thrown\n");
                        exit(1);
                }
                CATCH(SQLException)
                {
                        printf("ok\n");
                        Connection_close(con);
                }
                END_TRY;
                TRY
                {
                        assert((con = ConnectionPool_getConnection(pool)));
                        printf("\tTesting: Column index out of range.. ");
                        result = Connection_executeQuery(con, "select id, name from zild_t;");
                        while (ResultSet_next(result)) {
                                int id = ResultSet_getInt(result, 1);  
                                const char *name = ResultSet_getString(result, 2);
                                /* So far so good, now, try access an invalid
                                   column, which should throw an SQLException */
                                int bogus = ResultSet_getInt(result, 3);
                                printf("\tResult: Test failed -- exception not thrown\n");
                                printf("%d, %s, %d", id, name, bogus);
                                exit(1);
                        }
                }
                CATCH(SQLException)
                {
                        printf("ok\n");
                        Connection_close(con);
                }
                END_TRY;
                TRY
                {
                        assert((con = ConnectionPool_getConnection(pool)));
                        printf("\tTesting: Invalid column name.. ");
                        result = Connection_executeQuery(con, "select name from zild_t;");
                        while (ResultSet_next(result)) {
                                const char *name = ResultSet_getStringByName(result, "nonexistingcolumnname");
                                printf("%s", name);
                                printf("\tResult: Test failed -- exception not thrown\n");
                                exit(1);
                        }
                }
                CATCH(SQLException)
                {
                        printf("ok\n");
                        Connection_close(con);
                }
                END_TRY;
                TRY
                {
                        assert((con = ConnectionPool_getConnection(pool)));
                        PreparedStatement_T p = Connection_prepareStatement(con, "update zild_t set name = ? where id = ?;");
                        printf("\tTesting: Parameter index out of range.. ");
                        PreparedStatement_setInt(p, 3, 123);
                        printf("\tResult: Test failed -- exception not thrown\n");
                        exit(1);
                }
                CATCH(SQLException)
                {
                        printf("ok\n");
                }
                FINALLY
                {
                        Connection_close(con);
                }
                END_TRY;
                assert((con = ConnectionPool_getConnection(pool)));
                Connection_execute(con, "drop table zild_t;");
                Connection_close(con);
                ConnectionPool_stop(pool);
                ConnectionPool_free(&pool);
                assert(pool==NULL);
                URL_free(&url);
        }
        printf("=> Test8: OK\n\n");
        
        printf("=> Test9: Ensure Capacity\n");
        {
                /* Check that MySQL ensureCapacity works for columns that exceed the preallocated buffer and that no truncation is done */
                if ( Str_startsWith(testURL, "mysql")) {
                        int myimagesize;
                        url = URL_new(testURL);
                        pool = ConnectionPool_new(url);
                        assert(pool);
                        ConnectionPool_start(pool);
                        Connection_T con = ConnectionPool_getConnection(pool);
                        assert(con);
                        Connection_execute(con, "CREATE TABLE zild_t(id INTEGER AUTO_INCREMENT PRIMARY KEY, image BLOB, string TEXT);");
                        PreparedStatement_T p = Connection_prepareStatement(con, "insert into zild_t (image, string) values(?, ?);");
                        char t[4096];
                        memset(t, 'x', 4096);
                        t[4095] = 0;
                        for (int i = 0; i < 4; i++) {
                                PreparedStatement_setBlob(p, 1, t, (i+1)*512); // store successive larger string-blobs to trigger realloc on ResultSet_getBlobByName
                                PreparedStatement_setString(p, 2, t);
                                PreparedStatement_execute(p);
                        }
                        ResultSet_T r = Connection_executeQuery(con, "select image, string from zild_t;");
                        for (int i = 0; ResultSet_next(r); i++) {
                                ResultSet_getBlobByName(r, "image", &myimagesize);
                                const char *image = ResultSet_getStringByName(r, "image"); // Blob as image should be terminated
                                const char *string = ResultSet_getStringByName(r, "string");
                                assert(myimagesize == (i+1)*512);
                                assert(strlen(image) == ((i+1)*512));
                                assert(strlen(string) == 4095);
                        }
                        p = Connection_prepareStatement(con, "select image, string from zild_t;");
                        r = PreparedStatement_executeQuery(p);
                        for (int i = 0; ResultSet_next(r); i++) {
                                ResultSet_getBlobByName(r, "image", &myimagesize);
                                const char *image = ResultSet_getStringByName(r, "image");
                                const char *string = (char*)ResultSet_getStringByName(r, "string");
                                assert(myimagesize == (i+1)*512);
                                assert(strlen(image) == ((i+1)*512));
                                assert(strlen(string) == 4095);
                        }
                        Connection_execute(con, "drop table zild_t;");
                        Connection_close(con);
                        ConnectionPool_stop(pool);
                        ConnectionPool_free(&pool);
                        URL_free(&url);
                }
        }
        printf("=> Test9: OK\n\n");

        printf("============> Connection Pool Tests: OK\n\n");
}
コード例 #15
0
ファイル: VA_B_B_ST.C プロジェクト: ktf/sherpa
void ST::CalcFFs(Vec4D p0, Vec4D p1)
{
    Vec4D v0 = p0/m0;
    Vec4D v1 = p1/m1;
    double w = v0*v1;

    double aaprime = 0.5*(a+ap);

    double I;
    double amap(0.0);
    switch(m_mode) {
    case 0:
        // Lambda_x (1/2+) -> Lambda_y or N (1/2+)
        I = IS(w, 1.0, 1.5, 2.0);
        m_V1 = I*(1.0+msigma/aaprime*(ap/mq+a/mQ));
        m_V2 = -I*(msigma*ap/mq/aaprime-a*ap/6.0/mq/mQ);
        m_V3 = -I*msigma*a/mQ/aaprime;
        m_A1 = I*(1.0-a*ap/18.0/mq/mQ);
        m_A2 = -I*(msigma*ap/mq/aaprime+4.0*sqr(msigma)*a*ap/5.0/mq/mQ/sqr(aaprime)+a*ap/18.0/mq/mQ);
        m_A3 = I*(msigma*a/mQ/aaprime+4.0*sqr(msigma)*a*ap/5.0/mq/mQ/sqr(aaprime));
        break;
    case 1:
        // Lambda_x (1/2+) -> Lambda_y or N (1/2-)
        I = IS(w, sqrt(2.0), 2.5, 3.0);
        m_V1 = I*aaprime/12.0*(3.0/mq-1.0/mQ);
        m_V2 = -I*(2.0*msigma/a-aaprime/4.0/mq+2.0*sqr(msigma)/aaprime/mQ-msigma/12.0/mq/mQ*(5.0*a-3.0*ap));
        m_V3 = I*2.0*sqr(msigma)/mQ/aaprime;
        m_A1 = I*(2.0*msigma/a-aaprime/12.0/mQ+msigma/36.0/mq/mQ*(11.0*a-5.0*ap));
        m_A2 = -I*(2.0*msigma/a-aaprime/4.0/mq-aaprime/6.0/mQ+msigma/18.0/mq/mQ*(a-ap));
        m_A3 = I*aaprime/6.0/mQ*(1.0+msigma/2.0/mq/aaprime*(ap-3.0*a));
        break;
    case 2:
        // Lambda_x (1/2+) -> Lambda_y or N (1/2+1)
        I = IS(w, sqrt(3.0)/2.0, 2.5, 3.0);
        m_V1 = I/2.0/ap/a*
               (sqr(a)-sqr(ap)-2.0*msigma/3.0*(a/mQ*(5.0*ap-3.0*a)-ap/mq*(5.0*a-3.0*ap)));
        m_V2 = -I*(5.0*a-3.0*ap)/3.0/mq*(msigma/a-aaprime/3.0/mQ);
        m_V3 = I*msigma/6.0/mQ/ap*(5.0*ap-3.0*a);
        m_A1 = I*((sqr(a)-sqr(ap))/2.0/a/ap-aaprime/54.0/mq/mQ*(5.0*a-3.0*ap));
        m_A2 = -I*msigma/3.0/mq/a*
               ((5.0*a-3.0*ap)+4.0*msigma*a/mQ/aaprime*(a-ap)+aaprime/18.0/mQ*(5.0*a-ap));
        m_A3 = -I*msigma/3.0/mQ/ap*
               ((5.0*ap-3.0*a)-4.0*msigma*ap/mQ/aaprime*(a-ap));
        break;
    case 10:
        // Omega_x (1/2+) -> Omega_y or Xi (1/2+ |200000>)
        I = IS(w, 1.0/3.0, 1.5, 2.0);
        m_V1 = -I*(1.0+msigma/aaprime*(ap/mq+a/mQ));
        m_V2 = 2.0*I*(1.0-msigma/aaprime*(ap/2.0/mq-a/mQ));
        m_V3 = 2.0*I*(1.0+msigma/aaprime*(ap/mq-a/2.0/mQ));
        m_A1 = -I;
        m_A2 = I*msigma*ap/mq/aaprime;
        m_A3 = -I*msigma*a/mQ/aaprime;
        break;
    case 11: {
        // Omega_x (1/2+) -> Omega_y or Xi (1/2+1 |200010>)
        I = IS(w, 1.0/2.0/sqrt(3.0), 2.5, 3.0);
        amap = sqr(a)-sqr(ap);
        m_V1 = -I/2.0/a/ap*(amap+2.0*msigma/3.0*(ap*(5.0*a-3.0*ap)/mq+a*(3.0*a-5.0*ap)/mQ));
        m_V2 = I/a/ap*(amap-2.0*msigma/3.0*(ap*(5.0*a-3.0*ap)/2.0/mq-a*(3.0*a-5.0*ap)/mQ));
        m_V3 = I/a/ap*(amap+2.0*msigma/3.0*(ap*(5.0*a-3.0*ap)/mq-a*(3.0*a-5.0*ap)/2.0/mQ));
        m_A1 = -I*amap/2.0/a/ap;
        m_A2 = I*msigma/3.0/mq*(5.0*a-3.0*ap)/a;
        m_A3 = -I*msigma/3.0/mQ*(3.0*a-5.0*ap)/ap;
        break;
    }
    case 12:
        // Omega_x (1/2+) -> Omega_y or Xi (1/2+2 |320002>)
        I = IS(w, -4.0/9.0*sqrt(5.0), 3.5, 4.0);
        m_V1 = -I*msigma*aaprime/2.0/a*(1.0/mq-1.0/mQ);
        m_V2 = -0.5*m_V1;
        m_V3 = m_V2;
        m_A1 = 0.0;
        m_A2 = I*msigma/a*(27.0*msigma/5.0/a-aaprime/4.0*(4.0/mq+3.0/mQ));
        m_A3 = -I*msigma/a*(27.0*msigma/5.0/a+aaprime/4.0/mQ);
        break;
    case 13:
        // Omega_x (1/2+) -> Omega_y or Xi (1/2- |210001>)
        I = IS(w, -sqrt(2.0)/3.0, 2.5, 3.0);
        m_V1 = -I*aaprime/12.0*(1.0/mq+5.0/mQ);
        m_V2 = I*(2.0*msigma/a*(1.0-msigma/aaprime*(2.0*ap/mq-a/mQ))-aaprime/12.0/mq);
        m_V3 = I*4.0*msigma/a*(1.0+msigma/aaprime*(ap/mq-a/2.0/mQ));
        m_A1 = I*(2.0*msigma/a-5.0*aaprime/12.0/mQ);
        m_A2 = -I*(2.0*msigma/a-aaprime*(1.0/4.0/mq+1.0/3.0/mQ));
        m_A3 = I*aaprime/3.0/mQ;
        break;
    case 14:
        // Omega_x (1/2+) -> Omega_y or Xi (1/2-1 |310001>)
        I = IS(w, -2.0/3.0, 2.5, 3.0);
        m_V1 = -I*aaprime/6.0*(1.0/mq-1.0/mQ);
        m_V2 = I*(msigma/a*(1.0+msigma/aaprime*(ap/mq+a/mQ))-aaprime/6.0/mq);
        m_V3 = -I*msigma/a*(1.0+msigma/aaprime*(ap/mq+a/mQ));
        m_A1 = -I*(2.0*msigma/a-aaprime/6.0/mQ);
        m_A2 = -I*(msigma/a-aaprime/6.0*(3.0/mq+1.0/mQ));
        m_A3 = I*(3.0*msigma/a+aaprime/6.0/mQ);
        break;
    default:
        THROW(fatal_error,"Mode not implemented in HO::CalcFFs.");
    }
    m_calced = true;
}
コード例 #16
0
ファイル: RadDBClient.cpp プロジェクト: MSoft1115/Rad3D
		rdbc::packet * GetResult()
		{
			while (Valid())
			{
				rdbc::pk_head head;

				// skip compact
				char compact[RDBC_PACK_COMPACT_SIZE + 1];
				if (IStream()->Read(compact, RDBC_PACK_COMPACT_SIZE) == 0)
					break;

				compact[RDBC_PACK_COMPACT_SIZE] = 0;
				if (strcmp(compact, RDBC_PACK_COMPACT) != 0)
				{
					d_assert(0);
					d_log("packet compact error");
					Close(0);
					break;
				}

				int skip = RDBC_PACK_COMPACT_SIZE;

				// read packet head
				if (IStream()->Read(&head, sizeof(head)) == 0)
				{
					IStream()->Skip(-skip);
					break;
				}

				skip += sizeof(head);

				// encrypt head
				if (M != 0)
				{
					rdbc::encrypt((char *)&head, sizeof(head), K, sizeof(K));
				}

				int length = head.length & 0x7FFFFFFF;
				if (length <= 0 || length > RDBC_PACK_MAX_SIZE)
				{
					d_log("packet size invalid, id %d, size %d", head.id, head.length);
					Close(0);
					break;
				}

				// read data
				char buffer[RDBC_PACK_MAX_SIZE];
				if (IStream()->Read(buffer, length) == 0)
				{
					IStream()->Skip(-skip);
					break;
				}

				char * data = buffer;
				static_memory buffer2;

				if (head.length & 0x80000000)
				{
					buffer2.query(RDBC_STATIC_MEMORY_CHANEL, RDBC_PACK_MAX_SIZE);

					length = Math::RLE8_Decode((byte *)buffer2.data(), RDBC_PACK_MAX_SIZE, (const byte *)buffer, length);
					if (length < 0)
					{
						d_log("packet uncompress error, '%d'", head.id);
						Close(0);
						break;
					}

					data = (char *)buffer2.data();
				}

				ISerializerM IS((byte *)data, length, false);

				rdbc::packet * pk = Root::Instance()->NEW_OBJECT_T<rdbc::packet>(head.id);
				if (pk == NULL)
				{
					d_log("packet unregister '%d'", head.id);
					Close(0);
					break;
				}

				pk->Serialize(IS);

				buffer2.free();

				return pk;
			}

			return NULL;
		}
コード例 #17
0
/*
 * Places the device in and out of reset and then places sane
 * values in the registers based on EEPROM config, initialization
 * vectors (as determined by the mode), and station configuration
 *
 * bChannelChange is used to preserve DMA/PCU registers across
 * a HW Reset during channel change.
 */
HAL_BOOL
ar5312Reset(struct ath_hal *ah, HAL_OPMODE opmode,
	HAL_CHANNEL *chan, HAL_BOOL bChannelChange, HAL_STATUS *status)
{
#define	N(a)	(sizeof (a) / sizeof (a[0]))
#define	FAIL(_code)	do { ecode = _code; goto bad; } while (0)
	struct ath_hal_5212 *ahp = AH5212(ah);
	HAL_CHANNEL_INTERNAL *ichan;
	const HAL_EEPROM *ee;
	uint32_t saveFrameSeqCount, saveDefAntenna;
	uint32_t macStaId1, synthDelay, txFrm2TxDStart;
	uint16_t rfXpdGain[MAX_NUM_PDGAINS_PER_CHANNEL];
	int16_t cckOfdmPwrDelta = 0;
	u_int modesIndex, freqIndex;
	HAL_STATUS ecode;
	int i, regWrites = 0;
	uint32_t testReg;
	uint32_t saveLedState = 0;

	HALASSERT(ah->ah_magic == AR5212_MAGIC);
	ee = AH_PRIVATE(ah)->ah_eeprom;

	OS_MARK(ah, AH_MARK_RESET, bChannelChange);
#define	IS(_c,_f)	(((_c)->channelFlags & _f) || 0)
	if ((IS(chan, CHANNEL_2GHZ) ^ IS(chan, CHANNEL_5GHZ)) == 0) {
		HALDEBUG(ah, HAL_DEBUG_ANY,
		    "%s: invalid channel %u/0x%x; not marked as 2GHz or 5GHz\n",
		    __func__, chan->channel, chan->channelFlags);
		FAIL(HAL_EINVAL);
	}
	if ((IS(chan, CHANNEL_OFDM) ^ IS(chan, CHANNEL_CCK)) == 0) {
		HALDEBUG(ah, HAL_DEBUG_ANY,
		    "%s: invalid channel %u/0x%x; not marked as OFDM or CCK\n",
		    __func__, chan->channel, chan->channelFlags);
		FAIL(HAL_EINVAL);
	}
#undef IS
	/*
	 * Map public channel to private.
	 */
	ichan = ath_hal_checkchannel(ah, chan);
	if (ichan == AH_NULL) {
		HALDEBUG(ah, HAL_DEBUG_ANY,
		    "%s: invalid channel %u/0x%x; no mapping\n",
		    __func__, chan->channel, chan->channelFlags);
		FAIL(HAL_EINVAL);
	}
	switch (opmode) {
	case HAL_M_STA:
	case HAL_M_IBSS:
	case HAL_M_HOSTAP:
	case HAL_M_MONITOR:
		break;
	default:
		HALDEBUG(ah, HAL_DEBUG_ANY, "%s: invalid operating mode %u\n",
		    __func__, opmode);
		FAIL(HAL_EINVAL);
		break;
	}
	HALASSERT(ahp->ah_eeversion >= AR_EEPROM_VER3);

	/* Preserve certain DMA hardware registers on a channel change */
	if (bChannelChange) {
		/*
		 * On Venice, the TSF is almost preserved across a reset;
		 * it requires the doubling writes to the RESET_TSF
		 * bit in the AR_BEACON register; it also has the quirk
		 * of the TSF going back in time on the station (station
		 * latches onto the last beacon's tsf during a reset 50%
		 * of the times); the latter is not a problem for adhoc
		 * stations since as long as the TSF is behind, it will
		 * get resynchronized on receiving the next beacon; the
		 * TSF going backwards in time could be a problem for the
		 * sleep operation (supported on infrastructure stations
		 * only) - the best and most general fix for this situation
		 * is to resynchronize the various sleep/beacon timers on
		 * the receipt of the next beacon i.e. when the TSF itself
		 * gets resynchronized to the AP's TSF - power save is
		 * needed to be temporarily disabled until that time
		 *
		 * Need to save the sequence number to restore it after
		 * the reset!
		 */
		saveFrameSeqCount = OS_REG_READ(ah, AR_D_SEQNUM);
	} else
		saveFrameSeqCount = 0;		/* NB: silence compiler */

	/* If the channel change is across the same mode - perform a fast channel change */
	if ((IS_2413(ah) || IS_5413(ah))) {
		/*
		 * Channel change can only be used when:
		 *  -channel change requested - so it's not the initial reset.
		 *  -it's not a change to the current channel - often called when switching modes
		 *   on a channel
		 *  -the modes of the previous and requested channel are the same - some ugly code for XR
		 */
		if (bChannelChange &&
		    (AH_PRIVATE(ah)->ah_curchan != AH_NULL) &&
		    (chan->channel != AH_PRIVATE(ah)->ah_curchan->channel) &&
		    ((chan->channelFlags & CHANNEL_ALL) ==
		     (AH_PRIVATE(ah)->ah_curchan->channelFlags & CHANNEL_ALL))) {
			if (ar5212ChannelChange(ah, chan))
				/* If ChannelChange completed - skip the rest of reset */
				return AH_TRUE;
		}
	}

	/*
	 * Preserve the antenna on a channel change
	 */
	saveDefAntenna = OS_REG_READ(ah, AR_DEF_ANTENNA);
	if (saveDefAntenna == 0)		/* XXX magic constants */
		saveDefAntenna = 1;

	/* Save hardware flag before chip reset clears the register */
	macStaId1 = OS_REG_READ(ah, AR_STA_ID1) & 
		(AR_STA_ID1_BASE_RATE_11B | AR_STA_ID1_USE_DEFANT);

	/* Save led state from pci config register */
	if (!IS_5315(ah))
		saveLedState = OS_REG_READ(ah, AR5312_PCICFG) &
			(AR_PCICFG_LEDCTL | AR_PCICFG_LEDMODE | AR_PCICFG_LEDBLINK |
			 AR_PCICFG_LEDSLOW);

	ar5312RestoreClock(ah, opmode);		/* move to refclk operation */

	/*
	 * Adjust gain parameters before reset if
	 * there's an outstanding gain updated.
	 */
	(void) ar5212GetRfgain(ah);

	if (!ar5312ChipReset(ah, chan)) {
		HALDEBUG(ah, HAL_DEBUG_ANY, "%s: chip reset failed\n", __func__);
		FAIL(HAL_EIO);
	}

	/* Setup the indices for the next set of register array writes */
	switch (chan->channelFlags & CHANNEL_ALL) {
	case CHANNEL_A:
		modesIndex = 1;
		freqIndex  = 1;
		break;
	case CHANNEL_T:
		modesIndex = 2;
		freqIndex  = 1;
		break;
	case CHANNEL_B:
		modesIndex = 3;
		freqIndex  = 2;
		break;
	case CHANNEL_PUREG:
		modesIndex = 4;
		freqIndex  = 2;
		break;
	case CHANNEL_108G:
		modesIndex = 5;
		freqIndex  = 2;
		break;
	default:
		HALDEBUG(ah, HAL_DEBUG_ANY, "%s: invalid channel flags 0x%x\n",
		    __func__, chan->channelFlags);
		FAIL(HAL_EINVAL);
	}

	OS_MARK(ah, AH_MARK_RESET_LINE, __LINE__);

	/* Set correct Baseband to analog shift setting to access analog chips. */
	OS_REG_WRITE(ah, AR_PHY(0), 0x00000007);

	regWrites = ath_hal_ini_write(ah, &ahp->ah_ini_modes, modesIndex, 0);
	regWrites = write_common(ah, &ahp->ah_ini_common, bChannelChange,
		regWrites);
	ahp->ah_rfHal->writeRegs(ah, modesIndex, freqIndex, regWrites);

	OS_MARK(ah, AH_MARK_RESET_LINE, __LINE__);

	if (IS_CHAN_HALF_RATE(chan) || IS_CHAN_QUARTER_RATE(chan)) {
		ar5212SetIFSTiming(ah, chan);
	}

	/* Overwrite INI values for revised chipsets */
	if (AH_PRIVATE(ah)->ah_phyRev >= AR_PHY_CHIP_ID_REV_2) {
		/* ADC_CTL */
		OS_REG_WRITE(ah, AR_PHY_ADC_CTL,
			     SM(2, AR_PHY_ADC_CTL_OFF_INBUFGAIN) |
			     SM(2, AR_PHY_ADC_CTL_ON_INBUFGAIN) |
			     AR_PHY_ADC_CTL_OFF_PWDDAC |
			     AR_PHY_ADC_CTL_OFF_PWDADC);
		
		/* TX_PWR_ADJ */
		if (chan->channel == 2484) {
			cckOfdmPwrDelta = SCALE_OC_DELTA(ee->ee_cckOfdmPwrDelta - ee->ee_scaledCh14FilterCckDelta);
		} else {
			cckOfdmPwrDelta = SCALE_OC_DELTA(ee->ee_cckOfdmPwrDelta);
		}
		
		if (IS_CHAN_G(chan)) {
			OS_REG_WRITE(ah, AR_PHY_TXPWRADJ,
				     SM((ee->ee_cckOfdmPwrDelta*-1), AR_PHY_TXPWRADJ_CCK_GAIN_DELTA) |
				     SM((cckOfdmPwrDelta*-1), AR_PHY_TXPWRADJ_CCK_PCDAC_INDEX));
		} else {
			OS_REG_WRITE(ah, AR_PHY_TXPWRADJ, 0);
		}
		
		/* Add barker RSSI thresh enable as disabled */
		OS_REG_CLR_BIT(ah, AR_PHY_DAG_CTRLCCK,
			       AR_PHY_DAG_CTRLCCK_EN_RSSI_THR);
		OS_REG_RMW_FIELD(ah, AR_PHY_DAG_CTRLCCK,
				 AR_PHY_DAG_CTRLCCK_RSSI_THR, 2);
		
		/* Set the mute mask to the correct default */
		OS_REG_WRITE(ah, AR_SEQ_MASK, 0x0000000F);
	}
	
	if (AH_PRIVATE(ah)->ah_phyRev >= AR_PHY_CHIP_ID_REV_3) {
		/* Clear reg to alllow RX_CLEAR line debug */
		OS_REG_WRITE(ah, AR_PHY_BLUETOOTH,  0);
	}
	if (AH_PRIVATE(ah)->ah_phyRev >= AR_PHY_CHIP_ID_REV_4) {
#ifdef notyet
		/* Enable burst prefetch for the data queues */
		OS_REG_RMW_FIELD(ah, AR_D_FPCTL, ... );
		/* Enable double-buffering */
		OS_REG_CLR_BIT(ah, AR_TXCFG, AR_TXCFG_DBL_BUF_DIS);
#endif
	}

	if (IS_5312_2_X(ah)) {
		/* ADC_CTRL */
		OS_REG_WRITE(ah, AR_PHY_SIGMA_DELTA,
			     SM(2, AR_PHY_SIGMA_DELTA_ADC_SEL) |
			     SM(4, AR_PHY_SIGMA_DELTA_FILT2) |
			     SM(0x16, AR_PHY_SIGMA_DELTA_FILT1) |
			     SM(0, AR_PHY_SIGMA_DELTA_ADC_CLIP));

		if (IS_CHAN_2GHZ(chan))
			OS_REG_RMW_FIELD(ah, AR_PHY_RXGAIN, AR_PHY_RXGAIN_TXRX_RF_MAX, 0x0F);

		/* CCK Short parameter adjustment in 11B mode */
		if (IS_CHAN_B(chan))
			OS_REG_RMW_FIELD(ah, AR_PHY_CCK_RXCTRL4, AR_PHY_CCK_RXCTRL4_FREQ_EST_SHORT, 12);

		/* Set ADC/DAC select values */
		OS_REG_WRITE(ah, AR_PHY_SLEEP_SCAL, 0x04);

		/* Increase 11A AGC Settling */
		if ((chan->channelFlags & CHANNEL_ALL) == CHANNEL_A)
			OS_REG_RMW_FIELD(ah, AR_PHY_SETTLING, AR_PHY_SETTLING_AGC, 32);
	} else {
		/* Set ADC/DAC select values */
		OS_REG_WRITE(ah, AR_PHY_SLEEP_SCAL, 0x0e);
	}

	/* Setup the transmit power values. */
	if (!ar5212SetTransmitPower(ah, ichan, rfXpdGain)) {
		HALDEBUG(ah, HAL_DEBUG_ANY,
		    "%s: error init'ing transmit power\n", __func__);
		FAIL(HAL_EIO);
	}

	/* Write the analog registers */
	if (!ahp->ah_rfHal->setRfRegs(ah, ichan, modesIndex, rfXpdGain)) {
		HALDEBUG(ah, HAL_DEBUG_ANY, "%s: ar5212SetRfRegs failed\n",
		    __func__);
		FAIL(HAL_EIO);
	}

	/* Write delta slope for OFDM enabled modes (A, G, Turbo) */
	if (IS_CHAN_OFDM(chan)) {
		if ((IS_5413(ah) || (AH_PRIVATE(ah)->ah_eeversion >= AR_EEPROM_VER5_3)) &&
		    (!IS_CHAN_B(chan)))
			ar5212SetSpurMitigation(ah, ichan);
		ar5212SetDeltaSlope(ah, chan);
	}

	/* Setup board specific options for EEPROM version 3 */
	if (!ar5212SetBoardValues(ah, ichan)) {
		HALDEBUG(ah, HAL_DEBUG_ANY,
		    "%s: error setting board options\n", __func__);
		FAIL(HAL_EIO);
	}

	/* Restore certain DMA hardware registers on a channel change */
	if (bChannelChange)
		OS_REG_WRITE(ah, AR_D_SEQNUM, saveFrameSeqCount);

	OS_MARK(ah, AH_MARK_RESET_LINE, __LINE__);

	OS_REG_WRITE(ah, AR_STA_ID0, LE_READ_4(ahp->ah_macaddr));
	OS_REG_WRITE(ah, AR_STA_ID1, LE_READ_2(ahp->ah_macaddr + 4)
		| macStaId1
		| AR_STA_ID1_RTS_USE_DEF
		| ahp->ah_staId1Defaults
	);
	ar5212SetOperatingMode(ah, opmode);

	/* Set Venice BSSID mask according to current state */
	OS_REG_WRITE(ah, AR_BSSMSKL, LE_READ_4(ahp->ah_bssidmask));
	OS_REG_WRITE(ah, AR_BSSMSKU, LE_READ_2(ahp->ah_bssidmask + 4));

	/* Restore previous led state */
	if (!IS_5315(ah))
		OS_REG_WRITE(ah, AR5312_PCICFG, OS_REG_READ(ah, AR_PCICFG) | saveLedState);

	/* Restore previous antenna */
	OS_REG_WRITE(ah, AR_DEF_ANTENNA, saveDefAntenna);

	/* then our BSSID */
	OS_REG_WRITE(ah, AR_BSS_ID0, LE_READ_4(ahp->ah_bssid));
	OS_REG_WRITE(ah, AR_BSS_ID1, LE_READ_2(ahp->ah_bssid + 4));

	/* Restore bmiss rssi & count thresholds */
	OS_REG_WRITE(ah, AR_RSSI_THR, ahp->ah_rssiThr);

	OS_REG_WRITE(ah, AR_ISR, ~0);		/* cleared on write */

	if (!ar5212SetChannel(ah, ichan))
		FAIL(HAL_EIO);

	OS_MARK(ah, AH_MARK_RESET_LINE, __LINE__);

	ar5212SetCoverageClass(ah, AH_PRIVATE(ah)->ah_coverageClass, 1);

	ar5212SetRateDurationTable(ah, chan);

	/* Set Tx frame start to tx data start delay */
	if (IS_RAD5112_ANY(ah) &&
	    (IS_CHAN_HALF_RATE(AH_PRIVATE(ah)->ah_curchan) ||
	     IS_CHAN_QUARTER_RATE(AH_PRIVATE(ah)->ah_curchan))) {
		txFrm2TxDStart = 
			(IS_CHAN_HALF_RATE(AH_PRIVATE(ah)->ah_curchan)) ?
					TX_FRAME_D_START_HALF_RATE:
					TX_FRAME_D_START_QUARTER_RATE;
		OS_REG_RMW_FIELD(ah, AR_PHY_TX_CTL, 
			AR_PHY_TX_FRAME_TO_TX_DATA_START, txFrm2TxDStart);
	}

	/*
	 * Setup fast diversity.
	 * Fast diversity can be enabled or disabled via regadd.txt.
	 * Default is enabled.
	 * For reference,
	 *    Disable: reg        val
	 *             0x00009860 0x00009d18 (if 11a / 11g, else no change)
	 *             0x00009970 0x192bb514
	 *             0x0000a208 0xd03e4648
	 *
	 *    Enable:  0x00009860 0x00009d10 (if 11a / 11g, else no change)
	 *             0x00009970 0x192fb514
	 *             0x0000a208 0xd03e6788
	 */

	/* XXX Setup pre PHY ENABLE EAR additions */

	/* flush SCAL reg */
	if (IS_5312_2_X(ah)) {
		(void) OS_REG_READ(ah, AR_PHY_SLEEP_SCAL);
	}

	/*
	 * Wait for the frequency synth to settle (synth goes on
	 * via AR_PHY_ACTIVE_EN).  Read the phy active delay register.
	 * Value is in 100ns increments.
	 */
	synthDelay = OS_REG_READ(ah, AR_PHY_RX_DELAY) & AR_PHY_RX_DELAY_DELAY;
	if (IS_CHAN_CCK(chan)) {
		synthDelay = (4 * synthDelay) / 22;
	} else {
		synthDelay /= 10;
	}

	/* Activate the PHY (includes baseband activate and synthesizer on) */
	OS_REG_WRITE(ah, AR_PHY_ACTIVE, AR_PHY_ACTIVE_EN);

	/* 
	 * There is an issue if the AP starts the calibration before
	 * the base band timeout completes.  This could result in the
	 * rx_clear false triggering.  As a workaround we add delay an
	 * extra BASE_ACTIVATE_DELAY usecs to ensure this condition
	 * does not happen.
	 */
	if (IS_CHAN_HALF_RATE(AH_PRIVATE(ah)->ah_curchan)) {
		OS_DELAY((synthDelay << 1) + BASE_ACTIVATE_DELAY);
	} else if (IS_CHAN_QUARTER_RATE(AH_PRIVATE(ah)->ah_curchan)) {
		OS_DELAY((synthDelay << 2) + BASE_ACTIVATE_DELAY);
	} else {
		OS_DELAY(synthDelay + BASE_ACTIVATE_DELAY);
	}

	/*
	 * The udelay method is not reliable with notebooks.
	 * Need to check to see if the baseband is ready
	 */
	testReg = OS_REG_READ(ah, AR_PHY_TESTCTRL);
	/* Selects the Tx hold */
	OS_REG_WRITE(ah, AR_PHY_TESTCTRL, AR_PHY_TESTCTRL_TXHOLD);
	i = 0;
	while ((i++ < 20) &&
	       (OS_REG_READ(ah, 0x9c24) & 0x10)) /* test if baseband not ready */		OS_DELAY(200);
	OS_REG_WRITE(ah, AR_PHY_TESTCTRL, testReg);

	/* Calibrate the AGC and start a NF calculation */
	OS_REG_WRITE(ah, AR_PHY_AGC_CONTROL,
		  OS_REG_READ(ah, AR_PHY_AGC_CONTROL)
		| AR_PHY_AGC_CONTROL_CAL
		| AR_PHY_AGC_CONTROL_NF);

	if (!IS_CHAN_B(chan) && ahp->ah_bIQCalibration != IQ_CAL_DONE) {
		/* Start IQ calibration w/ 2^(INIT_IQCAL_LOG_COUNT_MAX+1) samples */
		OS_REG_RMW_FIELD(ah, AR_PHY_TIMING_CTRL4, 
			AR_PHY_TIMING_CTRL4_IQCAL_LOG_COUNT_MAX,
			INIT_IQCAL_LOG_COUNT_MAX);
		OS_REG_SET_BIT(ah, AR_PHY_TIMING_CTRL4,
			AR_PHY_TIMING_CTRL4_DO_IQCAL);
		ahp->ah_bIQCalibration = IQ_CAL_RUNNING;
	} else
		ahp->ah_bIQCalibration = IQ_CAL_INACTIVE;

	/* Setup compression registers */
	ar5212SetCompRegs(ah);

	/* Set 1:1 QCU to DCU mapping for all queues */
	for (i = 0; i < AR_NUM_DCU; i++)
		OS_REG_WRITE(ah, AR_DQCUMASK(i), 1 << i);

	ahp->ah_intrTxqs = 0;
	for (i = 0; i < AH_PRIVATE(ah)->ah_caps.halTotalQueues; i++)
		ar5212ResetTxQueue(ah, i);

	/*
	 * Setup interrupt handling.  Note that ar5212ResetTxQueue
	 * manipulates the secondary IMR's as queues are enabled
	 * and disabled.  This is done with RMW ops to insure the
	 * settings we make here are preserved.
	 */
	ahp->ah_maskReg = AR_IMR_TXOK | AR_IMR_TXERR | AR_IMR_TXURN
			| AR_IMR_RXOK | AR_IMR_RXERR | AR_IMR_RXORN
			| AR_IMR_HIUERR
			;
	if (opmode == HAL_M_HOSTAP)
		ahp->ah_maskReg |= AR_IMR_MIB;
	OS_REG_WRITE(ah, AR_IMR, ahp->ah_maskReg);
	/* Enable bus errors that are OR'd to set the HIUERR bit */
	OS_REG_WRITE(ah, AR_IMR_S2,
		OS_REG_READ(ah, AR_IMR_S2)
		| AR_IMR_S2_MCABT | AR_IMR_S2_SSERR | AR_IMR_S2_DPERR);

	if (AH_PRIVATE(ah)->ah_rfkillEnabled)
		ar5212EnableRfKill(ah);

	if (!ath_hal_wait(ah, AR_PHY_AGC_CONTROL, AR_PHY_AGC_CONTROL_CAL, 0)) {
		HALDEBUG(ah, HAL_DEBUG_ANY,
		    "%s: offset calibration failed to complete in 1ms;"
		    " noisy environment?\n", __func__);
	}

	/*
	 * Set clocks back to 32kHz if they had been using refClk, then
	 * use an external 32kHz crystal when sleeping, if one exists.
	 */
	ar5312SetupClock(ah, opmode);

	/*
	 * Writing to AR_BEACON will start timers. Hence it should
	 * be the last register to be written. Do not reset tsf, do
	 * not enable beacons at this point, but preserve other values
	 * like beaconInterval.
	 */
	OS_REG_WRITE(ah, AR_BEACON,
		(OS_REG_READ(ah, AR_BEACON) &~ (AR_BEACON_EN | AR_BEACON_RESET_TSF)));

	/* XXX Setup post reset EAR additions */

	/*  QoS support */
	if (AH_PRIVATE(ah)->ah_macVersion > AR_SREV_VERSION_VENICE ||
	    (AH_PRIVATE(ah)->ah_macVersion == AR_SREV_VERSION_VENICE &&
	     AH_PRIVATE(ah)->ah_macRev >= AR_SREV_GRIFFIN_LITE)) {
		OS_REG_WRITE(ah, AR_QOS_CONTROL, 0x100aa);	/* XXX magic */
		OS_REG_WRITE(ah, AR_QOS_SELECT, 0x3210);	/* XXX magic */
	}

	/* Turn on NOACK Support for QoS packets */
	OS_REG_WRITE(ah, AR_NOACK,
		     SM(2, AR_NOACK_2BIT_VALUE) |
		     SM(5, AR_NOACK_BIT_OFFSET) |
		     SM(0, AR_NOACK_BYTE_OFFSET));

	/* Restore user-specified settings */
	if (ahp->ah_miscMode != 0)
		OS_REG_WRITE(ah, AR_MISC_MODE, ahp->ah_miscMode);
	if (ahp->ah_slottime != (u_int) -1)
		ar5212SetSlotTime(ah, ahp->ah_slottime);
	if (ahp->ah_acktimeout != (u_int) -1)
		ar5212SetAckTimeout(ah, ahp->ah_acktimeout);
	if (ahp->ah_ctstimeout != (u_int) -1)
		ar5212SetCTSTimeout(ah, ahp->ah_ctstimeout);
	if (ahp->ah_sifstime != (u_int) -1)
		ar5212SetSifsTime(ah, ahp->ah_sifstime);
	if (AH_PRIVATE(ah)->ah_diagreg != 0)
		OS_REG_WRITE(ah, AR_DIAG_SW, AH_PRIVATE(ah)->ah_diagreg);

	AH_PRIVATE(ah)->ah_opmode = opmode;	/* record operating mode */

	if (bChannelChange) {
		if (!(ichan->privFlags & CHANNEL_DFS)) 
			ichan->privFlags &= ~CHANNEL_INTERFERENCE;
		chan->channelFlags = ichan->channelFlags;
		chan->privFlags = ichan->privFlags;
	}

	HALDEBUG(ah, HAL_DEBUG_RESET, "%s: done\n", __func__);

	OS_MARK(ah, AH_MARK_RESET_DONE, 0);

	return AH_TRUE;
bad:
	OS_MARK(ah, AH_MARK_RESET_DONE, ecode);
	if (*status)
		*status = ecode;
	return AH_FALSE;
#undef FAIL
#undef N
}
コード例 #18
0
ファイル: Main.c プロジェクト: abcsds/pinguino-installers
NSIS_ENTRYPOINT_GUINOCRT
EXTERN_C void NSISWinMainNOCRT()
{
  int ret = 0;
  const TCHAR *m_Err = _LANG_ERRORWRITINGTEMP;

  int cl_flags = 0;

  TCHAR *realcmds;
  TCHAR seekchar=_T(' ');
  TCHAR *cmdline;

  InitCommonControls();

  SetErrorMode(SEM_NOOPENFILEERRORBOX | SEM_FAILCRITICALERRORS);

#if defined(NSIS_SUPPORT_ACTIVEXREG) || defined(NSIS_SUPPORT_CREATESHORTCUT)
  {
    extern HRESULT g_hres;
    g_hres=OleInitialize(NULL);
  }
#endif

  // load shfolder.dll before any script code is executed to avoid
  // weird situations where SetOutPath or even the extraction of 
  // shfolder.dll will cause unexpected behavior.
  //
  // this also prevents the following:
  //
  //  SetOutPath "C:\Program Files\NSIS" # maybe read from reg
  //  File shfolder.dll
  //  Delete $PROGRAMFILES\shfolder.dll # can't be deleted, as the
  //                                    # new shfolder.dll is used
  //                                    # to find its own path.
  g_SHGetFolderPath = myGetProcAddress(MGA_SHGetFolderPath);

  {
    // workaround for bug #1008632
    // http://sourceforge.net/tracker/index.php?func=detail&aid=1008632&group_id=22049&atid=373085
    //
    // without this, SHGetSpecialFolderLocation doesn't always recognize
    // some special folders, like the desktop folder for all users, on
    // Windows 9x. unlike SHGetSpecialFolderPath, which is not available
    // on all versions of Windows, SHGetSpecialFolderLocation doesn't try
    // too hard to make sure the caller gets what he asked for. so we give
    // it a little push in the right direction by doing part of the work
    // for it.
    //
    // part of what SHGetFileInfo does, is to convert a path into an idl.
    // to do this conversion, it first needs to initialize the list of 
    // special idls, which are exactly the idls we use to get the paths
    // of special folders (CSIDL_*).

    SHFILEINFO shfi;
    SHGetFileInfo(_T(""), 0, &shfi, sizeof(SHFILEINFO), 0);
  }

  mystrcpy(g_caption,_LANG_GENERIC_ERROR);

  mystrcpy(state_command_line, GetCommandLine());

#ifdef NSIS_CONFIG_VISIBLE_SUPPORT
  g_hInstance = GetModuleHandle(NULL);
#endif//NSIS_CONFIG_VISIBLE_SUPPORT

  cmdline = state_command_line;
  if (*cmdline == _T('\"')) seekchar = *cmdline++;

  cmdline=findchar(cmdline, seekchar);
  cmdline=CharNext(cmdline);
  realcmds=cmdline;

  while (*cmdline)
  {
    // skip over any spaces
    while (*cmdline == _T(' ')) cmdline++;
    
    // get char we should look for to get the next parm
    seekchar = _T(' ');
    if (cmdline[0] == _T('\"'))
    {
      cmdline++;
      seekchar = _T('\"');
    }

    // is it a switch?
    if (cmdline[0] == _T('/'))
    {
      cmdline++;

#define END_OF_ARG(c) (c == _T(' ') || c == _T('\0'))

#if defined(NSIS_CONFIG_VISIBLE_SUPPORT) && defined(NSIS_CONFIG_SILENT_SUPPORT)
      if (cmdline[0] == _T('S') && END_OF_ARG(cmdline[1]))
        g_exec_flags.silent = 1; // bug #1076 - just set the silent flag. the user really wants it silent.
                                 // loadHeaders() will not reset this as it uses |= to apply the script flags.
                                 // there is also no option to force non-silent like `CRCCheck force`
#endif//NSIS_CONFIG_SILENT_SUPPORT && NSIS_CONFIG_VISIBLE_SUPPORT
#ifdef NSIS_CONFIG_CRC_SUPPORT
      if (CMP4CHAR(cmdline, _T("NCRC")) && END_OF_ARG(cmdline[4]))
        cl_flags |= FH_FLAGS_NO_CRC;
#endif//NSIS_CONFIG_CRC_SUPPORT

      if (CMP4CHAR(cmdline-2, _T(" /D=")))
      {
        *(cmdline-2)=_T('\0'); // keep this from being passed to uninstaller if necessary
        mystrcpy(state_install_directory,cmdline+2);
        break; // /D= must always be last
      }
    }

    // skip over our parm
    cmdline = findchar(cmdline, seekchar);
    // skip the quote
    if (*cmdline == _T('\"'))
      cmdline++;
  }

  GetTempPath(NSIS_MAX_STRLEN, state_temp_dir);
  if (!ValidateTempDir())
  {
    GetWindowsDirectory(state_temp_dir, NSIS_MAX_STRLEN - 5); // leave space for \Temp
    mystrcat(state_temp_dir, _T("\\Temp"));
    if (!ValidateTempDir())
    {
      // Bug #2909242:
      // When running at <= Low IL we cannot write to %Temp% but we can try the temp folder used by IE.
      // There does not seem to be a API to get the low temp dir directly, so we build the path on our own

      GetTempPath(NSIS_MAX_STRLEN - 4, state_temp_dir); // leave space for \Low
      mystrcat(state_temp_dir, _T("Low"));

      // If we don't call SetEnvironmentVariable 
      // child processes will use %temp% and not %temp%\Low
      // and some apps probably can't handle a read only %temp%
      // Do it before ValidateTempDir() because it appends a backslash.
      // TODO: Should this be moved to ValidateTempDir() so it also updates for %windir%\Temp?
      SetEnvironmentVariable(_T("TEMP"), state_temp_dir);
      SetEnvironmentVariable(_T("TMP"), state_temp_dir);

      if (!ValidateTempDir())
      {
        goto end;
      }
    }
  }
  DeleteFile(state_language);

  m_Err = loadHeaders(cl_flags);
  if (m_Err) goto end;

#ifdef NSIS_CONFIG_UNINSTALL_SUPPORT
  if (g_is_uninstaller)
  {
    TCHAR *p = findchar(state_command_line, 0);

    // state_command_line has state_install_directory right after it in memory, so reading
    // a bit over state_command_line won't do any harm
    while (p >= state_command_line && !CMP4CHAR(p, _T(" _?="))) p--;

    m_Err = _LANG_UNINSTINITERROR;

    if (p >= state_command_line)
    {
      *p=0; // terminate before "_?="
      p+=4; // skip over " _?="
      if (is_valid_instpath(p))
      {
        mystrcpy(state_install_directory, p);
        mystrcpy(state_output_directory, p);
        m_Err = 0;
      }
      else
      {
        goto end;
      }
    }
    else
    {
      int x;

      mystrcat(state_temp_dir,_T("~nsu.tmp"));

      // check if already running from uninstaller temp dir
      // this prevents recursive uninstaller calls
      if (!lstrcmpi(state_temp_dir,state_exe_directory))
        goto end;

      CreateDirectory(state_temp_dir,NULL);
      SetCurrentDirectory(state_temp_dir);

      if (!(*state_install_directory))
        mystrcpy(state_install_directory,state_exe_directory);

      mystrcpy(g_usrvars[0], realcmds);
      SET2CHAR(g_usrvars[1], _T("A\0"));

      for (x = 0; x < 26; x ++)
      {
        static TCHAR buf2[NSIS_MAX_STRLEN];

        GetNSISString(buf2,g_header->str_uninstchild); // $TEMP\$1u_.exe

        DeleteFile(buf2); // clean up after all the other ones if they are there

        if (m_Err) // not done yet
        {
          // copy file
          if (CopyFile(state_exe_path,buf2,TRUE))
          {
            HANDLE hProc;
#ifdef NSIS_SUPPORT_MOVEONREBOOT
            MoveFileOnReboot(buf2,NULL);
#endif
            GetNSISString(buf2,g_header->str_uninstcmd); // '"$TEMP\$1u_.exe" $0 _?=$INSTDIR\'
            hProc=myCreateProcess(buf2);
            if (hProc)
            {
              CloseHandle(hProc);
              // success
              m_Err = 0;
            }
          }
        }
        (*(((NSIS_STRING *)g_usrvars)[1]))++;
      }

#ifdef NSIS_SUPPORT_MOVEONREBOOT
      MoveFileOnReboot(state_temp_dir,NULL);
#endif

      goto end;
    }
  }
#endif//NSIS_CONFIG_UNINSTALL_SUPPORT

  g_exec_flags.errlvl = -1;
  ret = ui_doinstall();

#ifdef NSIS_CONFIG_LOG
#if !defined(NSIS_CONFIG_LOG_ODS) && !defined(NSIS_CONFIG_LOG_STDOUT)
  log_write(1);
#endif//!NSIS_CONFIG_LOG_ODS && !NSIS_CONFIG_LOG_STDOUT
#endif//NSIS_CONFIG_LOG
end:

  CleanUp();

#if defined(NSIS_SUPPORT_ACTIVEXREG) || defined(NSIS_SUPPORT_CREATESHORTCUT)
  OleUninitialize();
#endif

  if (m_Err)
  {
    my_MessageBox(m_Err, MB_OK | MB_ICONSTOP | (IDOK << 21));
    ExitProcess(2);
  }

#ifdef NSIS_SUPPORT_REBOOT
  if (g_exec_flags.reboot_called)
  {
    const DWORD reason = SHTDN_REASON_FLAG_PLANNED | SHTDN_REASON_MAJOR_APPLICATION | SHTDN_REASON_MINOR_INSTALLATION;
    BOOL (WINAPI *OPT)(HANDLE, DWORD,PHANDLE);
    BOOL (WINAPI *LPV)(LPCTSTR,LPCTSTR,PLUID);
    BOOL (WINAPI *ATP)(HANDLE,BOOL,PTOKEN_PRIVILEGES,DWORD,PTOKEN_PRIVILEGES,PDWORD);
    BOOL (WINAPI *IS)(LPTSTR,LPTSTR,DWORD,DWORD,DWORD);
    #ifdef _WIN64
    OPT=OpenProcessToken, LPV=LookupPrivilegeValue, ATP=AdjustTokenPrivileges;
    #else
    OPT=myGetProcAddress(MGA_OpenProcessToken);
    LPV=myGetProcAddress(MGA_LookupPrivilegeValue);
    ATP=myGetProcAddress(MGA_AdjustTokenPrivileges);
    if (OPT && LPV && ATP)
    #endif
    {
      HANDLE hToken;
      TOKEN_PRIVILEGES tkp;
      if (OPT(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
      {
        LPV(NULL, SE_SHUTDOWN_NAME, &tkp.Privileges[0].Luid);
        tkp.PrivilegeCount = 1;
        tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
        ATP(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES)NULL, 0);
      }
    }

    IS=myGetProcAddress(MGA_InitiateShutdown);
    if ( (IS && !IS(NULL, NULL, 0, SHUTDOWN_RESTART | SHUTDOWN_FORCE_OTHERS | SHUTDOWN_GRACE_OVERRIDE, reason))
      || (!ExitWindowsEx(EWX_REBOOT, reason))
      )
      ExecuteCallbackFunction(CB_ONREBOOTFAILED);
  }
#endif//NSIS_SUPPORT_REBOOT

  if (g_exec_flags.errlvl != -1)
    ret = g_exec_flags.errlvl;

  ExitProcess(ret);
}
コード例 #19
0
ファイル: esil.c プロジェクト: djpohly/radare2
static int esil_commit (RAnalEsil *c, const char *op) {
	const char *q = POP();
	const char *p = POP();
	//const char *o = op;
	int ss = c->opsize;
	if (ss) {
//		eprintf (";; GET %d[%s]\n", ss, q);
//		eprintf ("PSUH %s %s\n", p, q);
eprintf (";; -> this means that we have to resolve before accessing memory %d\n", c->opsize);
		c->opsize = 0;
		PUSH (p);
		PUSH (q);
		return 0;
	}
	if (!op) {
		eprintf ("COMMIT UNKNOWN OP.. THIs IS []\n");
		return 0;
	}
	//eprintf (";;; COMMIT ;;; (%s) %s (%s)\n", p, o, q);
	if (IS ("[=")) {
		eprintf ("EQUAL------SET\n");
	} else
	if (IS ("+")) {
		// push (get (p)+get (q));
		ut64 n = esil_get (c, p) + esil_get (c, q);
		char *ns = malloc (32); // XXX memleak
		sprintf (ns, "0x%"PFMT64x, n);
		PUSH (ns);
		eprintf (";;; %s %s\n", p, q);
		//eprintf (" (((0x%llx)))\n", esil_get (c, p));
		eprintf (";;; +EQUAL! (%s)\n", ns);
	} else
	if (IS ("-")) {
		// push (get (p)+get (q));
		ut64 n = esil_get (c, p) - esil_get (c, q);
		char *ns = malloc (32); // XXX memleak
		sprintf (ns, "0x%"PFMT64x, n);
		PUSH (ns);
		eprintf (";;; %s %s\n", p, q);
		eprintf (";;; -EQUAL! (%s)\n", ns);
	} else
	if (IS ("*")) {
		// push (get (p)+get (q));
		ut64 n = esil_get (c, p) * esil_get (c, q);
		char *ns = malloc (32); // XXX memleak
		sprintf (ns, "0x%"PFMT64x, n);
		PUSH (ns);
		eprintf (";;; %s %s\n", p, q);
		eprintf (";;; *EQUAL! (%s)\n", ns);
	}
	if (IS ("=")) {
		if (p == NULL || q == NULL) {
			eprintf ("Invalid construction\n");
			return -1;
		}
		// set (p, get (q))
		c->set (c, p, c->get (c, q));
		eprintf (";;; EQUAL! (%s=%s)\n", p, q);
	}
	return 0;
}
コード例 #20
0
ファイル: control.c プロジェクト: bumper-app/nicad
/**
 * Check to see if we should try to start/stop service
 * @param P A service name as stated in the config file
 * @param action A string describing the action to execute
 * @return TRUE if the service was handled successfully otherwise FALSE
 */
void check_service(const char *P, const char *action) {

  Service_T s= NULL;

  ASSERT(P);
  ASSERT(action);

  if(NULL==(s= get_service(P))) {
    log("%s: Cannot %s program '%s' -- not found in %s\n",
          prog, action, P, Run.controlfile);
    return;
  }

  if(IS(action, "start")) {
    
    if(s->type==TYPE_PROCESS && is_process_running(s)) {
      DEBUG("%s: Process already running -- process %s\n", prog, P);
      monitor_set(s);
      return;
    }
    
    if(s->type==TYPE_PROCESS && !s->start) {
      DEBUG("%s: Start method not defined -- process %s\n", prog, P);
      monitor_set(s);
      return;
    }
    
    do_depend(s, "stop");
    do_start(s);
    do_depend(s, "start");
    
  } else if(IS(action, "stop")) {
    
    if(s->type==TYPE_PROCESS && !s->stop) {
      DEBUG("%s: Stop method not defined -- process %s\n", prog, P);
      monitor_unset(s);
      return;
    }
    
    do_depend(s, "stop");
    do_stop(s);
    
  } else if(IS(action, "restart")) {
    
    if(s->type==TYPE_PROCESS && (!s->start || !s->stop)) {
      DEBUG("%s: Start or stop method not defined -- process %s\n", prog, P);
      monitor_set(s);
      return;
    } else {
      log("Trying to restart '%s'\n", s->name);
    }
    
    do_depend(s, "stop");
    if(do_stop(s)) {
      /* Only start if stop succeeded */
      do_start(s);
      do_depend(s, "start");
    }
    
  } else if(IS(action, "monitor")) {
    
    /* We only enable monitoring of this service and all prerequisite
     * services. Chain of services which depends on this service keep
     * its state */
    do_monitor(s);
    
  } else if(IS(action, "unmonitor")) {
    
    /* We disable monitoring of this service and all services which
     * depends on it */
    do_depend(s, "unmonitor");
    do_unmonitor(s);
    
  }
    
}
コード例 #21
0
ファイル: mkdef_ord.c プロジェクト: nihilus/ia32rtools
int main(int argc, char *argv[])
{
  const struct parsed_proto *pp;
  FILE *fout, *fhdr;
  char basename[256] = { 0, };
  char line[256];
  char fmt[256];
  char word[256];
  int noname = 0;
  const char *p2;
  char *p;
  int arg;
  int ret, ord;
  int l;

  for (arg = 1; arg < argc; arg++) {
    if (IS(argv[arg], "-n"))
      noname = 1;
    else if (IS(argv[arg], "-b") && arg < argc - 1)
      snprintf(basename, sizeof(basename), "%s", argv[++arg]);
    else
      break;
  }

  if (argc != arg + 2) {
    printf("usage:\n%s [-n] [-b <basename>] <.h> <.def>\n", argv[0]);
    return 1;
  }

  hdrfn = argv[arg++];
  fhdr = fopen(hdrfn, "r");
  my_assert_not(fhdr, NULL);

  fout = fopen(argv[arg++], "w");
  my_assert_not(fout, NULL);

  if (basename[0] == 0) {
    p = strrchr(hdrfn, '.');
    my_assert_not(p, NULL);
    p2 = strrchr(hdrfn, '/');
    if (p2++ == NULL)
      p2 = hdrfn;
    l = p - p2;
    my_assert((unsigned int)l < 256, 1);
    memcpy(basename, p2, l);
    basename[l] = 0;
  }

  snprintf(fmt, sizeof(fmt), "%s_%%d", basename);

  fprintf(fout, "LIBRARY %s\n", basename);
  fprintf(fout, "EXPORTS\n");

  while (fgets(line, sizeof(line), fhdr))
  {
    p = sskip(line);
    if (*p == 0)
      continue;

    if (IS_START(p, "//"))
      continue;

    ret = 0;
    while (p != NULL && *p != 0) {
      p = next_word(word, sizeof(word), p);
      ret = sscanf(word, fmt, &ord);
      if (ret == 1)
        break;
    }
    if (ret != 1) {
      printf("scan for '%s' failed for '%s'\n", fmt, line);
      return 1;
    }

    snprintf(word, sizeof(word), fmt, ord);
    pp = proto_parse(fhdr, word, 0);
    if (pp == NULL)
      return 1;

    fputc(' ', fout);
    fputc(pp->is_fastcall ? '@' : ' ', fout);
    fprintf(fout, "%s", word);
    if (pp->is_stdcall)
      fprintf(fout, "@%-2d", pp->argc * 4);
    else
      fprintf(fout, "   ");
    fprintf(fout, " @%d", ord);
    if (noname)
      fprintf(fout, " NONAME");
    fprintf(fout, "\n");
  }

  fclose(fhdr);
  fclose(fout);
  return 0;
}
コード例 #22
0
ファイル: ex_blend.c プロジェクト: ufaith/d2imdev
/* Draw our example scene. */
static void draw(void)
{
    ALLEGRO_COLOR test[5];
    ALLEGRO_BITMAP *target = al_get_target_bitmap();

    char const *blend_names[] = {"ZERO", "ONE", "ALPHA", "INVERSE"};
    char const *blend_vnames[] = {"ZERO", "ONE", "ALPHA", "INVER"};
    int blend_modes[] = {ALLEGRO_ZERO, ALLEGRO_ONE, ALLEGRO_ALPHA,
                         ALLEGRO_INVERSE_ALPHA
                        };
    float x = 40, y = 40;
    int i, j;

    al_clear_to_color(al_map_rgb_f(0.5, 0.5, 0.5));

    test[0] = al_map_rgba_f(1, 1, 1, 1);
    test[1] = al_map_rgba_f(1, 1, 1, 0.5);
    test[2] = al_map_rgba_f(1, 1, 1, 0.25);
    test[3] = al_map_rgba_f(1, 0, 0, 0.75);
    test[4] = al_map_rgba_f(0, 0, 0, 0);

    print(x, 0, false, "D  E  S  T  I  N  A  T  I  O  N  (%0.2f fps)", ex.fps);
    print(0, y, true, "S O U R C E");
    for (i = 0; i < 4; i++) {
        print(x + i * 110, 20, false, blend_names[i]);
        print(20, y + i * 110, true, blend_vnames[i]);
    }

    al_set_blender(ALLEGRO_ADD, ALLEGRO_ONE, ALLEGRO_ZERO);
    if (ex.mode >= 1 && ex.mode <= 5) {
        al_set_target_bitmap(ex.offscreen);
        al_clear_to_color(test[ex.mode - 1]);
    }
    if (ex.mode >= 6 && ex.mode <= 10) {
        al_set_target_bitmap(ex.memory);
        al_clear_to_color(test[ex.mode - 6]);
    }

    for (j = 0; j < 4; j++) {
        for (i = 0; i < 4; i++) {
            al_set_blender(ALLEGRO_ADD, blend_modes[j], blend_modes[i]);
            if (ex.image == 0)
                al_draw_bitmap(ex.example, x + i * 110, y + j * 110, 0);
            else if (ex.image >= 1 && ex.image <= 6) {
                al_draw_filled_rectangle(x + i * 110, y + j * 110,
                                         x + i * 110 + 100, y + j * 110 + 100,
                                         test[ex.image - 1]);
            }
        }
    }

    if (ex.mode >= 1 && ex.mode <= 5) {
        al_set_blender(ALLEGRO_ADD, ALLEGRO_ONE, ALLEGRO_INVERSE_ALPHA);
        al_set_target_bitmap(target);
        al_draw_bitmap_region(ex.offscreen, x, y, 430, 430, x, y, 0);
    }
    if (ex.mode >= 6 && ex.mode <= 10) {
        al_set_blender(ALLEGRO_ADD, ALLEGRO_ONE, ALLEGRO_INVERSE_ALPHA);
        al_set_target_bitmap(target);
        al_draw_bitmap_region(ex.memory, x, y, 430, 430, x, y, 0);
    }

#define IS(x)  ((ex.image == x) ? "*" : " ")
    print(ex.BUTTONS_X, 20 * 1, false, "What to draw");
    print(ex.BUTTONS_X, 20 * 2, false, "%s Picture", IS(0));
    print(ex.BUTTONS_X, 20 * 3, false, "%s Rec1 (1/1/1/1)", IS(1));
    print(ex.BUTTONS_X, 20 * 4, false, "%s Rec2 (1/1/1/.5)", IS(2));
    print(ex.BUTTONS_X, 20 * 5, false, "%s Rec3 (1/1/1/.25)", IS(3));
    print(ex.BUTTONS_X, 20 * 6, false, "%s Rec4 (1/0/0/.75)", IS(4));
    print(ex.BUTTONS_X, 20 * 7, false, "%s Rec5 (0/0/0/0)", IS(5));
#undef IS

#define IS(x)  ((ex.mode == x) ? "*" : " ")
    print(ex.BUTTONS_X, 20 * 9, false, "Where to draw");
    print(ex.BUTTONS_X, 20 * 10, false, "%s screen", IS(0));

    print(ex.BUTTONS_X, 20 * 11, false, "%s offscreen1", IS(1));
    print(ex.BUTTONS_X, 20 * 12, false, "%s offscreen2", IS(2));
    print(ex.BUTTONS_X, 20 * 13, false, "%s offscreen3", IS(3));
    print(ex.BUTTONS_X, 20 * 14, false, "%s offscreen4", IS(4));
    print(ex.BUTTONS_X, 20 * 15, false, "%s offscreen5", IS(5));

    print(ex.BUTTONS_X, 20 * 16, false, "%s memory1", IS(6));
    print(ex.BUTTONS_X, 20 * 17, false, "%s memory2", IS(7));
    print(ex.BUTTONS_X, 20 * 18, false, "%s memory3", IS(8));
    print(ex.BUTTONS_X, 20 * 19, false, "%s memory4", IS(9));
    print(ex.BUTTONS_X, 20 * 20, false, "%s memory5", IS(10));
#undef IS
}
コード例 #23
0
ファイル: lua_compiler.c プロジェクト: NaughtyCode/slua
static int doargs(int argc, char* argv[]) {
  int i;
  int version=0;
  if (argv[0]!=NULL && *argv[0]!=0) progname=argv[0];
  for (i=1; i<argc; i++) {
    if (*argv[i]!='-') {		/* end of options; keep it */
      break;
    } else if (IS("--")) {	/* end of options; skip it */
      ++i;
      if (version) ++version;
      break;
    } else if (IS("-")) {		/* end of options; use stdin */
      break;
    } else if (IS("-c")) {	/* output C code */
      c_code=1;
      dumping=0;
    } else if (IS("-L")) {	/* preload library */
      if (preloads >= MAX_PRELOADS) usage(LUA_QL("-L") " too many preloads");
      preload_libs[preloads]=argv[++i];
      preloads++;
    } else if (IS("-M")) {	/* list */
      LuaModule = true;
    } else if (IS("-l")) {	/* list */
      ++listing;
    } else if (IS("-o")) {	/* output file */
      output=argv[++i];
      if (output==NULL || *output==0) usage(LUA_QL("-o") " needs argument");
      if (IS("-")) output=NULL;
    } else if (IS("-p")) {	/* parse only */
      parse_only=1;
    } else if (IS("-s")) {	/* strip debug information */
      stripping=1;
    } else if (IS("-v")) {	/* show version */
      ++version;
    } else {					/* unknown option */
      usage(argv[i]);
    }
  }
  if (i==argc && (listing || !dumping)) {
    dumping=0;
    argv[--i]=Output;
  }
  if (version) {
    printf("%s  %s\n",LUA_RELEASE,LUA_COPYRIGHT);
    if (version==argc-1) exit(EXIT_SUCCESS);
  }
  return i;
}
コード例 #24
0
ファイル: breakpoints.cpp プロジェクト: gt1/translocations
int main(int argc, char * argv[])
{
	try
	{
		libmaus2::util::ArgInfo const arginfo(argc,argv);
		// free list for alignments
		libmaus2::util::GrowingFreeList<libmaus2::bambam::BamAlignment> BAFL;
		// insert size
		int64_t const insertsize = arginfo.getValue<int64_t>("insertsize",800);
		// container for bam decoders
		DecoderContainer deccont;
		
		while ( std::cin )
		{
			// eof?
			if ( std::cin.peek() < 0 )
				break;
		
			// get next instance line
			InstanceLine IS(&deccont,std::cin);
			std::cout << IS << '\n';
			
			uint64_t ilow = 0;
			while ( ilow != IS.size() )
			{
				uint64_t ihigh = ilow;
				
				// get interval for one type of instance
				while ( ihigh != IS.size() && IS.instances[ihigh].type == IS.instances[ilow].type )
					++ihigh;
				
				// if type is split, improper or samestrand
				if ( 
					IS.instances[ilow].type == Instance::instance_type_split
					||
					IS.instances[ilow].type == Instance::instance_type_improper
					||
					IS.instances[ilow].type == Instance::instance_type_samestrand
				)
				{
					// key is maxcnt,num
					std::map<SubInstKey, std::vector<std::string>, std::greater<SubInstKey> > subinst;
				
					for ( uint64_t i = ilow; i < ihigh; ++i )
					{
						std::vector<libmaus2::bambam::BamAlignment *> retlist;
						
						// map from read name to vector of alignments
						std::map<std::string, std::vector<libmaus2::bambam::BamAlignment *> > amap;
						
						libmaus2::bambam::BamHeader::unique_ptr_type uheader;
					
						// get alignments from A file marked with gene A
						{
							libmaus2::bambam::BamAlignmentDecoder & deca = IS.getInstanceDecoderA(i);
							libmaus2::bambam::BamAlignment & algna = deca.getAlignment();
							libmaus2::bambam::BamHeader const & headera = deca.getHeader();

							libmaus2::bambam::BamHeader::unique_ptr_type theader(headera.uclone());
							uheader = UNIQUE_PTR_MOVE(theader);
							
							while ( deca.readAlignment() )
								if ( algna.isMapped() && hasGeneComment(&algna,IS.geneA.name) )
								{
									// std::cerr << algna.formatAlignment(headera) << std::endl;
									libmaus2::bambam::BamAlignment * palgn = BAFL.get();
									retlist.push_back(palgn);
									amap[algna.getName()].push_back(palgn);
									palgn->swap(algna);
								}
						}

						// get alignments from B file marked with gene B
						{
							libmaus2::bambam::BamAlignmentDecoder & decb = IS.getInstanceDecoderB(i);
							libmaus2::bambam::BamAlignment & algnb = decb.getAlignment();
							// libmaus2::bambam::BamHeader const & headerb = decb->getHeader();
							
							while ( decb.readAlignment() )
								if ( algnb.isMapped() && hasGeneComment(&algnb,IS.geneB.name) )
								{
									// std::cerr << algna.formatAlignment(headera) << std::endl;
									libmaus2::bambam::BamAlignment * palgn = BAFL.get();
									retlist.push_back(palgn);
									amap[algnb.getName()].push_back(palgn);
									palgn->swap(algnb);
								}
						}
						
						// pair map intervals
						std::vector<MappedPair> pairs;
						// count read pairs for gene pair
						uint64_t cnt = 0;
						// iterate over names
						for ( std::map<std::string, std::vector<libmaus2::bambam::BamAlignment *> >::iterator ita = amap.begin(); ita != amap.end(); ++ita )
						{
							// get vector of alignments for name
							std::vector<libmaus2::bambam::BamAlignment *> & V = ita->second;
							// sort by (refid,pos,read1)
							std::sort(V.begin(),V.end(),PosComparator());
							
							// remove multiple copies of same alignment
							uint64_t o = 0;
							uint64_t rcnt[2] = {0,0};
							for ( uint64_t l = 0; l < V.size(); )
							{
								// skip over multiple copies of same alignment
								uint64_t h = l;
								while ( h != V.size() && sameAlignment(V[l],V[h]) )
									++h;

								// count read 1
								if ( V[l]->isRead1() )
									rcnt[0]++;
								// count read 2
								if ( V[l]->isRead2() )
									rcnt[1]++;
								
								// copy alignment pointer
								if ( V[l]->isRead1() || V[l]->isRead2() )
									V[o++] = V[l];							
									
								l = h;
							}
														
							V.resize(o);
							
							// if we have read1 and read2
							if ( V.size() > 1 && rcnt[0] && rcnt[1] )
							{
								// iterate over read 1
								for ( uint64_t r1 = 0; r1 < rcnt[0]; ++r1 )
									// iterate over read 2
									for ( uint64_t r2 = rcnt[0]; r2 < o; ++r2 )
									{
										// get alignment for read 1
										libmaus2::bambam::BamAlignment const * algn1 = V[r1];
										// get alignment for read 2
										libmaus2::bambam::BamAlignment const * algn2 = V[r2];

										// if pair is marked with gene pair we are looking for
										if ( 
											(
												hasGeneComment(algn1,IS.geneA.name)
												&&
												hasGeneComment(algn2,IS.geneB.name)
											)
											||
											(											
												hasGeneComment(algn1,IS.geneB.name)
												&&
												hasGeneComment(algn2,IS.geneA.name)
											)
										)
										{
											#if 0
											std::cerr << "\n --- \n";
											std::cerr << algn1->formatAlignment(*uheader) << std::endl;
											std::cerr << algn2->formatAlignment(*uheader) << std::endl;
											++cnt;
											std::cerr << "subcnt=" << V.size() << std::endl;
											#endif
											
											// increment number of read pairs found
											cnt += 1;
											
											// determine smaller and larger alignment (by position)
											bool const smal1 = PosComparator::compare(algn1,algn2);
											libmaus2::bambam::BamAlignment const * algnl = smal1 ? algn1 : algn2;
											libmaus2::bambam::BamAlignment const * algnr = smal1 ? algn2 : algn1;

											// "left" interval
											libmaus2::math::IntegerInterval<int64_t> intl(
												algnl->getPos(),
												algnl->getAlignmentEnd()
											);

											// "right" interval
											libmaus2::math::IntegerInterval<int64_t> intr(
												algnr->getPos(),
												algnr->getAlignmentEnd()
											);
											
											// construct mapped pair of aligned intervals
											MappedPair MP(intl,intr);
								
											// see if this interval (modulo insert size) already exists			
											bool existing = false;
											for ( uint64_t i = 0; (!existing) && i < pairs.size(); ++i )
												// already seen?
												if ( MappedPair::isInsertSizeOverlap(pairs[i],MP,insertsize) )
												{
													// update from for left
													pairs[i].first.from = std::min(
														MP.first.from,
														pairs[i].first.from
													);
													// update to for left
													pairs[i].first.to = std::max(
														MP.first.to,
														pairs[i].first.to
													);

													// update from for right
													pairs[i].second.from = std::min(
														MP.second.from,
														pairs[i].second.from
													);
													// update to for right
													pairs[i].second.to = std::max(
														MP.second.to,
														pairs[i].second.to
													);
													
													// update number of supporting pair for this "break point"
													pairs[i].cnt += 1;
												
													// note that this break point already existed
													existing = true;
												}
												#if 0
												else
												{
													std::cerr << "no overlap" << std::endl;
													std::cerr << MP << std::endl;
													std::cerr << pairs[i] << std::endl;
												}
												#endif
											
											// push new pair if break point did not exist yet
											if ( ! existing )
												pairs.push_back(MP);
										}
									}
							
							}
						}

						// std::cerr << IS.instances[i] << " gcnt=" << cnt << ((IS.instances[i].num != cnt) ? "___" : "") << std::endl;

						std::ostringstream ostr;						
						ostr << "\t" << IS.instances[i];
						// sort by number of supporting read pairs
						std::sort(pairs.begin(),pairs.end(),MappedPairCountComparator());
						// maximum count
						uint64_t const maxcnt =  pairs.size() ? pairs.front().cnt : 0;
						ostr << "\t" << maxcnt;
						// output break points
						for ( uint64_t j = 0; j < pairs.size();++j )
							ostr << "\t" << pairs[j];
						
						// sub instances map ordered by number of read pairs supporting break point
						subinst[SubInstKey(maxcnt,IS.instances[i].num)].push_back(ostr.str());

						// return alignment to free list
						for ( uint64_t i = 0; i < retlist.size(); ++i )
							BAFL.put(retlist[i]);
					}

					// output instance lines
					for ( 
						std::map<SubInstKey, std::vector<std::string>, std::greater<SubInstKey> >::const_iterator ita = subinst.begin();
							ita != subinst.end(); ++ita 
					)
					{
						std::vector<std::string> const & V = ita->second;
						for ( uint64_t i = 0; i < V.size(); ++i )
							std::cout << V[i] << "\n";
					}
				}

				ilow = ihigh;
			}
		}			
	}
	catch(std::exception const & ex)
	{
		std::cerr << ex.what() << std::endl;
		return EXIT_FAILURE;
	}
}
コード例 #25
0
ファイル: luac.c プロジェクト: ARMinARM/elua
static int doargs(int argc, char* argv[])
{
 int i;
 int version=0;
 if (argv[0]!=NULL && *argv[0]!=0) progname=argv[0];
 for (i=1; i<argc; i++)
 {
  if (*argv[i]!='-')			/* end of options; keep it */
   break;
  else if (IS("--"))			/* end of options; skip it */
  {
   ++i;
   if (version) ++version;
   break;
  }
  else if (IS("-"))			/* end of options; use stdin */
   break;
  else if (IS("-l"))			/* list */
   ++listing;
  else if (IS("-o"))			/* output file */
  {
   output=argv[++i];
   if (output==NULL || *output==0) usage(LUA_QL("-o") " needs argument");
   if (IS("-")) output=NULL;
  }
  else if (IS("-p"))			/* parse only */
   dumping=0;
  else if (IS("-s"))			/* strip debug information */
   stripping=1;
  else if (IS("-v"))			/* show version */
   ++version;
  else if (IS("-cci")) /* target integer size */
  {
   int s = target.sizeof_int = atoi(argv[++i])/8;
   if (!(s==1 || s==2 || s==4)) fatal(LUA_QL("-cci") " must be 8, 16 or 32");
  }
  else if (IS("-ccn")) /* target lua_Number type and size */
  {
   const char *type=argv[++i];
   if (strcmp(type,"int")==0) target.lua_Number_integral=1;
   else if (strcmp(type,"float")==0) target.lua_Number_integral=0;
   else if (strcmp(type,"float_arm")==0)
   {
     target.lua_Number_integral=0;
     target.is_arm_fpa=1;
   }
   else fatal(LUA_QL("-ccn") " type must be " LUA_QL("int") " or " LUA_QL("float") " or " LUA_QL("float_arm"));
   int s = target.sizeof_lua_Number = atoi(argv[++i])/8;
   if (target.lua_Number_integral && !(s==1 || s==2 || s==4)) fatal(LUA_QL("-ccn") " size must be 8, 16, or 32 for int");
   if (!target.lua_Number_integral && !(s==4 || s==8)) fatal(LUA_QL("-ccn") " size must be 32 or 64 for float");
  }
  else if (IS("-cce")) /* target endianness */
  {
   const char *val=argv[++i];
   if (strcmp(val,"big")==0) target.little_endian=0;
   else if (strcmp(val,"little")==0) target.little_endian=1;
   else fatal(LUA_QL("-cce") " must be " LUA_QL("big") " or " LUA_QL("little"));
  }
  else					/* unknown option */
   usage(argv[i]);
 }
 if (i==argc && (listing || !dumping))
 {
  dumping=0;
  argv[--i]=Output;
 }
 if (version)
 {
  printf("%s  %s\n",LUA_RELEASE,LUA_COPYRIGHT);
  if (version==argc-1) exit(EXIT_SUCCESS);
 }
 return i;
}
コード例 #26
0
ファイル: luac.c プロジェクト: NicolSpies/nodemcu-firmware
static int doargs(int argc, char* argv[])
{
 int i;
 int version=0;
 if (argv[0]!=NULL && *argv[0]!=0) progname=argv[0];
 for (i=1; i<argc; i++)
 {
  if (*argv[i]!='-')			/* end of options; keep it */
   break;
  else if (IS("--"))			/* end of options; skip it */
  {
   ++i;
   if (version) ++version;
   break;
  }
  else if (IS("-"))		  	/* end of options; use stdin */
   break;
  else if (IS("-e"))			/* execute a lua source file file */
  {
   execute=argv[++i];
   if (execute ==NULL || *execute==0 || *execute=='-' ) 
     usage(LUA_QL("-e") " needs argument");
  }
  else if (IS("-f"))			/* Flash image file */
  {
   flash=lookup=1;
  }
  else if (IS("-a"))			/* Absolue flash image file */
  {
   flash=lookup=1;
   address=strtol(argv[++i],NULL,0);
   size_t offset = (unsigned) (address -IROM0_SEG);
   if (offset > IROM0_SEGMAX)
     usage(LUA_QL("-e") " absolute address must be valid flash address");
  }
  else if (IS("-i"))			/* lookup */
   lookup = 1;
  else if (IS("-l"))			/* list */
   ++listing;
  else if (IS("-m"))			/* specify a maximum image size */
  {
   flash=lookup=1;
   maxSize=strtol(argv[++i],NULL,0);
   if (maxSize & 0xFFF)
     usage(LUA_QL("-e") " maximum size must be a multiple of 4,096");
  }
  else if (IS("-o"))			/* output file */
  {
   output=argv[++i];
   if (output==NULL || *output==0) usage(LUA_QL("-o") " needs argument");
   if (IS("-")) output=NULL;
  }

  else if (IS("-p"))			/* parse only */
   dumping=0;   
  else if (IS("-s"))			/* strip debug information */
   stripping=1;
  else if (IS("-v"))			/* show version */
   ++version;
  else					/* unknown option */
  usage(argv[i]);
 }

 if (i==argc && (listing || !dumping))
 {
  dumping=0;
  argv[--i]=Output;
 }
 if (version)
 {
  printf("%s  %s\n",LUA_RELEASE,LUA_COPYRIGHT);
  if (version==argc-1) exit(EXIT_SUCCESS);
 }
 return i;
}
コード例 #27
0
ファイル: lexrulee.c プロジェクト: Pendrokar/ilmentufa
token *JEK_root_926_1()
	{
	INIT;
	IS(JA_546);
	RETURN;
	}
コード例 #28
0
ファイル: xupl.c プロジェクト: xupl/xupl
xupl* xupl_parse(xupl *xup) {

	xupl_*_ = (xupl_*) xup;
	FILE* in = _->in;
	off_t buffsize = _->buffsize;

	unsigned short bit = 0x0001;
	unsigned short WHITESPACE = bit;

	unsigned short DOUBLE_STRING = (bit <<= 1);
	unsigned short SINGLE_STRING = (bit <<= 1);
	unsigned short STRING = DOUBLE_STRING | SINGLE_STRING;

	unsigned short LINE_COMMENT = (bit <<= 1);
	unsigned short MULTI_COMMENT = (bit <<= 1);
	unsigned short COMMENT = LINE_COMMENT | MULTI_COMMENT;

	unsigned short _state = 0;

	const int default_tksize = 12;
	int tksize = default_tksize + 1;

	unsigned char *tk = NULL;
	int tkndx = 0;

	int chars_read;
	char* buf = malloc(buffsize + 1);

	xmlNodePtr xroot = NULL;
	xmlNodePtr xc = NULL;
	xmlAttrPtr xprop = NULL;

	const xmlChar* xuplAttr = (const xmlChar*) "data-xupl";
	const xmlChar* xuplClosed = (const xmlChar*) "closed";

	xmlDocPtr xdoc = xmlNewDoc((const unsigned char*) "1.1");
	//xmlNsPtr xuplNs = xmlNewGlobalNs(xdoc,"http://ns.xupl.org/1.1","xupl");

	while ((chars_read = fread(buf, 1, buffsize, in)) > 0) {

		for (int i = 0; i < chars_read; i++) {
			const char c = buf[i];

			switch (c) {

				case '\'':
				case '"':
					IF(COMMENT) break;

					IF(STR(c)) {
						DISABLE(STR(c));
					} else if (NOT(STRING)) {
						ALLOW(STR(c));
						break;
					}

				case '{':
				case '}':
				case ' ':
				case '\n':
				case '\r':
				case '\t':
				case '\f':
				case '\v':
				case ',':
				case '=':
				// Comment characters
				case '*':
				case '/':
				case '#':
				case '!':
					IF(STRING) break;

					switch (c) {
						case ',':
						case '{':
							xprop = NULL;
					}

					if (tk) {
						tk[tkndx] = 0;

						char p = 0;
						if (tkndx >= 1) p = tk[tkndx - 1];
						unsigned char* m = NULL;

						unsigned int tklen = tkndx + 1;
						unsigned char* t = tk;

						IF(COMMENT) {
							if ('\n' == c && IS(LINE_COMMENT)) {
								if (tkndx + 1 < tksize) {
									tk[tkndx++] = ' ';
									tk[tkndx] = 0;
								}
							} else if ('*' == p && '/' == c && IS(MULTI_COMMENT)) {
								tk[tkndx - 1] = 0;
							} else break;
							DISABLE(COMMENT);
							m = tk + 2;
						} else if ('/' == p && '*' == c) {
							ALLOW(MULTI_COMMENT);
							break;
						// Single-line comments can be #! #* #/ ##
						} else if ('#' == p && ('!' == c || '*' == c || '/' == c || '#' == c)) {
							ALLOW(LINE_COMMENT);
							break;
						// If these characters were in the token and not part of a comment,
						// then continue as if they are normal characters of a token.
						} else if ('!' == c || '/' == c || '*' == c || '#' == c) break;

						if (!xc) {
							if (m) {
								xroot = xmlNewDocComment(xdoc, m);
								xmlDocSetRootElement(xdoc, xroot);
							} else {
								xc = xmlNewNode(NULL, tk);
								xmlDocSetRootElement(xdoc, xc);
								if (!xroot) xroot = xc;
							}
						} else if (m) {
							xmlAddChild(xc, xmlNewComment(m));
						} else {
							char *attr = NULL;
							xmlAttrPtr closed = xmlHasProp(xc, xuplAttr);

							switch (tk[0]) {
								case '\'':
								case '"':
									t += 1;
									xmlAddChild(xc, xmlNewText(t));
									break;
									// TODO make this parameterized, characters and names.
								case '.': attr = "class";    break;
								case '#': attr = "id";       break;
								case '@': attr = "project";  break;
								case '/': attr = "href";     break;
								case '[': attr = "data";     break;
								case '~': attr = "duration"; break;
								case '=': attr = "location"; break;
								case '^': attr = "at";       break;
								case ':': attr = "type";     break;
								case '!': attr = "priority"; break;
								default:
								{
									regmatch_t pmatch[1];
									unsigned int isword = 0 == regexec(&re_word, (char*) tk, 1, pmatch, 0);
									if (closed) {
										if (isword) {
											xc = xmlNewChild(xc, NULL, tk, NULL);
										} else {
											xmlAddChild(xc, xmlNewText(tk));
										}
									} else {
										if (xprop) {
											xmlNewProp(xc, xprop->name, tk);
											xmlRemoveProp(xprop);
											xprop = NULL;
										} else if (isword) {
											xprop = xmlNewProp(xc, tk, (unsigned char*) "True");
										} else {
											xprop = xmlNewProp(xc, (unsigned char*) ".fake", tk);
										}
										switch (c) {
											case ',':
											case '{':
												xprop = NULL;
										}
									}
								}
									break;
							}

							if (attr) {
								if (closed) {
									xmlAddChild(xc, xmlNewText(t));
								} else {
									xmlNewProp(xc, (xmlChar*) attr, t);
								}
							}
						}

						free(tk);
						tk = NULL;
						if (tksize > default_tksize && tkndx < default_tksize) {
							tksize /= 2;
						}
						tkndx = 0;

						if (m) continue;
					}

				default:
					break;
			}

			switch (c) {
				case '{':
					xmlNewProp(xc, xuplAttr, xuplClosed);
					continue;
				case '}':
					if (xc) {
						xmlAttrPtr data = xmlHasProp(xc, xuplAttr);
						if (data) xmlRemoveProp(data);
						xc = xc->parent;
					}
					continue;
				default:
					break;
			}

			// Accumulate the tk.
			if (!tk || tkndx >= tksize) {
				// If the tk buffer is too small, double it.
				tk = realloc(tk, tksize *= 2);
			}
			tk[tkndx++] = c;
		}
コード例 #29
0
ファイル: cookie.c プロジェクト: Myleft/cphalcon7
/**
 * Sends the cookie to the HTTP client
 * Stores the cookie definition in session
 *
 * @return Phalcon\Http\Cookie
 */
PHP_METHOD(Phalcon_Http_Cookie, send){

	zval *name, *value, *expire, *domain, *path, *secure;
	zval *http_only, *dependency_injector, *definition;
	zval *service = NULL, *session = NULL, *key, *encryption, *crypt = NULL;
	zval *encrypt_value = NULL, *has_session = NULL;

	PHALCON_MM_GROW();

	name = phalcon_read_property(getThis(), SL("_name"), PH_NOISY);
	value = phalcon_read_property(getThis(), SL("_value"), PH_NOISY);
	expire = phalcon_read_property(getThis(), SL("_expire"), PH_NOISY);
	domain = phalcon_read_property(getThis(), SL("_domain"), PH_NOISY);
	path = phalcon_read_property(getThis(), SL("_path"), PH_NOISY);
	secure = phalcon_read_property(getThis(), SL("_secure"), PH_NOISY);
	http_only = phalcon_read_property(getThis(), SL("_httpOnly"), PH_NOISY);
	dependency_injector = phalcon_read_property(getThis(), SL("_dependencyInjector"), PH_NOISY);
	if (Z_TYPE_P(dependency_injector) == IS_OBJECT) {
		PHALCON_INIT_VAR(service);
		ZVAL_STR(service, IS(session));

		PHALCON_CALL_METHOD(&has_session, dependency_injector, "has", service);
		if (zend_is_true(has_session)) {
			PHALCON_INIT_VAR(definition);
			array_init(definition);
			if (!PHALCON_IS_LONG(expire, 0)) {
				phalcon_array_update_str(definition, SL("expire"), expire, PH_COPY);
			}

			if (PHALCON_IS_NOT_EMPTY(path)) {
				phalcon_array_update_str(definition, SL("path"), path, PH_COPY);
			}

			if (PHALCON_IS_NOT_EMPTY(domain)) {
				phalcon_array_update_string(definition, IS(domain), domain, PH_COPY);
			}

			if (PHALCON_IS_NOT_EMPTY(secure)) {
				phalcon_array_update_str(definition, SL("secure"), secure, PH_COPY);
			}

			if (PHALCON_IS_NOT_EMPTY(http_only)) {
				phalcon_array_update_str(definition, SL("httpOnly"), http_only, PH_COPY);
			}

			/**
			 * The definition is stored in session
			 */
			if (phalcon_fast_count_ev(definition)) {
				PHALCON_CALL_METHOD(&session, dependency_injector, "getshared", service);

				if (Z_TYPE_P(session) != IS_NULL) {
					PHALCON_VERIFY_INTERFACE(session, phalcon_session_adapterinterface_ce);

					PHALCON_INIT_VAR(key);
					PHALCON_CONCAT_SV(key, "_PHCOOKIE_", name);
					PHALCON_CALL_METHOD(NULL, session, "set", key, definition);
				}
			}
		}
	}

	encryption = phalcon_read_property(getThis(), SL("_useEncryption"), PH_NOISY);
	if (zend_is_true(encryption) && PHALCON_IS_NOT_EMPTY(value)) {
		if (Z_TYPE_P(dependency_injector) != IS_OBJECT) {
			PHALCON_THROW_EXCEPTION_STR(phalcon_http_cookie_exception_ce, "A dependency injection object is required to access the 'filter' service");
			return;
		}

		PHALCON_INIT_NVAR(service);
		ZVAL_STRING(service, "crypt");

		PHALCON_CALL_METHOD(&crypt, dependency_injector, "getshared", service);
		PHALCON_VERIFY_INTERFACE(crypt, phalcon_cryptinterface_ce);

		/**
		 * Encrypt the value also coding it with base64
		 */
		PHALCON_CALL_METHOD(&encrypt_value, crypt, "encryptbase64", value);
	} else {
		PHALCON_CPY_WRT(encrypt_value, value);
	}

	/** 
	 * Sets the cookie using the standard 'setcookie' function
	 */
	convert_to_string_ex(name);
	convert_to_string_ex(encrypt_value);
	convert_to_long_ex(expire);
	convert_to_string_ex(path);
	convert_to_string_ex(domain);
	convert_to_long_ex(secure);
	convert_to_long_ex(http_only);

	php_setcookie(Z_STR_P(name), Z_STR_P(encrypt_value), Z_LVAL_P(expire), Z_STR_P(path), Z_STR_P(domain), Z_LVAL_P(secure), 1, Z_LVAL_P(http_only));

	RETURN_THIS();
}
コード例 #30
0
ファイル: DInst.cpp プロジェクト: dilawar/sesc
void DInst::killSilently()
{
  I(getPendEvent()==0);
  I(getResource()==0);

#ifdef SESC_BAAD
  if (fetch2Time == 0) {
    fetch1QSize--;
  }else if (renameTime == 0) {
    fetch2QSize--;
  }else if (issueTime == 0) {
    issueQSize--;
  }else if (schedTime == 0) {
    schedQSize--;
  }else if (exeTime == 0) {
    exeQSize--;
  }else{
    retireQSize--;
  }
#endif

  markIssued();
  markExecuted();
  if( getFetch() ) {
    getFetch()->unBlockFetch();
    IS(setFetch(0));
  }

  if (getInst()->isStore())
    LDSTBuffer::storeLocallyPerformed(this);
 
  while (hasPending()) {
    DInst *dstReady = getNextPending();

    if (!dstReady->isIssued()) {
      // Accross processor dependence
      if (dstReady->hasDepsAtRetire())
        dstReady->clearDepsAtRetire();
      
      I(!dstReady->hasDeps());
      continue;
    }
    if (dstReady->isExecuted()) {
      // The instruction got executed even though it has dependences. This is
      // because the instruction got silently killed (killSilently)
      if (!dstReady->hasDeps())
        dstReady->scrap();
      continue;
    }

    if (!dstReady->hasDeps()) {
      I(dstReady->isIssued());
      I(!dstReady->isExecuted());
      Resource *dstRes = dstReady->getResource();
      I(dstRes);
      dstRes->simTime(dstReady);
    }
  }

#ifdef TASKSCALAR
  notifyDataDepViolation(DataDepViolationAtRetire);

  if (lvid) { // maybe got killSilently
    lvid = 0;
    lvidVersion->decOutsReqs();
    lvidVersion->garbageCollect();
    IS(lvidVersion=0);
  }
  
  I(lvidVersion==0);
#endif

  I(!getFetch());

  if (hasDeps())
    return;
  
  I(nDeps == 0);   // No deps src

#if (defined TLS)
  I(!myEpoch);
#endif

  I(!getFetch());
#if (defined MIPS_EMUL)
  context->delDInst();
  context=0;
#endif
  dInstPool.in(this); 
}