TEST(QueryPlannerTest, threeVarTriples) {
  try {
    ParsedQuery pq = SparqlParser::parse(
        "SELECT ?x ?p ?o WHERE {"
        "<s> <p> ?x . ?x ?p ?o }");
    QueryPlanner qp(nullptr);
    QueryExecutionTree qet = qp.createExecutionTree(pq);
    ASSERT_EQ(
        "{\n  JOIN\n  {\n    SCAN FOR FULL INDEX SPO (DUMMY OPERATION)\n   "
        " qet-width: 3 \n  } join-column: [0]\n  |X|\n  {\n    SCAN"
        " PSO with P = \"<p>\", S = \"<s>\"\n    qet-width: 1 \n  }"
        " join-column: [0]\n  qet-width: 3 \n}",
        qet.asString());
  } catch (const ad_semsearch::Exception& e) {
    std::cout << "Caught: " << e.getFullErrorMessage() << std::endl;
    FAIL() << e.getFullErrorMessage();
  } catch (const std::exception& e) {
    std::cout << "Caught: " << e.what() << std::endl;
    FAIL() << e.what();
  }

  try {
    ParsedQuery pq = SparqlParser::parse(
        "SELECT ?x ?p ?o WHERE {"
        "<s> ?x <o> . ?x ?p ?o }");
    QueryPlanner qp(nullptr);
    QueryExecutionTree qet = qp.createExecutionTree(pq);
    ASSERT_EQ(
        "{\n  JOIN\n  {\n    SCAN FOR FULL INDEX SPO (DUMMY OP"
        "ERATION)\n    qet-width: 3 \n  } join-column: [0]"
        "\n  |X|\n  {\n    SCAN SOP with S = \"<s>\", O = \"<o>\"\n "
        "   qet-width: 1 \n  } join-column: [0]\n  qet-width: 3 \n}",
        qet.asString());
  } catch (const ad_semsearch::Exception& e) {
    std::cout << "Caught: " << e.getFullErrorMessage() << std::endl;
    FAIL() << e.getFullErrorMessage();
  } catch (const std::exception& e) {
    std::cout << "Caught: " << e.what() << std::endl;
    FAIL() << e.what();
  }

  try {
    ParsedQuery pq = SparqlParser::parse(
        "SELECT ?s ?p ?o WHERE {"
        "<s> <p> ?p . ?s ?p ?o }");
    QueryPlanner qp(nullptr);
    QueryExecutionTree qet = qp.createExecutionTree(pq);
    ASSERT_EQ(
        "{\n  JOIN\n  {\n    SCAN FOR FULL INDEX PSO (DUMMY OPERATION)\n"
        "    qet-width: 3 \n  } join-column: [0]\n  |X|\n  {\n "
        "   SCAN PSO with P = \"<p>\", S = \"<s>\"\n  "
        "  qet-width: 1 \n  } join-column: [0]\n  qet-width: 3 \n}",
        qet.asString());
  } catch (const ad_semsearch::Exception& e) {
    std::cout << "Caught: " << e.getFullErrorMessage() << std::endl;
    FAIL() << e.getFullErrorMessage();
  } catch (const std::exception& e) {
    std::cout << "Caught: " << e.what() << std::endl;
    FAIL() << e.what();
  }
}
Ejemplo n.º 2
0
template<bool avx> void typeToBGRA(const void* const src, void* const dest, const PixelTypes::PixelType type, const size_t size)
{
  const __m_auto_i* const pSrc = reinterpret_cast<const __m_auto_i*>(src);
  const __m_auto_i* const srcEnd = reinterpret_cast<const __m_auto_i*>(src) + (size * PixelTypes::pixelSize(type)) / sizeof(__m_auto_i);
  __m_auto_i* pDest = reinterpret_cast<__m_auto_i*>(dest);

  switch(type)
  {
    case PixelTypes::PixelType::RGB:
      rgbToBGRA<avx>(pSrc, srcEnd, pDest);
      break;
    case PixelTypes::PixelType::YUV:
      yuvToBGRA<avx>(pSrc, srcEnd, pDest);
      break;
    case PixelTypes::PixelType::YUYV:
      yuyvToBGRA<avx>(pSrc, srcEnd, pDest);
      break;
    case PixelTypes::PixelType::Colored:
      coloredToBGRA<avx>(pSrc, srcEnd, pDest);
      break;
    case PixelTypes::PixelType::Grayscale:
      grayscaledToBGRA<avx>(pSrc, srcEnd, pDest);
      break;
    case PixelTypes::PixelType::Hue:
      hueToBGRA(reinterpret_cast<const PixelTypes::HuePixel*>(src), reinterpret_cast<const PixelTypes::HuePixel*>(srcEnd), reinterpret_cast<PixelTypes::BGRAPixel*>(dest));
      break;
    case PixelTypes::PixelType::Edge2:
      edge2ToBGRA<avx>(pSrc, srcEnd, pDest, reinterpret_cast<const __m_auto_i*>(dest) + (size * PixelTypes::pixelSize(PixelTypes::BGRA)) / sizeof(__m_auto_i));
      break;/*
    case PixelTypes::PixelType::Edge2MonoAvg:
      //edge2MonoAvgToBGRA<avx>(pSrc, srcEnd, pDest);
      break;
    case PixelTypes::PixelType::Edge2MonoAbsAvg:
      //edge2MonoAbsAvgBGRA<avx>(pSrc, srcEnd, pDest);
      break;*/
    case PixelTypes::PixelType::Binary:
      binaryToBGRA<avx>(pSrc, srcEnd, pDest);
      break;
    default:
      FAIL("Unknown pixel type.");
  }

  size_t rest = (size * PixelTypes::pixelSize(type)) % sizeof(__m_auto_i);
  if(rest != 0)
  {
    PixelTypes::BGRAPixel* const ppDest = reinterpret_cast<PixelTypes::BGRAPixel*>(dest) + size - rest;
    switch(type)
    {
      case PixelTypes::PixelType::RGB:
        rgbToBGRA(reinterpret_cast<const PixelTypes::RGBPixel*>(src) + size - rest, reinterpret_cast<const PixelTypes::RGBPixel*>(src) + size, ppDest);
        break;
      case PixelTypes::PixelType::YUV:
        yuvToBGRA(reinterpret_cast<const PixelTypes::YUVPixel*>(src) + size - rest, reinterpret_cast<const PixelTypes::YUVPixel*>(src) + size, ppDest);
        break;
      case PixelTypes::PixelType::YUYV:
        yuyvToBGRA(reinterpret_cast<const PixelTypes::YUYVPixel*>(src) + size - rest, reinterpret_cast<const PixelTypes::YUYVPixel*>(src) + size, ppDest);
        break;
      case PixelTypes::PixelType::Colored:
        coloredToBGRA(reinterpret_cast<const PixelTypes::ColoredPixel*>(src) + size - rest, reinterpret_cast<const PixelTypes::ColoredPixel*>(src) + size, ppDest);
        break;
      case PixelTypes::PixelType::Grayscale:
        grayscaledToBGRA(reinterpret_cast<const PixelTypes::GrayscaledPixel*>(src) + size - rest, reinterpret_cast<const PixelTypes::GrayscaledPixel*>(src) + size, ppDest);
        break;
      case PixelTypes::PixelType::Hue:
        hueToBGRA(reinterpret_cast<const PixelTypes::HuePixel*>(src) + size - rest, reinterpret_cast<const PixelTypes::HuePixel*>(src) + size, ppDest);
        break;
      case PixelTypes::PixelType::Edge2:
        edge2ToBGRA(reinterpret_cast<const PixelTypes::Edge2Pixel*>(src) + size - rest, reinterpret_cast<const PixelTypes::Edge2Pixel*>(src) + size, ppDest, reinterpret_cast<PixelTypes::BGRAPixel*>(dest) + size);
        break;
      case PixelTypes::PixelType::Binary:
        binaryToBGRA(reinterpret_cast<const PixelTypes::BinaryPixel*>(src) + size - rest, reinterpret_cast<const PixelTypes::BinaryPixel*>(src) + size, ppDest);
        break;
      default:
        FAIL("Unknown pixel type.");
    }
  }
}
Ejemplo n.º 3
0
 void check( const BSONObj &one, const BSONObj &two ) {
     if ( one.woCompare( two ) != 0 ) {
         static string fail = string( "Assertion failure expected " ) + string( one ) + ", got " + string( two );
         FAIL( fail.c_str() );
     }
 }
Ejemplo n.º 4
0
/*
 - SREcomp - compile a regular expression into internal code
 *
 * We can't allocate space until we know how big the compiled form will be,
 * but we can't compile it (and thus know how big it is) until we've got a
 * place to put the code.  So we cheat:  we compile it twice, once with code
 * generation turned off and size counting turned on, and once "for real".
 * This also means that we don't allocate space until we are sure that the
 * thing really will compile successfully, and we never have to move the
 * code and thus invalidate pointers into it.  (Note that it has to be in
 * one piece because free() must be able to free it all.)
 *
 * Beware that the optimization-preparation code in here knows about some
 * of the structure of the compiled SRE.
 */
SRE *
SREcomp(char *exp)
{
	register SRE *r;
	register char *scan;
	register char *longest;
	register int len;
	int flags;

	if (exp == NULL) {
		FAIL("NULL argument");
	}

	/* First pass: determine size, legality. */
	regparse = exp;
	regnpar = 1;
	regsize = 0L;
	regcode = &regdummy;
	regc(SRE_MAGIC);
	if (reg(0, &flags) == NULL) {
		return(NULL);
	}

	/* Small enough for pointer-storage convention? */
	if (regsize >= 32767L) {	/* Probably could be 65535L. */
		FAIL("SRE too big");
	}

	/* Allocate space. */
	r = xalloc(sizeof(SRE) + (unsigned)regsize, 0, 0);
	if (r == NULL) {
		FAIL("out of space");
	}

	/* Second pass: emit code. */
	regparse = exp;
	regnpar = 1;
	regcode = r->program;
	regc(SRE_MAGIC);
	if (reg(0, &flags) == NULL) {
		return(NULL);
	}

	/* Dig out information for optimizations. */
	r->regstart = '\0';	/* Worst-case defaults. */
	r->reganch = 0;
	r->regmust = NULL;
	r->regmlen = 0;
	r->regsize = sizeof(SRE) + regsize;
	scan = r->program+1;			/* First BRANCH. */
	if (OP(regnext(scan)) == END) {		/* Only one top-level choice. */
		scan = OPERAND(scan);

		/* Starting-point info. */
		if (OP(scan) == EXACTLY) {
			r->regstart = *OPERAND(scan);
		} else if (OP(scan) == BEGWORD && OP(regnext(scan)) == EXACTLY) {
			r->regstart = *OPERAND(regnext(scan));
		} else if (OP(scan) == BOL) {
			r->reganch++;
		}

		/*
		 * If there's something expensive in the r.e., find the
		 * longest literal string that must appear and make it the
		 * regmust.  Resolve ties in favor of later strings, since
		 * the regstart check works with the beginning of the r.e.
		 * and avoiding duplication strengthens checking.  Not a
		 * strong reason, but sufficient in the absence of others.
		 */
		if (flags&SPSTART) {
			longest = NULL;
			len = 0;
			for (; scan != NULL; scan = regnext(scan)) {
				if (OP(scan) == EXACTLY && strlen(OPERAND(scan)) >= len) {
					longest = OPERAND(scan);
					len = strlen(OPERAND(scan));
				}
			}
			r->regmust = longest;
			r->regmlen = len;
		}
	}

	return(r);
}
Ejemplo n.º 5
0
/*
 - regpiece - something followed by possible [*+?{]
 *
 * Note that the branching code sequences used for ? and the general cases
 * of * and + are somewhat optimized:  they use the same NOTHING node as
 * both the endmarker for their branch list and the body of the last branch.
 * It might seem that this node could be dispensed with entirely, but the
 * endmarker role is not redundant.
 */
static char *
regpiece(int *flagp)
{
	register char	*next;
	register char	*ret;
	register char	op;
	unsigned char	max;
	unsigned char	min;
	int		flags;

	ret = regatom(&flags);
	if (ret == NULL) {
		return(NULL);
	}

	op = *regparse;
	if (!ISMULT(op)) {
		*flagp = flags;
		return(ret);
	}

	if (!(flags&HASWIDTH) && op != '?') {
		FAIL("*+{ operand could be empty");
	}
	*flagp = (op != '+' && op != '{') ? (WORST|SPSTART) : (WORST|HASWIDTH);

	if (op == '*' && (flags&SIMPLE)) {
		reginsert(STAR, ret);
	} else if (op == '*') {
		/* Emit x* as (x&|), where & means "self". */
		reginsert(BRANCH, ret);			/* Either x */
		regoptail(ret, regnode(BACK));		/* and loop */
		regoptail(ret, ret);			/* back */
		regtail(ret, regnode(BRANCH));		/* or */
		regtail(ret, regnode(NOTHING));		/* null. */
	} else if (op == '+' && (flags&SIMPLE)) {
		reginsert(PLUS, ret);
	} else if (op == '+') {
		/* Emit x+ as x(&|), where & means "self". */
		next = regnode(BRANCH);			/* Either */
		regtail(ret, next);
		regtail(regnode(BACK), ret);		/* loop back */
		regtail(next, regnode(BRANCH));		/* or */
		regtail(ret, regnode(NOTHING));		/* null. */
	} else if (op == '{') {
		for (min = 0, regparse++ ; *regparse && isdigit(*regparse) ; regparse++) {
			min = min * 10 + (*regparse - '0');
		}
		for (max = 0, regparse++ ; *regparse && isdigit(*regparse) ; regparse++) {
			max = max * 10 + (*regparse - '0');
		}
		reginsert(max, ret);
		next = OPERAND(ret);
		reginsert(min, ret);
		next = OPERAND(next);
		reginsert(MINMAX, ret);
		regtail(ret, OPERAND(next));		/* MINMAX->next = x */
	} else if (op == '?') {
		/* Emit x? as (x|) */
		reginsert(BRANCH, ret);			/* Either x */
		regtail(ret, regnode(BRANCH));		/* or */
		next = regnode(NOTHING);		/* null. */
		regtail(ret, next);
		regoptail(ret, next);
	}
	regparse++;
	if (ISMULT(*regparse)) {
		FAIL("nested *?+{");
	}

	return(ret);
}
int main(int argc, char *argv[])
{
	long hpage_size;
	int fd;
	void *p;
	volatile unsigned int *q;
	int err;
	int sigbus_count = 0;
	unsigned long initial_rsvd, rsvd;
	struct sigaction sa = {
		.sa_sigaction = sigbus_handler,
		.sa_flags = SA_SIGINFO,
	};

	test_init(argc, argv);

	hpage_size = check_hugepagesize();

	fd = hugetlbfs_unlinked_fd();
	if (fd < 0)
		FAIL("hugetlbfs_unlinked_fd()");

	initial_rsvd = get_huge_page_counter(hpage_size, HUGEPAGES_RSVD);
	verbose_printf("Reserve count before map: %lu\n", initial_rsvd);

	p = mmap(NULL, hpage_size, PROT_READ|PROT_WRITE, MAP_SHARED,
		 fd, 0);
	if (p == MAP_FAILED)
		FAIL("mmap(): %s", strerror(errno));
	q = p;

	verbose_printf("Reserve count after map: %lu\n",
		get_huge_page_counter(hpage_size, HUGEPAGES_RSVD));

	*q = 0;
	verbose_printf("Reserve count after touch: %lu\n",
		get_huge_page_counter(hpage_size, HUGEPAGES_RSVD));

	err = ftruncate(fd, 0);
	if (err)
		FAIL("ftruncate(): %s", strerror(errno));

	rsvd = get_huge_page_counter(hpage_size, HUGEPAGES_RSVD);
	verbose_printf("Reserve count after truncate: %lu\n", rsvd);
	if (rsvd != initial_rsvd)
		FAIL("Reserved count is not restored after truncate: %lu instead of %lu",
		     rsvd, initial_rsvd);

	err = sigaction(SIGBUS, &sa, NULL);
	if (err)
		FAIL("sigaction(): %s", strerror(errno));

	if (sigsetjmp(sig_escape, 1) == 0)
		*q; /* Fault, triggering a SIGBUS */
	else
		sigbus_count++;

	if (sigbus_count != 1)
		FAIL("Didn't SIGBUS after truncate");

	rsvd = get_huge_page_counter(hpage_size, HUGEPAGES_RSVD);
	verbose_printf("Reserve count after SIGBUS fault: %lu\n", rsvd);
	if (rsvd != initial_rsvd)
		FAIL("Reserved count is altered by SIGBUS fault: %lu instead of %lu",
		     rsvd, initial_rsvd);

	munmap(p, hpage_size);

	verbose_printf("Reserve count after munmap(): %lu\n",
		get_huge_page_counter(hpage_size, HUGEPAGES_RSVD));

	close(fd);

	verbose_printf("Reserve count after close(): %lu\n",
		get_huge_page_counter(hpage_size, HUGEPAGES_RSVD));

	PASS();
}
Ejemplo n.º 7
0
//!	(internal,static)
void StreamerMMF::readVertexData(Mesh * mesh, Reader & in) {
	static const std::string warningPrefix("LoaderMMF::readVertexData: ");

	VertexDescription vd;

	for(uint32_t attrId = in.read_uint32(); attrId != StreamerMMF::MMF_END ; attrId = in.read_uint32()) {
		uint32_t numValues = in.read_uint32();
		uint32_t glType = in.read_uint32();
		uint32_t extLength = in.read_uint32();
		std::string name;

		switch(attrId) {
			case 0x00: {
					static const std::string s( VertexAttributeIds::POSITION.toString() );
					name = s;
					break;
				}
			case 0x01: {
					static const std::string s( VertexAttributeIds::NORMAL.toString() );
					name = s;
					break;
				}
			case 0x02: {
					static const std::string s( VertexAttributeIds::COLOR.toString() );
					name = s;
					break;
				}
			case 0x06: {
					static const std::string s( VertexAttributeIds::TEXCOORD0.toString() );
					name = s;
					break;
				}
			case 0x07: {
					static const std::string s( VertexAttributeIds::TEXCOORD1.toString() );
					name = s;
					break;
				}
			case MMF_CUSTOM_ATTR_ID: {
					break;
				}
			default: {
					WARN(warningPrefix+"Unknown attribute found.");
					break;
				}
		}


		while(extLength >= 8) {
			uint32_t extBlockType=in.read_uint32();
			uint32_t extBlockSize=in.read_uint32();
			extLength-=8;

			if(extLength>extBlockSize) {
				WARN(warningPrefix+"Error in vertex block");
				FAIL();
			}

			std::vector<uint8_t> data(extBlockSize);
			in.read(data.data(),extBlockSize);
			extLength-=extBlockSize;

			if(extBlockType==MMF_VERTEX_ATTR_EXT_NAME) {
				name.assign(data.begin(), data.end());
				name=name.substr(0,name.find('\0')); // remove additional zeros
			} else {
				WARN(warningPrefix+"Found unsupported ext data, skipping data.");
			}
		}
		if(extLength!=0) {
			WARN(warningPrefix+"Error in vertex block");
			FAIL();
		}
		if(name.empty())
			WARN(warningPrefix+"Found unnamed vertex attribute.");

		vd.appendAttribute(name,numValues,glType);
//        vd.setData(index, numValues, glType);

	}
	const uint32_t count = in.read_uint32();
	MeshVertexData & vertices = mesh->openVertexData();
	vertices.allocate(count,vd);

	in.read( vertices.data(), vertices.dataSize());

	vertices.updateBoundingBox();
}
Ejemplo n.º 8
0
void* udp_pull(void* leflux)
{
    struct flux * flux = (struct flux *) leflux;
	struct epoll_event ev;
	memset(&ev, 0, sizeof(struct epoll_event));
	int epollfd;

	epollfd = epoll_create(10);
	FAIL(epollfd);

	struct tabClients tabClientsUDP;
	tabClientsUDP.clients =
		(struct sockClient *)malloc(BASE_CLIENTS*sizeof(struct sockClient));
	memset(tabClientsUDP.clients, 0, sizeof(struct sockClient)*BASE_CLIENTS);
	tabClientsUDP.nbClients = 0;

	int baseCouranteUDP = BASE_CLIENTS;

	struct epoll_event events[MAX_EVENTS];

	flux->sock = createSockEventUDP(epollfd, flux->port);
	int sockData = socket(AF_INET, SOCK_DGRAM, 0);

	int nfds;
	int done = 0;

	while(done == 0) //Boucle principale
	{

		nfds = epoll_wait(epollfd, events, MAX_EVENTS, -1);
		FAIL(nfds);

		int n;

		for (n = 0; n < nfds; ++n)
		{
			if (events[n].events == EPOLLIN )
			{					
				char * buffer = (char *)malloc(512*sizeof(char));
				memset(buffer, '\0', 512);

				struct sockaddr_in faddr;
				memset(&faddr, 0, sizeof(struct sockaddr_in));
				socklen_t len = sizeof(faddr);

				FAIL(recvfrom(flux->sock, buffer, 512*sizeof(char),0, (struct sockaddr*)&faddr, &len));

				int j = 0;
				int trouve = -1;
				while((trouve == -1) && (j < tabClientsUDP.nbClients))
				{
					struct sockaddr_in * comp = &tabClientsUDP.clients[j].videoClient.orig_addr;
					if(faddr.sin_addr.s_addr == comp->sin_addr.s_addr 
							&& faddr.sin_family == comp->sin_family
							&& faddr.sin_port == comp->sin_port)
					{
						trouve = j;
					}
					j++;
				}
				if(trouve == -1)
				{
					if (tabClientsUDP.nbClients >= baseCouranteUDP)
					{
						baseCouranteUDP *=2;
						struct sockClient *  temp;
						temp = (struct sockClient *) realloc(tabClientsUDP.clients,
								baseCouranteUDP*sizeof(struct sockClient));
						if (temp!=NULL) 
						{
							tabClientsUDP.clients = temp;
						}
						else 
						{
							free (tabClientsUDP.clients);
							puts ("Error (re)allocating memory");
							exit (1);
						}
					}
					initReq(&(tabClientsUDP.clients[tabClientsUDP.nbClients].requete));
					memset(&tabClientsUDP.clients[tabClientsUDP.nbClients].videoClient.orig_addr,0,sizeof(struct sockaddr_in));
					memcpy(&tabClientsUDP.clients[tabClientsUDP.nbClients].videoClient.orig_addr, &faddr, sizeof(struct sockaddr_in));
					tabClientsUDP.clients[tabClientsUDP.nbClients].videoClient.clientSocket = sockData;
					
					tabClientsUDP.clients[tabClientsUDP.nbClients].videoClient.infosVideo = &flux->infosVideo;
					trouve = tabClientsUDP.nbClients++;
				}
				traiteChaine(buffer, &tabClientsUDP.clients[trouve].requete, &tabClientsUDP.clients[trouve].videoClient, 
						epollfd, 0);
			}

		}


	}
	return NULL;
}
Ejemplo n.º 9
0
TEST(ZxTestCAssertionsTest, Fail) {
    FAIL("Something bad happened\n");
    ZX_ASSERT_MSG(_ZXTEST_ABORT_IF_ERROR, "FAIL did not abort test execution");
    ZX_ASSERT_MSG(false, "_ZXTEST_ABORT_IF_ERROR not set on failure.");
}
Ejemplo n.º 10
0
int
shiftprop(Flow *r)
{
	Flow *r1;
	Prog *p, *p1, *p2;
	int n, o;
	Adr a;

	p = r->prog;
	if(p->to.type != D_REG)
		FAIL("BOTCH: result not reg");
	n = p->to.reg;
	a = zprog.from;
	if(p->reg != NREG && p->reg != p->to.reg) {
		a.type = D_REG;
		a.reg = p->reg;
	}
	if(debug['P'])
		print("shiftprop\n%P", p);
	r1 = r;
	for(;;) {
		/* find first use of shift result; abort if shift operands or result are changed */
		r1 = uniqs(r1);
		if(r1 == nil)
			FAIL("branch");
		if(uniqp(r1) == nil)
			FAIL("merge");
		p1 = r1->prog;
		if(debug['P'])
			print("\n%P", p1);
		switch(copyu(p1, &p->to, A)) {
		case 0:	/* not used or set */
			if((p->from.type == D_REG && copyu(p1, &p->from, A) > 1) ||
			   (a.type == D_REG && copyu(p1, &a, A) > 1))
				FAIL("args modified");
			continue;
		case 3:	/* set, not used */
			FAIL("BOTCH: noref");
		}
		break;
	}
	/* check whether substitution can be done */
	switch(p1->as) {
	default:
		FAIL("non-dpi");
	case AAND:
	case AEOR:
	case AADD:
	case AADC:
	case AORR:
	case ASUB:
	case ASBC:
	case ARSB:
	case ARSC:
		if(p1->reg == n || (p1->reg == NREG && p1->to.type == D_REG && p1->to.reg == n)) {
			if(p1->from.type != D_REG)
				FAIL("can't swap");
			p1->reg = p1->from.reg;
			p1->from.reg = n;
			switch(p1->as) {
			case ASUB:
				p1->as = ARSB;
				break;
			case ARSB:
				p1->as = ASUB;
				break;
			case ASBC:
				p1->as = ARSC;
				break;
			case ARSC:
				p1->as = ASBC;
				break;
			}
			if(debug['P'])
				print("\t=>%P", p1);
		}
	case ABIC:
	case ATST:
	case ACMP:
	case ACMN:
		if(p1->reg == n)
			FAIL("can't swap");
		if(p1->reg == NREG && p1->to.reg == n)
			FAIL("shift result used twice");
//	case AMVN:
		if(p1->from.type == D_SHIFT)
			FAIL("shift result used in shift");
		if(p1->from.type != D_REG || p1->from.reg != n)
			FAIL("BOTCH: where is it used?");
		break;
	}
	/* check whether shift result is used subsequently */
	p2 = p1;
	if(p1->to.reg != n)
	for (;;) {
		r1 = uniqs(r1);
		if(r1 == nil)
			FAIL("inconclusive");
		p1 = r1->prog;
		if(debug['P'])
			print("\n%P", p1);
		switch(copyu(p1, &p->to, A)) {
		case 0:	/* not used or set */
			continue;
		case 3: /* set, not used */
			break;
		default:/* used */
			FAIL("reused");
		}
		break;
	}

	/* make the substitution */
	p2->from.type = D_SHIFT;
	p2->from.reg = NREG;
	o = p->reg;
	if(o == NREG)
		o = p->to.reg;

	switch(p->from.type){
	case D_CONST:
		o |= (p->from.offset&0x1f)<<7;
		break;
	case D_REG:
		o |= (1<<4) | (p->from.reg<<8);
		break;
	}
	switch(p->as){
	case ASLL:
		o |= 0<<5;
		break;
	case ASRL:
		o |= 1<<5;
		break;
	case ASRA:
		o |= 2<<5;
		break;
	}
	p2->from.offset = o;
	if(debug['P'])
		print("\t=>%P\tSUCCEED\n", p2);
	return 1;
}
Ejemplo n.º 11
0
int
test_capmode(void)
{
	struct statfs statfs;
	struct stat sb;
	long sysarch_arg = 0;
	int fd_close, fd_dir, fd_file, fd_socket, fd2[2];
	int success = PASSED;
	pid_t pid, wpid;
	char ch;

	/* Open some files to play with. */
	REQUIRE(fd_file = open("/tmp/cap_capmode", O_RDWR|O_CREAT, 0644));
	REQUIRE(fd_close = open("/dev/null", O_RDWR));
	REQUIRE(fd_dir = open("/tmp", O_RDONLY));
	REQUIRE(fd_socket = socket(PF_INET, SOCK_DGRAM, 0));

	/* Enter capability mode. */
	REQUIRE(cap_enter());

	/*
	 * System calls that are not permitted in capability mode.
	 */
	CHECK_CAPMODE(access, "/tmp/cap_capmode_access", F_OK);
	CHECK_CAPMODE(acct, "/tmp/cap_capmode_acct");
	CHECK_CAPMODE(bind, PF_INET, NULL, 0);
	CHECK_CAPMODE(chdir, "/tmp/cap_capmode_chdir");
	CHECK_CAPMODE(chflags, "/tmp/cap_capmode_chflags", UF_NODUMP);
	CHECK_CAPMODE(chmod, "/tmp/cap_capmode_chmod", 0644);
	CHECK_CAPMODE(chown, "/tmp/cap_capmode_chown", -1, -1);
	CHECK_CAPMODE(chroot, "/tmp/cap_capmode_chroot");
	CHECK_CAPMODE(connect, PF_INET, NULL, 0);
	CHECK_CAPMODE(creat, "/tmp/cap_capmode_creat", 0644);
	CHECK_CAPMODE(fchdir, fd_dir);
	CHECK_CAPMODE(getfsstat, &statfs, sizeof(statfs), MNT_NOWAIT);
	CHECK_CAPMODE(link, "/tmp/foo", "/tmp/bar");
	CHECK_CAPMODE(lstat, "/tmp/cap_capmode_lstat", &sb);
	CHECK_CAPMODE(mknod, "/tmp/capmode_mknod", 06440, 0);
	CHECK_CAPMODE(mount, "procfs", "/not_mounted", 0, NULL);
	CHECK_CAPMODE(open, "/dev/null", O_RDWR);
	CHECK_CAPMODE(readlink, "/tmp/cap_capmode_readlink", NULL, 0);
	CHECK_CAPMODE(revoke, "/tmp/cap_capmode_revoke");
	CHECK_CAPMODE(stat, "/tmp/cap_capmode_stat", &sb);
	CHECK_CAPMODE(symlink,
	    "/tmp/cap_capmode_symlink_from",
	    "/tmp/cap_capmode_symlink_to");
	CHECK_CAPMODE(unlink, "/tmp/cap_capmode_unlink");
	CHECK_CAPMODE(unmount, "/not_mounted", 0);

	/*
	 * System calls that are permitted in capability mode.
	 */
	CHECK_SYSCALL_SUCCEEDS(close, fd_close);
	CHECK_SYSCALL_SUCCEEDS(dup, fd_file);
	CHECK_SYSCALL_SUCCEEDS(fstat, fd_file, &sb);
	CHECK_SYSCALL_SUCCEEDS(lseek, fd_file, 0, SEEK_SET);
	CHECK_SYSCALL_SUCCEEDS(msync, &fd_file, 8192, MS_ASYNC);
	CHECK_SYSCALL_SUCCEEDS(profil, NULL, 0, 0, 0);
	CHECK_SYSCALL_SUCCEEDS(read, fd_file, &ch, sizeof(ch));
	CHECK_SYSCALL_SUCCEEDS(recvfrom, fd_socket, NULL, 0, 0, NULL, NULL);
	CHECK_SYSCALL_SUCCEEDS(setuid, getuid());
	CHECK_SYSCALL_SUCCEEDS(write, fd_file, &ch, sizeof(ch));

	/*
	 * These calls will fail for lack of e.g. a proper name to send to,
	 * but they are allowed in capability mode, so errno != ECAPMODE.
	 */
	CHECK_NOT_CAPMODE(accept, fd_socket, NULL, NULL);
	CHECK_NOT_CAPMODE(getpeername, fd_socket, NULL, NULL);
	CHECK_NOT_CAPMODE(getsockname, fd_socket, NULL, NULL);
	CHECK_NOT_CAPMODE(fchflags, fd_file, UF_NODUMP);
	CHECK_NOT_CAPMODE(recvmsg, fd_socket, NULL, 0);
	CHECK_NOT_CAPMODE(sendmsg, fd_socket, NULL, 0);
	CHECK_NOT_CAPMODE(sendto, fd_socket, NULL, 0, 0, NULL, 0);

	/*
	 * System calls which should be allowed in capability mode, but which
	 * don't return errors, and are thus difficult to check.
	 *
	 * We will try anyway, by checking errno.
	 */
	CHECK_SYSCALL_VOID_NOT_ECAPMODE(getegid);
	CHECK_SYSCALL_VOID_NOT_ECAPMODE(geteuid);
	CHECK_SYSCALL_VOID_NOT_ECAPMODE(getgid);
	CHECK_SYSCALL_VOID_NOT_ECAPMODE(getpid);
	CHECK_SYSCALL_VOID_NOT_ECAPMODE(getppid);
	CHECK_SYSCALL_VOID_NOT_ECAPMODE(getuid);

	/*
	 * Finally, tests for system calls that don't fit the pattern very well.
	 */
	pid = fork();
	if (pid >= 0) {
		if (pid == 0) {
			exit(0);
		} else if (pid > 0) {
			wpid = waitpid(pid, NULL, 0);
			if (wpid < 0) {
				if (errno != ECAPMODE)
					FAIL("capmode:waitpid");
			} else
				FAIL("capmode:waitpid succeeded");
		}
	} else
		FAIL("capmode:fork");

	if (getlogin() == NULL)
		FAIL("test_sycalls:getlogin %d", errno);

	if (getsockname(fd_socket, NULL, NULL) < 0) {
		if (errno == ECAPMODE)
			FAIL("capmode:getsockname");
	}

	/* XXXRW: ktrace */

	if (pipe(fd2) == 0) {
		close(fd2[0]);
		close(fd2[1]);
	} else if (errno == ECAPMODE)
		FAIL("capmode:pipe");

	/* XXXRW: ptrace. */

	/* sysarch() is, by definition, architecture-dependent */
#if defined (__amd64__) || defined (__i386__)
	CHECK_CAPMODE(sysarch, I386_SET_IOPERM, &sysarch_arg);
#else
	/* XXXJA: write a test for arm */
	FAIL("capmode:no sysarch() test for current architecture");
#endif

	/* XXXRW: No error return from sync(2) to test. */

	return (success);
}
Ejemplo n.º 12
0
/* ------------------------- */
STATIC void test205()
{
u_int16_t vol = VolID;
DSI *dsi = &Conn->dsi;
u_int16_t ret;
char *tp;

	enter_test();
    fprintf(stdout,"===================\n");
    fprintf(stdout,"FPOpenVol:t205: Open Volume call\n");

    FAIL (FPCloseVol(Conn, vol));
	/* --------- */
    ret = FPOpenVolFull(Conn, Vol, 0);
    if (ret != 0xffff || dsi->header.dsi_code != htonl(AFPERR_BITMAP)) {
		failed();    
    }
	
	if (ret != 0xffff) {
    	FAIL (FPCloseVol(Conn, ret));
	}
	/* --------- */
    ret = FPOpenVolFull(Conn, Vol, 0xffff);
    if (ret != 0xffff || dsi->header.dsi_code != htonl(AFPERR_BITMAP)) {
		failed();    
    }
	if (ret != 0xffff) {
    	FAIL (FPCloseVol(Conn, ret));
	}
	/* --------- */
	tp = strdup(Vol);
	if (!tp) {
		goto fin;
	}
	*tp = *tp +1;
    ret = FPOpenVol(Conn, tp);
	free(tp);
    if (ret != 0xffff || dsi->header.dsi_code != htonl(AFPERR_NOOBJ)) {
		failed();    
    }
	if (ret != 0xffff) {
    	FAIL (FPCloseVol(Conn, ret));
	}
	/* -------------- */
	ret = FPOpenVol(Conn, Vol);
	if (ret == 0xffff) {
		failed();
	}
	vol = FPOpenVol(Conn, Vol);
	if (vol != ret) {
		fprintf(stdout,"\tFAILED double open != volume id\n");
		failed_nomsg();
	}	
    FAIL (FPCloseVol(Conn, ret));
    FAIL (!FPCloseVol(Conn, ret));
fin:
	ret = VolID = FPOpenVol(Conn, Vol);
	if (ret == 0xffff) {
		failed();
	}
	exit_test("test205");
}
Ejemplo n.º 13
0
double
VTIM_parse(const char *p)
{
	double t;
	int month = 0, year = 0, weekday = -1, mday = 0;
	int hour = 0, min = 0, sec = 0;
	int d, leap;

	while (*p == ' ')
		p++;

	if (*p >= '0' && *p <= '9') {
		/* ISO8601 -- "1994-11-06T08:49:37" */
		DIGIT(1000, year);
		DIGIT(100, year);
		DIGIT(10, year);
		DIGIT(1, year);
		MUSTBE('-');
		DIGIT(10, month);
		DIGIT(1, month);
		MUSTBE('-');
		DIGIT(10, mday);
		DIGIT(1, mday);
		MUSTBE('T');
		TIMESTAMP();
	} else {
		WEEKDAY();
		assert(weekday >= 0 && weekday <= 6);
		if (*p == ',') {
			/* RFC822 & RFC1123 - "Sun, 06 Nov 1994 08:49:37 GMT" */
			p++;
			MUSTBE(' ');
			DIGIT(10, mday);
			DIGIT(1, mday);
			MUSTBE(' ');
			MONTH();
			MUSTBE(' ');
			DIGIT(1000, year);
			DIGIT(100, year);
			DIGIT(10, year);
			DIGIT(1, year);
			MUSTBE(' ');
			TIMESTAMP();
			MUSTBE(' ');
			MUSTBE('G');
			MUSTBE('M');
			MUSTBE('T');
		} else if (*p == ' ') {
			/* ANSI-C asctime() -- "Sun Nov  6 08:49:37 1994" */
			p++;
			MONTH();
			MUSTBE(' ');
			if (*p != ' ')
				DIGIT(10, mday);
			else
				p++;
			DIGIT(1, mday);
			MUSTBE(' ');
			TIMESTAMP();
			MUSTBE(' ');
			DIGIT(1000, year);
			DIGIT(100, year);
			DIGIT(10, year);
			DIGIT(1, year);
		} else if (!memcmp(p, more_weekday[weekday],
		    strlen(more_weekday[weekday]))) {
			/* RFC850 -- "Sunday, 06-Nov-94 08:49:37 GMT" */
			p += strlen(more_weekday[weekday]);
			MUSTBE(',');
			MUSTBE(' ');
			DIGIT(10, mday);
			DIGIT(1, mday);
			MUSTBE('-');
			MONTH();
			MUSTBE('-');
			DIGIT(10, year);
			DIGIT(1, year);
			year += 1900;
			if (year < 1969)
				year += 100;
			MUSTBE(' ');
			TIMESTAMP();
			MUSTBE(' ');
			MUSTBE('G');
			MUSTBE('M');
			MUSTBE('T');
		} else
			FAIL();
	}

	while (*p == ' ')
		p++;

	if (*p != '\0')
		FAIL();

	if (sec < 0 || sec > 60)	/* Leapseconds! */
		FAIL();
	if (min < 0 || min > 59)
		FAIL();
	if (hour < 0 || hour > 23)
		FAIL();
	if (month < 1 || month > 12)
		FAIL();
	if (mday < 1 || mday > days_in_month[month - 1])
		FAIL();
	if (year < 1899)
		FAIL();

	leap =
	    ((year) % 4) == 0 && (((year) % 100) != 0 || ((year) % 400) == 0);

	if (month == 2 && mday > 28 && !leap)
		FAIL();

	if (sec == 60)			/* Ignore Leapseconds */
		sec--;

	t = ((hour * 60.) + min) * 60. + sec;

	d = (mday - 1) + days_before_month[month - 1];

	if (month > 2 && leap)
		d++;

	d += (year % 100) * 365;	/* There are 365 days in a year */

	if ((year % 100) > 0)		/* And a leap day every four years */
		d += (((year % 100) - 1) / 4);

	d += ((year / 100) - 20) *	/* Days relative to y2000 */
	    (100 * 365 + 24);		/* 24 leapdays per year in a century */

	d += ((year - 1) / 400) - 4;	/* And one more every 400 years */

	/*
	 * Now check weekday, if we have one.
	 * 6 is because 2000-01-01 was a saturday.
	 * 10000 is to make sure the modulus argument is always positive
	 */
	if (weekday != -1 && (d + 6 + 7 * 10000) % 7 != weekday)
		FAIL();

	t += d * 86400.;

	t += 10957. * 86400.;		/* 10957 days frm UNIX epoch to y2000 */

	return (t);
}
Ejemplo n.º 14
0
TEST(QueryPlannerTest, testCpyCtorWithKeepNodes) {
  try {
    {
      ParsedQuery pq = SparqlParser::parse(
          "SELECT ?x WHERE {?x ?p <X>. ?x ?p2 <Y>. <X> ?p <Y>}");
      pq.expandPrefixes();
      QueryPlanner qp(nullptr);
      auto tg = qp.createTripleGraph(&pq._rootGraphPattern);
      ASSERT_EQ(2u, tg._nodeMap.find(0)->second->_variables.size());
      ASSERT_EQ(2u, tg._nodeMap.find(1)->second->_variables.size());
      ASSERT_EQ(1u, tg._nodeMap.find(2)->second->_variables.size());
      ASSERT_EQ(
          "0 {s: ?x, p: ?p, o: <X>} : (1, 2)\n"
          "1 {s: ?x, p: ?p2, o: <Y>} : (0)\n"
          "2 {s: <X>, p: ?p, o: <Y>} : (0)",
          tg.asString());
      {
        vector<size_t> keep;
        QueryPlanner::TripleGraph tgnew(tg, keep);
        ASSERT_EQ("", tgnew.asString());
      }
      {
        vector<size_t> keep;
        keep.push_back(0);
        keep.push_back(1);
        keep.push_back(2);
        QueryPlanner::TripleGraph tgnew(tg, keep);
        ASSERT_EQ(
            "0 {s: ?x, p: ?p, o: <X>} : (1, 2)\n"
            "1 {s: ?x, p: ?p2, o: <Y>} : (0)\n"
            "2 {s: <X>, p: ?p, o: <Y>} : (0)",
            tgnew.asString());
        ASSERT_EQ(2u, tgnew._nodeMap.find(0)->second->_variables.size());
        ASSERT_EQ(2u, tgnew._nodeMap.find(1)->second->_variables.size());
        ASSERT_EQ(1u, tgnew._nodeMap.find(2)->second->_variables.size());
      }
      {
        vector<size_t> keep;
        keep.push_back(0);
        QueryPlanner::TripleGraph tgnew(tg, keep);
        ASSERT_EQ("0 {s: ?x, p: ?p, o: <X>} : ()", tgnew.asString());
        ASSERT_EQ(2u, tgnew._nodeMap.find(0)->second->_variables.size());
      }
      {
        vector<size_t> keep;
        keep.push_back(0);
        keep.push_back(1);
        QueryPlanner::TripleGraph tgnew(tg, keep);
        ASSERT_EQ(
            "0 {s: ?x, p: ?p, o: <X>} : (1)\n"
            "1 {s: ?x, p: ?p2, o: <Y>} : (0)",
            tgnew.asString());
        ASSERT_EQ(2u, tgnew._nodeMap.find(0)->second->_variables.size());
        ASSERT_EQ(2u, tgnew._nodeMap.find(1)->second->_variables.size());
      }
    }
  } catch (const std::exception& e) {
    std::cout << "Caught: " << e.what() << std::endl;
    FAIL() << e.what();
  }
}
Ejemplo n.º 15
0
THuiFxFilterType CHuiFxEffectParser::GetFilterTypeL( CMDXMLNode* aNode )
    {
#ifdef _HUI_FX_PARSER_LOGGING
    __ALFFXLOGSTRING1("CHuiFxEffectParser::GetFilterTypeL - 0x%x",this);
#endif
    if (aNode->NodeType() != CMDXMLNode::EElementNode)
        {
        FAIL(KErrGeneral, _L("Text node expected while reading filter type"));
        }
    
    TInt attributeIndex = ((CMDXMLElement*)aNode)->FindIndex( KLitType );

    if (attributeIndex == KErrNotFound)
        {
        FAIL(KErrGeneral, _L("Filter type not found"));
        }
    
    TPtrC attributeValue;
    TPtrC attributeName;
    User::LeaveIfError(((CMDXMLElement*)aNode)->AttributeDetails( attributeIndex, attributeName, attributeValue));

    if( attributeValue.Compare( KLitDesaturate ) == 0 )
        {
        return EFilterTypeDesaturate;
        }
    else if( attributeValue.Compare( KLitBlur ) == 0 )
        {
        return EFilterTypeBlur;
        }
    else if( attributeValue.Compare( KLitGlow ) == 0 )
        {
        return EFilterTypeGlow;
        }
    else if( attributeValue.Compare( KLitBrightnessContrast ) == 0 )
        {
        return EFilterTypeBrightnessContrast;
        }
    else if( attributeValue.Compare( KlitHSL ) == 0 )
        {
        return EFilterTypeHSL;
        }
    else if( attributeValue.Compare( KlitColorize ) == 0 )
        {
        return EFilterTypeColorize;
        }
    else if( attributeValue.Compare( KlitOutline ) == 0 )
        {
        return EFilterTypeOutline;
        }
    else if( attributeValue.Compare( KLitDropShadow ) == 0 )
        {
        // drop shadow is generated using outline filter
        return EFilterTypeOutline;
        }
    else if( attributeValue.Compare( KlitBevel ) == 0 )
        {
        return EFilterTypeBevel;
        }
    else if ( attributeValue.Compare ( KlitTransform ) == 0 )
        {
        return EFilterTypeTransform;
        }
    else
        {
        return EFilterTypeUnknown;
        }
    }
Ejemplo n.º 16
0
TEST fuzzy_hash_test(long size, long btree_node_size, int _commit)
{
	INIT();

	long *elements = malloc(sizeof(long) * size);
	long *nonelements = malloc(sizeof(long) * size);
	long *values = malloc(sizeof(long) * size);
	void **flatten_scores = malloc(sizeof(void *) * size);

	long btree_page = db->next_empty_page;
	RL_CALL_VERBOSE(rl_write, RL_OK, db, btree->type->btree_type, btree_page, btree);

	long i, element, value, *element_copy, *value_copy;

	long j, flatten_size;

	void *val, *tmp;

	for (i = 0; i < size; i++) {
		element = rand();
		value = rand();
		if (contains_element(element, elements, i)) {
			i--;
			continue;
		}
		else {
			RL_CALL_VERBOSE(rl_read, RL_FOUND, db, &rl_data_type_btree_hash_long_long, btree_page, &rl_btree_type_hash_long_long, &tmp, 1);
			elements[i] = element;
			element_copy = malloc(sizeof(long));
			*element_copy = element;
			values[i] = value;
			value_copy = malloc(sizeof(long));
			*value_copy = value;
			RL_CALL_VERBOSE(rl_btree_add_element, RL_OK, db, btree, btree_page, element_copy, value_copy);
			RL_CALL_VERBOSE(rl_btree_is_balanced, RL_OK, db, btree);
		}
		flatten_size = 0;
		RL_CALL_VERBOSE(rl_flatten_btree, RL_OK, db, btree, &flatten_scores, &flatten_size);
		for (j = 1; j < flatten_size; j++) {
			if (*(long *)flatten_scores[j - 1] >= *(long *)flatten_scores[j]) {
				fprintf(stderr, "Tree is in a bad state in element %ld after adding child %ld\n", j, i);
				retval = RL_UNEXPECTED;
				goto cleanup;
			}
		}
		if (_commit) {
			RL_CALL_VERBOSE(rl_commit, RL_OK, db);
			RL_CALL_VERBOSE(rl_read, RL_FOUND, db, &rl_data_type_btree_hash_long_long, btree_page, &rl_btree_type_hash_long_long, &tmp, 1);
			btree = tmp;
		}
	}

	for (i = 0; i < size; i++) {
		element = rand();
		if (contains_element(element, elements, size) || contains_element(element, nonelements, i)) {
			i--;
		}
		else {
			nonelements[i] = element;
		}
	}

	for (i = 0; i < size; i++) {
		RL_CALL_VERBOSE(rl_btree_find_score, RL_FOUND, db, btree, &elements[i], &val, NULL, NULL);
		EXPECT_LONG(*(long *)val, values[i]);
		RL_CALL_VERBOSE(rl_btree_find_score, RL_NOT_FOUND, db, btree, &nonelements[i], NULL, NULL, NULL);
	}

	retval = 0;
cleanup:
	free(values);
	free(elements);
	free(nonelements);
	free(flatten_scores);
	rl_close(db);
	if (retval == 0) { PASS(); } else { FAIL(); }
}
Ejemplo n.º 17
0
// Executes one line of 0-terminated G-Code. The line is assumed to contain only uppercase
// characters and signed floating point values (no whitespace). Comments and block delete
// characters have been removed. In this function, all units and positions are converted and 
// exported to grbl's internal functions in terms of (mm, mm/min) and absolute machine 
// coordinates, respectively.
uint8_t gc_execute_line(char *line) 
{
  /* -------------------------------------------------------------------------------------
     STEP 1: Initialize parser block struct and copy current g-code state modes. The parser
     updates these modes and commands as the block line is parser and will only be used and
     executed after successful error-checking. The parser block struct also contains a block
     values struct, word tracking variables, and a non-modal commands tracker for the new 
     block. This struct contains all of the necessary information to execute the block. */
     
  memset(&gc_block, 0, sizeof(gc_block)); // Initialize the parser block struct.
  memcpy(&gc_block.modal,&gc_state.modal,sizeof(gc_modal_t)); // Copy current modes
  uint8_t axis_command = AXIS_COMMAND_NONE;
  uint8_t axis_0, axis_1, axis_linear;
  uint8_t coord_select = 0; // Tracks G10 P coordinate selection for execution
  float coordinate_data[N_AXIS]; // Multi-use variable to store coordinate data for execution
  float parameter_data[N_AXIS]; // Multi-use variable to store parameter data for execution
  
  // Initialize bitflag tracking variables for axis indices compatible operations.
  uint8_t axis_words = 0; // XYZ tracking

  // Initialize command and value words variables. Tracks words contained in this block.
  uint16_t command_words = 0; // G and M command words. Also used for modal group violations.
  uint16_t value_words = 0; // Value words. 

  /* -------------------------------------------------------------------------------------
     STEP 2: Import all g-code words in the block line. A g-code word is a letter followed by
     a number, which can either be a 'G'/'M' command or sets/assigns a command value. Also, 
     perform initial error-checks for command word modal group violations, for any repeated
     words, and for negative values set for the value words F, N, P, T, and S. */
     
  uint8_t word_bit; // Bit-value for assigning tracking variables
  uint8_t char_counter = 0;  
  char letter;
  float value;
  uint8_t int_value = 0;
  uint8_t mantissa = 0; // NOTE: For mantissa values > 255, variable type must be changed to uint16_t.


  while (line[char_counter] != 0) { // Loop until no more g-code words in line.
    
    // Import the next g-code word, expecting a letter followed by a value. Otherwise, error out.
    letter = line[char_counter];
    if((letter < 'A') || (letter > 'Z')) { FAIL(STATUS_EXPECTED_COMMAND_LETTER); } // [Expected word letter]
    char_counter++;
    if (!read_float(line, &char_counter, &value)) { FAIL(STATUS_BAD_NUMBER_FORMAT); } // [Expected word value]

    // Convert values to smaller uint8 significand and mantissa values for parsing this word.
    // NOTE: Mantissa is multiplied by 100 to catch non-integer command values. This is more 
    // accurate than the NIST gcode requirement of x10 when used for commands, but not quite
    // accurate enough for value words that require integers to within 0.0001. This should be
    // a good enough comprimise and catch most all non-integer errors. To make it compliant, 
    // we would simply need to change the mantissa to int16, but this add compiled flash space.
    // Maybe update this later. 
    int_value = trunc(value);
    mantissa =  round(100*(value - int_value)); // Compute mantissa for Gxx.x commands.
    // NOTE: Rounding must be used to catch small floating point errors. 
    // Check if the g-code word is supported or errors due to modal group violations or has
    // been repeated in the g-code block. If ok, update the command or record its value.
    switch(letter) {
    
      /* 'G' and 'M' Command Words: Parse commands and check for modal group violations.
         NOTE: Modal group numbers are defined in Table 4 of NIST RS274-NGC v3, pg.20 */
         
      case 'G':
        // Determine 'G' command and its modal group
        switch(int_value) {
          case 1:
            if (axis_command) { FAIL(STATUS_GCODE_AXIS_COMMAND_CONFLICT); } // [Axis word/command conflict]
            axis_command = AXIS_COMMAND_MOTION_MODE; 
            gc_block.modal.motion = MOTION_MODE_LINEAR;
            word_bit = MODAL_GROUP_G1; 

            break;
          default: FAIL(STATUS_GCODE_UNSUPPORTED_COMMAND); // [Unsupported G command]
        }  
        if (mantissa > 0) { FAIL(STATUS_GCODE_COMMAND_VALUE_NOT_INTEGER); } // [Unsupported or invalid Gxx.x command]
        // Check for more than one command per modal group violations in the current block
        // NOTE: Variable 'word_bit' is always assigned, if the command is valid.
        if ( bit_istrue(command_words,bit(word_bit)) ) { FAIL(STATUS_GCODE_MODAL_GROUP_VIOLATION); }
        command_words |= bit(word_bit);
        break;
        
      case 'M':
        // Determine 'M' command and its modal group
        if (mantissa > 0) { FAIL(STATUS_GCODE_COMMAND_VALUE_NOT_INTEGER); } // [No Mxx.x commands]
        switch(int_value) {
          case 0: case 2:
            word_bit = MODAL_GROUP_M4; 
            switch(int_value) {
              case 0: gc_block.modal.program_flow = PROGRAM_FLOW_PAUSED; break; // Program pause
              case 2: gc_block.modal.program_flow = PROGRAM_FLOW_COMPLETED; break; // Program end and reset 
            }
            break;
          case 17: gc_block.modal.motor = MOTOR_ENABLE; break;
          case 18: gc_block.modal.motor = MOTOR_DISABLE; break;
          case 50: gc_block.modal.ldr = LDR_READ; break;
          case 70: gc_block.modal.laser = LASER_DISABLE; break;
          case 71: gc_block.modal.laser = LASER_ENABLE; break;

          default: FAIL(STATUS_GCODE_UNSUPPORTED_COMMAND); // [Unsupported M command]
        }            
      
        // Check for more than one command per modal group violations in the current block
        // NOTE: Variable 'word_bit' is always assigned, if the command is valid.
        if ( bit_istrue(command_words,bit(word_bit)) ) { FAIL(STATUS_GCODE_MODAL_GROUP_VIOLATION); }
        command_words |= bit(word_bit);
        break;
      
      // NOTE: All remaining letters assign values.
      default: 
  
        /* Non-Command Words: This initial parsing phase only checks for repeats of the remaining
           legal g-code words and stores their value. Error-checking is performed later since some
           words (I,J,K,L,P,R) have multiple connotations and/or depend on the issued commands. */
        switch(letter){
          case 'F': word_bit = WORD_F; gc_block.values.f = value; break;
          case 'T': word_bit = WORD_T; gc_block.values.t = int_value; break; // gc.values.t = int_value;
          case 'X': word_bit = WORD_X; gc_block.values.xyz[X_AXIS] = value; axis_words |= (1<<X_AXIS); break;
          /*case 'Y': word_bit = WORD_Y; gc_block.values.xyz[Y_AXIS] = value; axis_words |= (1<<Y_AXIS); break;
          case 'Z': word_bit = WORD_Z; gc_block.values.xyz[Z_AXIS] = value; axis_words |= (1<<Z_AXIS); break;*/
          default: FAIL(STATUS_GCODE_UNSUPPORTED_COMMAND);
        } 
        
        // NOTE: Variable 'word_bit' is always assigned, if the non-command letter is valid.
        if (bit_istrue(value_words,bit(word_bit))) { FAIL(STATUS_GCODE_WORD_REPEATED); } // [Word repeated]
        // Check for invalid negative values for words F, N, P, T, and S.
        // NOTE: Negative value check is done here simply for code-efficiency.
        if ( bit(word_bit) & (bit(WORD_F)|bit(WORD_N)|bit(WORD_P)|bit(WORD_T)|bit(WORD_S)) ) {
          if (value < 0.0) { FAIL(STATUS_NEGATIVE_VALUE); } // [Word value cannot be negative]
        }
        value_words |= bit(word_bit); // Flag to indicate parameter assigned.
      
    }   
  } 
  // Parsing complete!
  

  /* -------------------------------------------------------------------------------------
     STEP 3: Error-check all commands and values passed in this block. This step ensures all of
     the commands are valid for execution and follows the NIST standard as closely as possible.
     If an error is found, all commands and values in this block are dumped and will not update
     the active system g-code modes. If the block is ok, the active system g-code modes will be
     updated based on the commands of this block, and signal for it to be executed. 
     
     Also, we have to pre-convert all of the values passed based on the modes set by the parsed
     block. There are a number of error-checks that require target information that can only be
     accurately calculated if we convert these values in conjunction with the error-checking.
     This relegates the next execution step as only updating the system g-code modes and 
     performing the programmed actions in order. The execution step should not require any 
     conversion calculations and would only require minimal checks necessary to execute.
  */

  /* NOTE: At this point, the g-code block has been parsed and the block line can be freed.
     NOTE: It's also possible, at some future point, to break up STEP 2, to allow piece-wise 
     parsing of the block on a per-word basis, rather than the entire block. This could remove 
     the need for maintaining a large string variable for the entire block and free up some memory. 
     To do this, this would simply need to retain all of the data in STEP 1, such as the new block
     data struct, the modal group and value bitflag tracking variables, and axis array indices 
     compatible variables. This data contains all of the information necessary to error-check the 
     new g-code block when the EOL character is received. However, this would break Grbl's startup
     lines in how it currently works and would require some refactoring to make it compatible.
  */  
  
  // [0. Non-specific/common error-checks and miscellaneous setup]: 
  
  // Determine implicit axis command conditions. Axis words have been passed, but no explicit axis
  // command has been sent. If so, set axis command to current motion mode.
  if (axis_words) {
    if (!axis_command) { axis_command = AXIS_COMMAND_MOTION_MODE; } // Assign implicit motion-mode
  }
  
  // Check for valid line number N value.
  if (bit_istrue(value_words,bit(WORD_N))) {
    // Line number value cannot be less than zero (done) or greater than max line number.
    if (gc_block.values.n > MAX_LINE_NUMBER) { FAIL(STATUS_GCODE_INVALID_LINE_NUMBER); } // [Exceeds max line number]
  }
  // bit_false(value_words,bit(WORD_N)); // NOTE: Single-meaning value word. Set at end of error-checking.
  
  // Track for unused words at the end of error-checking.
  // NOTE: Single-meaning value words are removed all at once at the end of error-checking, because
  // they are always used when present. This was done to save a few bytes of flash. For clarity, the
  // single-meaning value words may be removed as they are used. Also, axis words are treated in the
  // same way. If there is an explicit/implicit axis command, XYZ words are always used and are 
  // are removed at the end of error-checking.  
  
  // [1. Comments ]: MSG's NOT SUPPORTED. Comment handling performed by protocol.
  
  // [2. Set feed rate mode ]: G93 F word missing with G1,G2/3 active, implicitly or explicitly. Feed rate
  //   is not defined after switching to G94 from G93.
  if (gc_block.modal.feed_rate == FEED_RATE_MODE_INVERSE_TIME) { // = G93
    // NOTE: G38 can also operate in inverse time, but is undefined as an error. Missing F word check added here.
    if (axis_command == AXIS_COMMAND_MOTION_MODE) { 
      if ((gc_block.modal.motion != MOTION_MODE_NONE) || (gc_block.modal.motion != MOTION_MODE_SEEK)) {
        if (bit_isfalse(value_words,bit(WORD_F))) { FAIL(STATUS_GCODE_UNDEFINED_FEED_RATE); } // [F word missing]
      }
    }
    // NOTE: It seems redundant to check for an F word to be passed after switching from G94 to G93. We would
    // accomplish the exact same thing if the feed rate value is always reset to zero and undefined after each
    // inverse time block, since the commands that use this value already perform undefined checks. This would
    // also allow other commands, following this switch, to execute and not error out needlessly. This code is 
    // combined with the above feed rate mode and the below set feed rate error-checking.

    // [3. Set feed rate ]: F is negative (done.)
    // - In inverse time mode: Always implicitly zero the feed rate value before and after block completion.
    // NOTE: If in G93 mode or switched into it from G94, just keep F value as initialized zero or passed F word 
    // value in the block. If no F word is passed with a motion command that requires a feed rate, this will error 
    // out in the motion modes error-checking. However, if no F word is passed with NO motion command that requires
    // a feed rate, we simply move on and the state feed rate value gets updated to zero and remains undefined.
  } else { // = G94
    // - In units per mm mode: If F word passed, ensure value is in mm/min, otherwise push last state value.
    if (gc_state.modal.feed_rate == FEED_RATE_MODE_UNITS_PER_MIN) { // Last state is also G94
      if (bit_istrue(value_words,bit(WORD_F))) {
        if (gc_block.modal.units == UNITS_MODE_INCHES) { gc_block.values.f *= MM_PER_INCH; }
      } else {
        gc_block.values.f = gc_state.feed_rate/60; // Push last state feed rate. Convert deg/min to deg/sec
      }
    } // Else, switching to G94 from G93, so don't push last state feed rate. Its undefined or the passed F word value.
  } 
  // bit_false(value_words,bit(WORD_F)); // NOTE: Single-meaning value word. Set at end of error-checking.
  
  // [4. Set spindle speed ]: S is negative (done.)
  if (bit_isfalse(value_words,bit(WORD_S))) { gc_block.values.s = gc_state.spindle_speed; }
  // bit_false(value_words,bit(WORD_S)); // NOTE: Single-meaning value word. Set at end of error-checking.
    
  // [5. Select tool ]: NOT SUPPORTED. Only tracks value. T is negative (done.) Not an integer. Greater than max tool value.
  // bit_false(value_words,bit(WORD_T)); // NOTE: Single-meaning value word. Set at end of error-checking.

  // [6. Change tool ]: N/A
  // [7. Spindle control ]: N/A
  // [8. Coolant control ]: N/A
  // [9. Enable/disable feed rate or spindle overrides ]: NOT SUPPORTED.
  
  // [10. Dwell ]: P value missing. P is negative (done.) NOTE: See below.
  if (gc_block.non_modal_command == NON_MODAL_DWELL) {
    if (bit_isfalse(value_words,bit(WORD_P))) { FAIL(STATUS_GCODE_VALUE_WORD_MISSING); } // [P word missing]
    bit_false(value_words,bit(WORD_P));
  }
  
  // [11. Set active plane ]: N/A
  switch (gc_block.modal.plane_select) {
    case PLANE_SELECT_XY:
      axis_0 = X_AXIS;
      axis_1 = Y_AXIS;
      axis_linear = Z_AXIS;
      break;
    case PLANE_SELECT_ZX:
      axis_0 = Z_AXIS;
      axis_1 = X_AXIS;
      axis_linear = Y_AXIS;
      break;
    default: // case PLANE_SELECT_YZ:
      axis_0 = Y_AXIS;
      axis_1 = Z_AXIS;
      axis_linear = X_AXIS;
  }   
            
  // [12. Set length units ]: N/A
  // Pre-convert XYZ coordinate values to millimeters, if applicable.
  uint8_t idx;
  if (gc_block.modal.units == UNITS_MODE_INCHES) {
    for (idx=0; idx<N_AXIS; idx++) { // Axes indices are consistent, so loop may be used.
      if (bit_istrue(axis_words,bit(idx)) ) {
        gc_block.values.xyz[idx] *= MM_PER_INCH;
      }
    }
  }
  
  // [13. Cutter radius compensation ]: NOT SUPPORTED. Error, if G53 is active.
  
  // [14. Cutter length compensation ]: G43 NOT SUPPORTED, but G43.1 and G49 are. 
  // [G43.1 Errors]: Motion command in same line. 
  //   NOTE: Although not explicitly stated so, G43.1 should be applied to only one valid 
  //   axis that is configured (in config.h). There should be an error if the configured axis
  //   is absent or if any of the other axis words are present.
  if (axis_command == AXIS_COMMAND_TOOL_LENGTH_OFFSET ) { // Indicates called in block.
    if (gc_block.modal.tool_length == TOOL_LENGTH_OFFSET_ENABLE_DYNAMIC) {
      if (axis_words ^ (1<<TOOL_LENGTH_OFFSET_AXIS)) { FAIL(STATUS_GCODE_G43_DYNAMIC_AXIS_ERROR); }
    }
  }
  
  // [15. Coordinate system selection ]: *N/A. Error, if cutter radius comp is active.
  // TODO: An EEPROM read of the coordinate data may require a buffer sync when the cycle
  // is active. The read pauses the processor temporarily and may cause a rare crash. For 
  // future versions on processors with enough memory, all coordinate data should be stored
  // in memory and written to EEPROM only when there is not a cycle active.
  memcpy(coordinate_data,gc_state.coord_system,sizeof(gc_state.coord_system));
  if ( bit_istrue(command_words,bit(MODAL_GROUP_G12)) ) { // Check if called in block
    if (gc_block.modal.coord_select > N_COORDINATE_SYSTEM) { FAIL(STATUS_GCODE_UNSUPPORTED_COORD_SYS); } // [Greater than N sys]
    if (gc_state.modal.coord_select != gc_block.modal.coord_select) {
      if (!(settings_read_coord_data(gc_block.modal.coord_select,coordinate_data))) { FAIL(STATUS_SETTING_READ_FAIL); } 
    }
  }
  
  // [16. Set path control mode ]: NOT SUPPORTED.
  // [17. Set distance mode ]: N/A. G90.1 and G91.1 NOT SUPPORTED.
  // [18. Set retract mode ]: NOT SUPPORTED.
  
  // [19. Remaining non-modal actions ]: Check go to predefined position, set G10, or set axis offsets.
  // NOTE: We need to separate the non-modal commands that are axis word-using (G10/G28/G30/G92), as these
  // commands all treat axis words differently. G10 as absolute offsets or computes current position as
  // the axis value, G92 similarly to G10 L20, and G28/30 as an intermediate target position that observes
  // all the current coordinate system and G92 offsets. 
  switch (gc_block.non_modal_command) {
    case NON_MODAL_SET_COORDINATE_DATA:  
      // [G10 Errors]: L missing and is not 2 or 20. P word missing. (Negative P value done.)
      // [G10 L2 Errors]: R word NOT SUPPORTED. P value not 0 to nCoordSys(max 9). Axis words missing.
      // [G10 L20 Errors]: P must be 0 to nCoordSys(max 9). Axis words missing.
      if (!axis_words) { FAIL(STATUS_GCODE_NO_AXIS_WORDS) }; // [No axis words]
      if (bit_isfalse(value_words,((1<<WORD_P)|(1<<WORD_L)))) { FAIL(STATUS_GCODE_VALUE_WORD_MISSING); } // [P/L word missing]
      coord_select = trunc(gc_block.values.p); // Convert p value to int.
      if (coord_select > N_COORDINATE_SYSTEM) { FAIL(STATUS_GCODE_UNSUPPORTED_COORD_SYS); } // [Greater than N sys]
      if (gc_block.values.l != 20) {
        if (gc_block.values.l == 2) {
          if (bit_istrue(value_words,bit(WORD_R))) { FAIL(STATUS_GCODE_UNSUPPORTED_COMMAND); } // [G10 L2 R not supported]
        } else { FAIL(STATUS_GCODE_UNSUPPORTED_COMMAND); } // [Unsupported L]
      }
      bit_false(value_words,(bit(WORD_L)|bit(WORD_P)));
      
      // Determine coordinate system to change and try to load from EEPROM.
      if (coord_select > 0) { coord_select--; } // Adjust P1-P6 index to EEPROM coordinate data indexing.
      else { coord_select = gc_block.modal.coord_select; } // Index P0 as the active coordinate system
      if (!settings_read_coord_data(coord_select,parameter_data)) { FAIL(STATUS_SETTING_READ_FAIL); } // [EEPROM read fail]
    
      // Pre-calculate the coordinate data changes. NOTE: Uses parameter_data since coordinate_data may be in use by G54-59.
      for (idx=0; idx<N_AXIS; idx++) { // Axes indices are consistent, so loop may be used.
        // Update axes defined only in block. Always in machine coordinates. Can change non-active system.
        if (bit_istrue(axis_words,bit(idx)) ) {
          if (gc_block.values.l == 20) {
            // L20: Update coordinate system axis at current position (with modifiers) with programmed value
            parameter_data[idx] = gc_state.position[idx]-gc_state.coord_offset[idx]-gc_block.values.xyz[idx];
            if (idx == TOOL_LENGTH_OFFSET_AXIS) { parameter_data[idx] -= gc_state.tool_length_offset; }
          } else {
            // L2: Update coordinate system axis to programmed value.
            parameter_data[idx] = gc_block.values.xyz[idx]; 
          }
        }
      }
      break;
    case NON_MODAL_SET_COORDINATE_OFFSET:
      // [G92 Errors]: No axis words.
      if (!axis_words) { FAIL(STATUS_GCODE_NO_AXIS_WORDS); } // [No axis words]
    
      // Update axes defined only in block. Offsets current system to defined value. Does not update when
      // active coordinate system is selected, but is still active unless G92.1 disables it. 
      for (idx=0; idx<N_AXIS; idx++) { // Axes indices are consistent, so loop may be used.
        if (bit_istrue(axis_words,bit(idx)) ) {
          gc_block.values.xyz[idx] = gc_state.position[idx]-coordinate_data[idx]-gc_block.values.xyz[idx];
          if (idx == TOOL_LENGTH_OFFSET_AXIS) { gc_block.values.xyz[idx] -= gc_state.tool_length_offset; }
        } else {
          gc_block.values.xyz[idx] = gc_state.coord_offset[idx];
        }
      }
      break;
      
    default:

      // At this point, the rest of the explicit axis commands treat the axis values as the traditional
      // target position with the coordinate system offsets, G92 offsets, absolute override, and distance
      // modes applied. This includes the motion mode commands. We can now pre-compute the target position.
      // NOTE: Tool offsets may be appended to these conversions when/if this feature is added.
      if (axis_command != AXIS_COMMAND_TOOL_LENGTH_OFFSET ) { // TLO block any axis command.
        if (axis_words) {
          for (idx=0; idx<N_AXIS; idx++) { // Axes indices are consistent, so loop may be used to save flash space.
            if ( bit_isfalse(axis_words,bit(idx)) ) {
              gc_block.values.xyz[idx] = gc_state.position[idx]; // No axis word in block. Keep same axis position.
            } else {
              // Update specified value according to distance mode or ignore if absolute override is active.
              // NOTE: G53 is never active with G28/30 since they are in the same modal group.
              if (gc_block.non_modal_command != NON_MODAL_ABSOLUTE_OVERRIDE) {
                // Apply coordinate offsets based on distance mode.
                if (gc_block.modal.distance == DISTANCE_MODE_ABSOLUTE) {
                  gc_block.values.xyz[idx] += coordinate_data[idx] + gc_state.coord_offset[idx];
                  if (idx == TOOL_LENGTH_OFFSET_AXIS) { gc_block.values.xyz[idx] += gc_state.tool_length_offset; }
                } else {  // Incremental mode
                  gc_block.values.xyz[idx] += gc_state.position[idx];
                }
              }
            }
          }
        }
      }
          
      // Check remaining non-modal commands for errors.
      switch (gc_block.non_modal_command) {        
        case NON_MODAL_GO_HOME_0:
          // [G28 Errors]: Cutter compensation is enabled. 
          // Retreive G28 go-home position data (in machine coordinates) from EEPROM
          if (!axis_words) { axis_command = AXIS_COMMAND_NONE; } // Set to none if no intermediate motion.
          if (!settings_read_coord_data(SETTING_INDEX_G28,parameter_data)) { FAIL(STATUS_SETTING_READ_FAIL); }
          break;
        case NON_MODAL_GO_HOME_1:
          // [G30 Errors]: Cutter compensation is enabled. 
          // Retreive G30 go-home position data (in machine coordinates) from EEPROM
          if (!axis_words) { axis_command = AXIS_COMMAND_NONE; } // Set to none if no intermediate motion.
          if (!settings_read_coord_data(SETTING_INDEX_G30,parameter_data)) { FAIL(STATUS_SETTING_READ_FAIL); }
          break;
        case NON_MODAL_SET_HOME_0: case NON_MODAL_SET_HOME_1:
          // [G28.1/30.1 Errors]: Cutter compensation is enabled. 
          // NOTE: If axis words are passed here, they are interpreted as an implicit motion mode.
          break;
        case NON_MODAL_RESET_COORDINATE_OFFSET:
          // NOTE: If axis words are passed here, they are interpreted as an implicit motion mode.
          break;
        case NON_MODAL_ABSOLUTE_OVERRIDE:
          // [G53 Errors]: G0 and G1 are not active. Cutter compensation is enabled.
          // NOTE: All explicit axis word commands are in this modal group. So no implicit check necessary.
          if (!(gc_block.modal.motion == MOTION_MODE_SEEK || gc_block.modal.motion == MOTION_MODE_LINEAR)) {
            FAIL(STATUS_GCODE_G53_INVALID_MOTION_MODE); // [G53 G0/1 not active]
          }
          break;
      }
  }
      
  // [20. Motion modes ]: 
  if (gc_block.modal.motion == MOTION_MODE_NONE) {
    // [G80 Errors]: Axis word exist and are not used by a non-modal command.
    if ((axis_words) && (axis_command != AXIS_COMMAND_NON_MODAL)) { 
      FAIL(STATUS_GCODE_AXIS_WORDS_EXIST); // [No axis words allowed]
    }

  // Check remaining motion modes, if axis word are implicit (exist and not used by G10/28/30/92), or 
  // was explicitly commanded in the g-code block.
  } else if ( axis_command == AXIS_COMMAND_MOTION_MODE ) {
  
    if (gc_block.modal.motion == MOTION_MODE_SEEK) {
      // [G0 Errors]: Axis letter not configured or without real value (done.)
      // Axis words are optional. If missing, set axis command flag to ignore execution.
      if (!axis_words) { axis_command = AXIS_COMMAND_NONE; }

    // All remaining motion modes (all but G0 and G80), require a valid feed rate value. In units per mm mode,
    // the value must be positive. In inverse time mode, a positive value must be passed with each block.
    } else {      
      // Check if feed rate is defined for the motion modes that require it.
      if (gc_block.values.f == 0.0) { FAIL(STATUS_GCODE_UNDEFINED_FEED_RATE); } // [Feed rate undefined]
     
      switch (gc_block.modal.motion) {
        case MOTION_MODE_LINEAR: 
          // [G1 Errors]: Feed rate undefined. Axis letter not configured or without real value.
          // Axis words are optional. If missing, set axis command flag to ignore execution.
          if (!axis_words) { axis_command = AXIS_COMMAND_NONE; }

          break;
        case MOTION_MODE_PROBE:
          // [G38 Errors]: Target is same current. No axis words. Cutter compensation is enabled. Feed rate
          //   is undefined. Probe is triggered. NOTE: Probe check moved to probe cycle. Instead of returning
          //   an error, it issues an alarm to prevent further motion to the probe. It's also done there to 
          //   allow the planner buffer to empty and move off the probe trigger before another probing cycle.
          if (!axis_words) { FAIL(STATUS_GCODE_NO_AXIS_WORDS); } // [No axis words]
          if (gc_check_same_position(gc_state.position, gc_block.values.xyz)) { FAIL(STATUS_GCODE_INVALID_TARGET); } // [Invalid target]
          break;
      } 
    }
  }
  
  // [21. Program flow ]: No error checks required.

  // [0. Non-specific error-checks]: Complete unused value words check,
  // radius mode, or axis words that aren't used in the block.  
  bit_false(value_words,(bit(WORD_N)|bit(WORD_F)|bit(WORD_S)|bit(WORD_T))); // Remove single-meaning value words. 
  if (axis_command) { bit_false(value_words,(bit(WORD_X)|bit(WORD_Y)|bit(WORD_Z))); } // Remove axis words. 
  if (value_words) { FAIL(STATUS_GCODE_UNUSED_WORDS); } // [Unused words]

   
  /* -------------------------------------------------------------------------------------
     STEP 4: EXECUTE!!
     Assumes that all error-checking has been completed and no failure modes exist. We just
     need to update the state and execute the block according to the order-of-execution.
  */ 
  
  // [1. Comments feedback ]:  NOT SUPPORTED
  
  // [2. Set feed rate mode ]:
  gc_state.modal.feed_rate = gc_block.modal.feed_rate;
  
  // [3. Set feed rate ]:
  gc_state.feed_rate = gc_block.values.f*60; // Always copy this value. See feed rate error-checking. Convert deg/sec to deg/min

  /*// [4. Set spindle speed ]:
  if (gc_state.spindle_speed != gc_block.values.s) { 
    gc_state.spindle_speed = gc_block.values.s; 
    
    // Update running spindle only if not in check mode and not already enabled.
    if (gc_state.modal.spindle != SPINDLE_DISABLE) { spindle_run(gc_state.modal.spindle, gc_state.spindle_speed); }
  }*/
    
  // [5. Select tool ]: NOT SUPPORTED. Only tracks tool value.
  gc_state.tool = gc_block.values.t;

  // [6. Change tool ]: NOT SUPPORTED
  // [7. Spindle control ]: NOT SUPPORTED
  // [8. Coolant control ]: NOT SUPPORTED
  // [9. Enable/disable feed rate or spindle overrides ]: NOT SUPPORTED

  // [10. Dwell ]:
  if (gc_block.non_modal_command == NON_MODAL_DWELL) { mc_dwell(gc_block.values.p); }
  
  // [11. Set active plane ]:
  gc_state.modal.plane_select = gc_block.modal.plane_select;  

  // [12. Set length units ]: NOT SUPPORTED
  // [13. Cutter radius compensation ]: NOT SUPPORTED

  // [14. Cutter length compensation ]: G43.1 and G49 supported. G43 NOT SUPPORTED.
  // NOTE: If G43 were supported, its operation wouldn't be any different from G43.1 in terms
  // of execution. The error-checking step would simply load the offset value into the correct
  // axis of the block XYZ value array. 
  if (axis_command == AXIS_COMMAND_TOOL_LENGTH_OFFSET ) { // Indicates a change.
    gc_state.modal.tool_length = gc_block.modal.tool_length;
    if (gc_state.modal.tool_length == TOOL_LENGTH_OFFSET_ENABLE_DYNAMIC) { // G43.1
      gc_state.tool_length_offset = gc_block.values.xyz[TOOL_LENGTH_OFFSET_AXIS];
    } else { // G49
      gc_state.tool_length_offset = 0.0;
    }
  }
  
  // [15. Coordinate system selection ]:
  if (gc_state.modal.coord_select != gc_block.modal.coord_select) {
    gc_state.modal.coord_select = gc_block.modal.coord_select;
    memcpy(gc_state.coord_system,coordinate_data,sizeof(coordinate_data));
  }
  
  // [16. Set path control mode ]: NOT SUPPORTED
  
  // [17. Set distance mode ]:
  gc_state.modal.distance = gc_block.modal.distance;
  
  // [18. Set retract mode ]: NOT SUPPORTED
    
  // [19. Go to predefined position, Set G10, or Set axis offsets ]:
  switch(gc_block.non_modal_command) {
    case NON_MODAL_SET_COORDINATE_DATA:    
      settings_write_coord_data(coord_select,parameter_data);
      // Update system coordinate system if currently active.
      if (gc_state.modal.coord_select == coord_select) { memcpy(gc_state.coord_system,parameter_data,sizeof(parameter_data)); }
      break;
    case NON_MODAL_GO_HOME_0: case NON_MODAL_GO_HOME_1: 
      // Move to intermediate position before going home. Obeys current coordinate system and offsets 
      // and absolute and incremental modes.
      if (axis_command) {
        #ifdef USE_LINE_NUMBERS
          mc_line(gc_block.values.xyz, -1.0, false, gc_block.values.n);
        #else
          mc_line(gc_block.values.xyz, -1.0, false);
        #endif
      }
      #ifdef USE_LINE_NUMBERS
        mc_line(parameter_data, -1.0, false, gc_block.values.n); 
      #else
        mc_line(parameter_data, -1.0, false); 
      #endif
      memcpy(gc_state.position, parameter_data, sizeof(parameter_data));
      break;
    case NON_MODAL_SET_HOME_0: 
      settings_write_coord_data(SETTING_INDEX_G28,gc_state.position);
      break;
    case NON_MODAL_SET_HOME_1:
      settings_write_coord_data(SETTING_INDEX_G30,gc_state.position);
      break;
    case NON_MODAL_SET_COORDINATE_OFFSET:
      memcpy(gc_state.coord_offset,gc_block.values.xyz,sizeof(gc_block.values.xyz));
      break;
    case NON_MODAL_RESET_COORDINATE_OFFSET: 
      clear_vector(gc_state.coord_offset); // Disable G92 offsets by zeroing offset vector.
      break;
  }

  
  // [20. Motion modes ]:
  // NOTE: Commands G10,G28,G30,G92 lock out and prevent axis words from use in motion modes. 
  // Enter motion modes only if there are axis words or a motion mode command word in the block.
  gc_state.modal.motion = gc_block.modal.motion;
    if (axis_command == AXIS_COMMAND_MOTION_MODE) {
      switch (gc_state.modal.motion) {
        case MOTION_MODE_SEEK:
          #ifdef USE_LINE_NUMBERS
            mc_line(gc_block.values.xyz, -1.0, false, gc_block.values.n);
          #else
            mc_line(gc_block.values.xyz, -1.0, false);
          #endif
          break;
        case MOTION_MODE_LINEAR:
          #ifdef USE_LINE_NUMBERS
            mc_line(gc_block.values.xyz, gc_state.feed_rate, gc_state.modal.feed_rate, gc_block.values.n);
          #else
            mc_line(gc_block.values.xyz, gc_state.feed_rate, gc_state.modal.feed_rate);
          #endif
          break;
        case MOTION_MODE_PROBE:
          // NOTE: gc_block.values.xyz is returned from mc_probe_cycle with the updated position value. So
          // upon a successful probing cycle, the machine position and the returned value should be the same.
          #ifdef USE_LINE_NUMBERS
            mc_probe_cycle(gc_block.values.xyz, gc_state.feed_rate, gc_state.modal.feed_rate, gc_block.values.n);
          #else
            mc_probe_cycle(gc_block.values.xyz, gc_state.feed_rate, gc_state.modal.feed_rate);
          #endif
      }
    
      // As far as the parser is concerned, the position is now == target. In reality the
      // motion control system might still be processing the action and the real tool position
      // in any intermediate location.
      memcpy(gc_state.position, gc_block.values.xyz, sizeof(gc_block.values.xyz)); // gc.position[] = target[];
    }
  
  // [21. Program flow ]:
  // M0,M2: Perform non-running program flow actions. During a program pause, the buffer may 
  // refill and can only be resumed by the cycle start run-time command.
  gc_state.modal.program_flow = gc_block.modal.program_flow;
  if (gc_state.modal.program_flow) { 
    protocol_buffer_synchronize(); // Finish all remaining buffered motions. Program paused when complete.
    sys.auto_start = false; // Disable auto cycle start. Forces pause until cycle start issued.
  
    // If complete, reset to reload defaults (G92.2,G54,G17,G90,G94,M48,G40,M5,M9). Otherwise,
    // re-enable program flow after pause complete, where cycle start will resume the program.
    if (gc_state.modal.program_flow == PROGRAM_FLOW_COMPLETED) { mc_reset(); }
    else { gc_state.modal.program_flow = PROGRAM_FLOW_RUNNING; }
  }

  // [22. Laser control ]:  
  gc_state.modal.laser = gc_block.modal.laser;
  laser_run(gc_block.values.t, gc_block.modal.laser);

  // [23. Motor control ]:  
  gc_state.modal.motor = gc_block.modal.motor;
  if (gc_block.modal.motor == MOTOR_ENABLE) {
    st_disable_on_idle(false);
    st_wake_up();
  }
  else {
    st_disable_on_idle(true);
    st_go_idle();
  }
  // [23. LDR read ]:
  if (gc_block.modal.ldr == LDR_READ){
      print_ldr(gc_block.values.t);
  }

  // TODO: % to denote start of program. Sets auto cycle start?
  return(STATUS_OK);
}
Ejemplo n.º 18
0
TEST fuzzy_hash_test_iterator(long size, long btree_node_size, int _commit)
{
	INIT();

	rl_btree_iterator *iterator = NULL;
	long *elements = malloc(sizeof(long) * size);
	long *nonelements = malloc(sizeof(long) * size);
	long *values = malloc(sizeof(long) * size);

	long btree_page = db->next_empty_page;
	RL_CALL_VERBOSE(rl_write, RL_OK, db, btree->type->btree_type, btree_page, btree);

	long i, element, value, *element_copy, *value_copy;

	long j;

	void *tmp;
	long prev_score = -1.0, score;

	for (i = 0; i < size; i++) {
		element = rand();
		value = rand();
		if (contains_element(element, elements, i)) {
			i--;
			continue;
		}
		else {
			elements[i] = element;
			element_copy = malloc(sizeof(long));
			*element_copy = element;
			values[i] = value;
			value_copy = malloc(sizeof(long));
			*value_copy = value;
			RL_CALL_VERBOSE(rl_btree_add_element, RL_OK, db, btree, btree_page, element_copy, value_copy);
			RL_CALL_VERBOSE(rl_btree_is_balanced, RL_OK, db, btree);
		}

		RL_CALL_VERBOSE(rl_btree_iterator_create, RL_OK, db, btree, &iterator);
		EXPECT_LONG(iterator->size, i + 1);

		j = 0;
		while (RL_OK == (retval = rl_btree_iterator_next(iterator, &tmp, NULL))) {
			score = *(long *)tmp;
			rl_free(tmp);
			if (j++ > 0) {
				if (prev_score >= score) {
					fprintf(stderr, "Tree is in a bad state in element %ld after adding child %ld\n", j, i);
					retval = RL_UNEXPECTED;
					goto cleanup;
				}
			}
			prev_score = score;
		}

		if (retval != RL_END) {
			rl_free(tmp);
			goto cleanup;
		}

		EXPECT_LONG(j, i + 1);
		iterator = NULL;

		if (_commit) {
			RL_CALL_VERBOSE(rl_commit, RL_OK, db);
			RL_CALL_VERBOSE(rl_read, RL_FOUND, db, &rl_data_type_btree_hash_long_long, btree_page, &rl_btree_type_hash_long_long, &tmp, 1);
			btree = tmp;
		}
	}


	rl_btree_iterator_destroy(iterator);
	retval = 0;
cleanup:
	free(values);
	free(elements);
	free(nonelements);
	rl_close(db);
	if (retval == 0) { PASS(); } else { FAIL(); }
}
Ejemplo n.º 19
0
SurfaceTexture::SurfaceTexture( JNIEnv * jni_ ) :
	textureId( 0 ),
	javaObject( NULL ),
	jni( NULL ),
	nanoTimeStamp( 0 ),
	updateTexImageMethodId( NULL ),
	getTimestampMethodId( NULL ),
	setDefaultBufferSizeMethodId( NULL )
{
#if defined( OVR_OS_ANDROID )
	jni = jni_;

	// Gen a gl texture id for the java SurfaceTexture to use.
	glGenTextures( 1, &textureId );
	glBindTexture( GL_TEXTURE_EXTERNAL_OES, textureId );
	glTexParameterf( GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
	glTexParameterf( GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
	glTexParameterf( GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
	glTexParameterf( GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
	glBindTexture( GL_TEXTURE_EXTERNAL_OES, 0 );

	static const char * className = "android/graphics/SurfaceTexture";
	const jclass surfaceTextureClass = jni->FindClass(className);
	if ( surfaceTextureClass == 0 ) {
		FAIL( "FindClass( %s ) failed", className );
	}

	// find the constructor that takes an int
	const jmethodID constructor = jni->GetMethodID( surfaceTextureClass, "<init>", "(I)V" );
	if ( constructor == 0 ) {
		FAIL( "GetMethodID( <init> ) failed" );
	}

	jobject obj = jni->NewObject( surfaceTextureClass, constructor, textureId );
	if ( obj == 0 ) {
		FAIL( "NewObject() failed" );
	}

	javaObject = jni->NewGlobalRef( obj );
	if ( javaObject == 0 ) {
		FAIL( "NewGlobalRef() failed" );
	}

	// Now that we have a globalRef, we can free the localRef
	jni->DeleteLocalRef( obj );

    updateTexImageMethodId = jni->GetMethodID( surfaceTextureClass, "updateTexImage", "()V" );
    if ( !updateTexImageMethodId ) {
    	FAIL( "couldn't get updateTexImageMethodId" );
    }

    getTimestampMethodId = jni->GetMethodID( surfaceTextureClass, "getTimestamp", "()J" );
    if ( !getTimestampMethodId ) {
    	FAIL( "couldn't get getTimestampMethodId" );
    }

	setDefaultBufferSizeMethodId = jni->GetMethodID( surfaceTextureClass, "setDefaultBufferSize", "(II)V" );
    if ( !setDefaultBufferSizeMethodId ) {
		FAIL( "couldn't get setDefaultBufferSize" );
    }

	// jclass objects are localRefs that need to be freed
	jni->DeleteLocalRef( surfaceTextureClass );
#endif
}
Ejemplo n.º 20
0
static void
test_chacha_stream(const struct tstring *key,
		    const struct tstring *iv,
		    const struct tstring *ciphertext,
		    const struct tstring *xor_ref)
{
  struct chacha_ctx ctx;
  uint8_t data[STREAM_LENGTH + 1];
  uint8_t stream[STREAM_LENGTH + 1];
  uint8_t xor[CHACHA_BLOCK_SIZE];
  size_t j;

  ASSERT (iv->length == CHACHA_IV_SIZE);
  ASSERT (ciphertext->length == 4*CHACHA_BLOCK_SIZE);
  ASSERT (xor_ref->length == CHACHA_BLOCK_SIZE);

  chacha_set_key(&ctx, key->length, key->data);
  chacha_set_iv(&ctx, iv->data);
  memset(stream, 0, STREAM_LENGTH + 1);
  chacha_crypt(&ctx, STREAM_LENGTH, stream, stream);
  if (stream[STREAM_LENGTH])
    {
      fprintf(stderr, "Stream of %d bytes wrote too much!\n", STREAM_LENGTH);
      FAIL();
    }
  if (!MEMEQ (64, stream, ciphertext->data))
    {
      fprintf(stderr, "Error failed, offset 0:\n");
      fprintf(stderr, "\nOutput: ");
      print_hex(64, stream);
      fprintf(stderr, "\nExpected:");
      print_hex(64, ciphertext->data);
      fprintf(stderr, "\n");
      FAIL();
    }
  if (!MEMEQ (128, stream + 192, ciphertext->data + 64))
    {
      fprintf(stderr, "Error failed, offset 192:\n");
      fprintf(stderr, "\nOutput: ");
      print_hex(128, stream + 192);
      fprintf(stderr, "\nExpected:");
      print_hex(64, ciphertext->data + 64);
      fprintf(stderr, "\n");
      FAIL();
    }
  if (!MEMEQ (64, stream + 448, ciphertext->data + 192))
    {
      fprintf(stderr, "Error failed, offset 448:\n");
      fprintf(stderr, "\nOutput: ");
      print_hex(64, stream + 448);
      fprintf(stderr, "\nExpected:");
      print_hex(64, ciphertext->data + 192);
      fprintf(stderr, "\n");
      FAIL();
    }

  memxor3 (xor, stream, stream + CHACHA_BLOCK_SIZE, CHACHA_BLOCK_SIZE);
  for (j = 2*CHACHA_BLOCK_SIZE; j < STREAM_LENGTH; j += CHACHA_BLOCK_SIZE)
    memxor (xor, stream + j, CHACHA_BLOCK_SIZE);

  if (!MEMEQ (CHACHA_BLOCK_SIZE, xor, xor_ref->data))
    {
      fprintf(stderr, "Error failed, bad xor 448:\n");
      fprintf(stderr, "\nOutput: ");
      print_hex(CHACHA_BLOCK_SIZE, xor);
      fprintf(stderr, "\nExpected:");
      print_hex(CHACHA_BLOCK_SIZE, xor_ref->data);
      fprintf(stderr, "\n");
      FAIL();
    }

  for (j = 1; j <= STREAM_LENGTH; j++)
    {
      memset(data, 0, STREAM_LENGTH + 1);
      chacha_set_iv(&ctx, iv->data);
      chacha_crypt(&ctx, j, data, data);

      if (!MEMEQ(j, data, stream))
	{
	  fprintf(stderr, "Encrypt failed for length %lu:\n",
		  (unsigned long) j);
	  fprintf(stderr, "\nOutput: ");
	  print_hex(j, data);
	  fprintf(stderr, "\nExpected:");
	  print_hex(j, stream);
	  fprintf(stderr, "\n");
	  FAIL();
	}
      if (!memzero_p (data + j, STREAM_LENGTH + 1 - j))
	{
	  fprintf(stderr, "Encrypt failed for length %lu, wrote too much:\n",
		  (unsigned long) j);
	  fprintf(stderr, "\nOutput: ");
	  print_hex(STREAM_LENGTH + 1 - j, data + j);
	  fprintf(stderr, "\n");
	  FAIL();
	}
    }
}
Ejemplo n.º 21
0
static void check_error(const char *s, int err)
{
	if (err != -FDT_ERR_NOTFOUND)
		FAIL("%s return error %s instead of -FDT_ERR_NOTFOUND", s,
		     fdt_strerror(err));
}
Ejemplo n.º 22
0
THuiFxReferencePoint CHuiFxEffectParser::GetReferencePointL( CMDXMLNode* aNode, TReal32& aRefValue, TBool& aNeedRefValue )
    {
    __ALFFXLOGSTRING1("CHuiFxEffectParser::GetReferencePointL - 0x%x",this);
    if (aNode->NodeType() != CMDXMLNode::EElementNode)
        {
        FAIL(KErrGeneral, _L("Text node expected while reading ref type"));
        }
    
    TInt attributeIndex = ((CMDXMLElement*)aNode)->FindIndex( KLitRef );

    THuiFxReferencePoint ref = EReferencePointIdentity;
    if (attributeIndex == KErrNotFound)
        {
        ref = EReferencePointUndefined;
        return ref;
        }
    aRefValue = 0;
        
    TPtrC attributeName;
    TPtrC paramRef;
    User::LeaveIfError(((CMDXMLElement*)aNode)->AttributeDetails( attributeIndex, attributeName, paramRef));
    TReal32 refValue = 0;
    TBool needRefValue = EFalse;

    if ( paramRef.Compare( KLitVisualWidth ) == 0 )
        {
        ref = EReferencePointVisualWidth;
        }
    else if ( paramRef.Compare( KLitVisualHeight ) == 0 )
        {
        ref = EReferencePointVisualHeight;
        }
    else if ( paramRef.Compare( KLitVisualTop ) == 0 )
        {
        ref = EReferencePointVisualTop;
        }
    else if ( paramRef.Compare( KLitVisualBottom ) == 0 )
        {
        ref = EReferencePointVisualBottom;
        }
    else if ( paramRef.Compare( KLitVisualLeft ) == 0 )
        {
        ref = EReferencePointVisualLeft;
        }
    else if ( paramRef.Compare( KLitVisualRight ) == 0 )
        {
        ref = EReferencePointVisualRight;
        }
    else if ( paramRef.Compare( KLitDisplayWidth ) == 0 )
        {
        ref = EReferencePointDisplayWidth;
        }
    else if ( paramRef.Compare( KLitDisplayHeight ) == 0 )
        {
        ref = EReferencePointDisplayHeight;
        }
    else if ( paramRef.Compare( KLitDisplayHeightMinusVisualTop ) == 0 )
        {
        ref = EReferencePointDisplayHeightMinusVisualTop;
        }
    else if ( paramRef.Compare( KLitDisplayTop ) == 0 )
        {
        ref = EReferencePointDisplayTop;
        }
    else if ( paramRef.Compare( KLitDisplayBottom ) == 0 )
        {
        ref = EReferencePointDisplayBottom;
        }
    else if ( paramRef.Compare( KLitDisplayLeft ) == 0 )
        {
        ref = EReferencePointDisplayLeft;
        }
    else if ( paramRef.Compare( KLitDisplayRight ) == 0 )
        {
        ref = EReferencePointDisplayRight;
        }
    else if ( paramRef.Compare( KLitExtRectWidth ) == 0 )
        {
        needRefValue = ETrue;
        ref = EReferencePointExtRectWidth;
        refValue = iExtRect.Width();
        }
    else if ( paramRef.Compare( KLitExtRectHeight ) == 0 )
        {
        needRefValue = ETrue;
        ref = EReferencePointExtRectHeight;
        refValue = iExtRect.Height();
        }
    else if ( paramRef.Compare( KLitExtRectTop ) == 0 )
        {
        needRefValue = ETrue;
        ref = EReferencePointExtRectTop;
        refValue = iExtRect.iTl.iY;
        }
    else if ( paramRef.Compare( KLitExtRectBottom ) == 0 )
        {
        needRefValue = ETrue;
        ref = EReferencePointExtRectBottom;
        refValue = iExtRect.iBr.iY;
        }
    else if ( paramRef.Compare( KLitExtRectLeft ) == 0 )
        {
        needRefValue = ETrue;
        ref = EReferencePointExtRectLeft;
        refValue = iExtRect.iTl.iX;
        }
    else if ( paramRef.Compare( KLitExtRectRight ) == 0 )
        {
        needRefValue = ETrue;
        ref = EReferencePointExtRectRight;
        refValue = iExtRect.iBr.iX;
        }
    // these are deprecated
    else if (paramRef.Compare(KLitVisualWidth1) == 0)
        {
        ref = EReferencePointVisualWidth; 
        }
    else if (paramRef.Compare(KLitVisualHeight1) == 0)
        {
        ref = EReferencePointVisualHeight; 
        }
    else if (paramRef.Compare(KLitDisplayWidth1) == 0)
        {
        ref = EReferencePointDisplayWidth; 
        }
    else if (paramRef.Compare(KLitDisplayHeight1) == 0)
        {
        ref = EReferencePointDisplayHeight; 
        }
    else
        {
        FAIL(KErrGeneral, _L("Unsupported parameter reference point"));
        }
    aRefValue = refValue;
    aNeedRefValue = needRefValue;
#ifdef _HUI_FX_PARSER_LOGGING
    __ALFFXLOGSTRING1("CHuiFxEffectParser::GetReferencePointL - return %d",ref);
#endif
    return ref;
    }
Ejemplo n.º 23
0
/*
 - reg - regular expression, i.e. main body or parenthesized thing
 *
 * Caller must absorb opening parenthesis.
 *
 * Combining parenthesis handling with the base level of regular expression
 * is a trifle forced, but the need to tie the tails of the branches to what
 * follows makes it hard to avoid.
 */
static char *
reg(int paren, int *flagp)
{
	register char *ret;
	register char *br;
	register char *ender;
	register int parno;
	int flags;

	*flagp = HASWIDTH;	/* Tentatively. */

	/* Make an OPEN node, if parenthesized. */
	if (paren) {
		if (regnpar >= NSUBEXP) {
			FAIL("too many ()");
		}
		parno = regnpar;
		regnpar++;
		ret = regnode(OPEN+parno);
	} else {
		ret = NULL;
		parno = 0;
	}

	/* Pick up the branches, linking them together. */
	br = regbranch(&flags);
	if (br == NULL) {
		return(NULL);
	}
	if (ret != NULL) {
		regtail(ret, br);	/* OPEN -> first. */
	} else {
		ret = br;
	}
	if (!(flags&HASWIDTH)) {
		*flagp &= ~HASWIDTH;
	}
	*flagp |= flags&SPSTART;
	while (*regparse == '|') {
		regparse++;
		br = regbranch(&flags);
		if (br == NULL) {
			return(NULL);
		}
		regtail(ret, br);	/* BRANCH -> BRANCH. */
		if (!(flags&HASWIDTH)) {
			*flagp &= ~HASWIDTH;
		}
		*flagp |= flags&SPSTART;
	}

	/* Make a closing node, and hook it on the end. */
	ender = regnode((paren) ? CLOSE+parno : END);	
	regtail(ret, ender);

	/* Hook the tails of the branches to the closing node. */
	for (br = ret; br != NULL; br = regnext(br)) {
		regoptail(br, ender);
	}

	/* Check for proper termination. */
	if (paren && *regparse++ != ')') {
		FAIL("unmatched ()");
	} else if (!paren && *regparse != '\0') {
		if (*regparse == ')') {
			FAIL("unmatched ()");
		} else
			FAIL("junk on end");	/* "Can't happen". */
		/* NOTREACHED */
	}

	return(ret);
}
Ejemplo n.º 24
0
void CHuiFxEffectParser::ParseNodeL( CMDXMLNode* aNode, CHuiFxLayer* aLayer)
    {
    switch( ResolveNode( aNode ) )
        {
        case ENodeTypeUnknown:
            {
#ifdef _HUI_FX_PARSER_LOGGING
            __ALFFXLOGSTRING("CHuiFxEffectParser::ParseNodeL - ENodeTypeUnknown");
#endif
            __ALFFXLOGSTRING1("CHuiFxEffectParser::ParseNodeL : WARNING - Node tag <%S> is not supported.", &(aNode->NodeName()));
            break;
            }
            
        case ENodeTypeGroup:
            {
#ifdef _HUI_FX_PARSER_LOGGING
            __ALFFXLOGSTRING("CHuiFxEffectParser::ParseNodeL - ENodeTypeGroup");
#endif
            // can't have group layers inside group layer
            if (aLayer && aLayer->Type() == ELayerTypeGroup)
                {
                FAIL(KErrGeneral, _L("Nested group layers not supported"));
                }
            
            CHuiFxGroupLayer* group = CHuiFxGroupLayer::NewL();
            CleanupStack::PushL( group );
            for (CMDXMLNode* node = aNode->FirstChild(); node; node = node->NextSibling())
                {
                ParseNodeL( node, group );
                }
            iEffect->AddLayerL( group ); // ownership transferred
            CleanupStack::Pop( group );
            break;
            }
            
        case ENodeTypeFilter:
            {
#ifdef _HUI_FX_PARSER_LOGGING
            __ALFFXLOGSTRING("CHuiFxEffectParser::ParseNodeL - ENodeTypeFilter");
#endif
            THuiFxFilterType filterType = GetFilterTypeL( aNode );
            CHuiFxFilter* filter = iEngine.CreateFilterL( filterType );
            CleanupStack::PushL( filter );
            CHuiFxFilterLayer* filterLayer = CHuiFxFilterLayer::NewL( filter );
            CleanupStack::Pop( filter );
            CleanupStack::PushL( filterLayer );
            if (aLayer && aLayer->Type() == ELayerTypeGroup)
                {
                CHuiFxGroupLayer* group = reinterpret_cast<CHuiFxGroupLayer*>(aLayer);
                group->AddLayerL( filterLayer ); // ownership transferred
                }
            else
                {
                iEffect->AddLayerL( filterLayer ); // ownership transferred
                }
            CleanupStack::Pop( filterLayer );
            
            if (filterType == EFilterTypeTransform)
                {
                filterLayer->SetTransformed(ETrue);
                }
            
            for (CMDXMLNode* node = aNode->FirstChild(); node; node = node->NextSibling())
                {
                ParseNodeL( node, filterLayer );
                }
            break;
            }
            
        case ENodeTypeVisual:
            {
#ifdef _HUI_FX_PARSER_LOGGING
            __ALFFXLOGSTRING("CHuiFxEffectParser::ParseNodeL - ENodeTypeVisual");
#endif
            TPtrC16 extBitmap;
            THuiFxVisualSrcType srcType = GetSrcTypeL( aNode, extBitmap );
            TBool opaqueHint = GetOpaqueHintL(aNode);
            CHuiFxVisualLayer* visual = CHuiFxVisualLayer::NewL( iVisual );
            CleanupStack::PushL( visual );
            visual->SetSourceType( srcType );
            visual->SetFxmlUsesOpaqueHint( opaqueHint );
            if ( srcType == EVisualSrcBitmap && extBitmap.Length() > 0 )
                {
                visual->SetExtBitmapFileL( extBitmap );
                }
            if (aLayer && aLayer->Type() == ELayerTypeGroup)
                {
                CHuiFxGroupLayer* group = reinterpret_cast<CHuiFxGroupLayer*>(aLayer);
                group->AddLayerL( visual ); // ownership transferred
                }
            else
                {
                iEffect->AddLayerL( visual ); // ownership transferred
                }
            for (CMDXMLNode* node = aNode->FirstChild(); node; node = node->NextSibling())
                {
                ParseNodeL( node, visual );
                }
            CleanupStack::Pop( visual );
            break;
            }
         
         case ENodeTypeBlending:
            {
#ifdef _HUI_FX_PARSER_LOGGING
            __ALFFXLOGSTRING("CHuiFxEffectParser::ParseNodeL - ENodeTypeBlending");
#endif
            CMDXMLNode* blendingNode = aNode->FirstChild();
            if( blendingNode->NodeType() != CMDXMLNode::ETextNode )
                {
                FAIL(KErrGeneral, _L("Bad blending mode"));
                }
            TPtrC modePtr( ((CMDXMLText *)blendingNode)->Data() );
            
            // set replace as default blending mode
            THuiFxBlendingMode blendingMode = EBlendingModeReplace;
            if( modePtr.Compare( KLitReplace ) == 0 )
                {
                blendingMode = EBlendingModeReplace;
                }
            else if( modePtr.Compare( KLitOver ) == 0 )
                {
                blendingMode = EBlendingModeOver;
                }
            else if( modePtr.Compare( KLitMultiply ) == 0 )
                {
                blendingMode = EBlendingModeMultiply;
                }
            else if( modePtr.Compare( KLitAdditive ) == 0 )
                {
                blendingMode = EBlendingModeAdditive;
                }
            else if( modePtr.Compare( KLitDarken ) == 0 )
                {
                blendingMode = EBlendingModeDarken;
                }
            else if( modePtr.Compare( KLitLighten ) == 0 )
                {
                blendingMode = EBlendingModeLighten;
                }
            else
                {
                FAIL(KErrGeneral, _L("Bad blending mode"));
                }
                
            if (aLayer && aLayer->Type() == ELayerTypeGroup)
                {
                aLayer->SetBlendingMode( blendingMode );
                }
            else
                {
                // TODO: should other layers have a blending mode?
                FAIL(KErrGeneral, _L("Blending mode can only be set for a group layer"));
                }            
            break;
            }
            
         case  ENodeTypeParam:
            {
#ifdef _HUI_FX_PARSER_LOGGING
            __ALFFXLOGSTRING("CHuiFxEffectParser::ParseNodeL - ENodeTypeParam");
#endif
            ResolveParamL(aNode, aLayer);
            break;
            }
            
        default:
            __ALFFXLOGSTRING("CHuiFxEffectParser::ParseNodeL - default??");
            break;
        }
    
    }
Ejemplo n.º 25
0
/*
 - regatom - the lowest level
 *
 * Optimization:  gobbles an entire sequence of ordinary characters so that
 * it can turn them into a single node, which is smaller to store and
 * faster to run.  Backslashed characters are exceptions, each becoming a
 * separate node; the code is simpler that way and it's not worth fixing.
 */
static char *
regatom(int *flagp)
{
	register char *ret;
	int flags;

	*flagp = WORST;		/* Tentatively. */

	switch (*regparse++) {
	case '^':
		ret = regnode(BOL);
		break;
	case '$':
		ret = regnode(EOL);
		break;
	case '.':
		ret = regnode(ANY);
		*flagp |= HASWIDTH|SIMPLE;
		break;
	case '[': {
			register int chclass;
			register int chclassend;

			if (*regparse == '^') {	/* Complement of range. */
				ret = regnode(ANYBUT);
				regparse++;
			} else {
				ret = regnode(ANYOF);
			}
			if (*regparse == ']' || *regparse == '-') {
				regc(*regparse++);
			}
			while (*regparse != '\0' && *regparse != ']') {
				if (*regparse == '-') {
					regparse++;
					if (*regparse == ']' || *regparse == '\0') {
						regc('-');
					} else {
						chclass = UCHARAT(regparse-2)+1;
						chclassend = UCHARAT(regparse);
						if (chclass > chclassend+1) {
							FAIL("invalid [] range");
						}
						for (; chclass <= chclassend; chclass++) {
							regc(chclass);
						}
						regparse++;
					}
				} else if (*regparse == '\\') {
					switch(*++regparse) {
					case 'n' :
						regc('\n');
						regparse++;
						break;
					case 't' :
						regc('\t');
						regparse++;
						break;
					case ']' :
						regc(']');
						regparse++;
						break;
					case '-' :
						regc('-');
						regparse++;
						break;
					case '\\' :
						regc('\\');
						regparse++;
						break;
					default :
						regparse--;
						regc(*regparse++);
					}
				} else {
					regc(*regparse++);
				}
			}
			regc('\0');
			if (*regparse != ']') {
				FAIL("unmatched []");
			}
			regparse++;
			*flagp |= HASWIDTH|SIMPLE;
		}
		break;
	case '(':
		ret = reg(1, &flags);
		if (ret == NULL) {
			return(NULL);
		}
		*flagp |= flags&(HASWIDTH|SPSTART);
		break;
	case '\0':
	case '|':
	case ')':
		FAIL("internal urp");	/* Supposed to be caught earlier. */
		break;
	case '?':
	case '+':
	case '*':
	case '{':
		FAIL("?+*{ follows nothing");
		break;
	case '\\':
		if (*regparse == '\0') {
			FAIL("trailing \\");
		}
		switch(*regparse) {
		case '<':
			ret = regnode(BEGWORD);
			break;
		case '>':
			ret = regnode(ENDWORD);
			break;
		case 'd':
			ret = regnode(DIGIT);
			*flagp |= (HASWIDTH|SIMPLE);
			break;
		case 'D':
			ret = regnode(NDIGIT);
			*flagp |= (HASWIDTH|SIMPLE);
			break;
		case 'n' :
			ret = regnode(EXACTLY);
			regc('\n');
			regc('\0');
			*flagp |= (HASWIDTH|SIMPLE);
			break;
		case 'p':
			ret = regnode(PRINT);
			*flagp |= HASWIDTH|SIMPLE;
			break;
		case 'P':
			ret = regnode(NPRINT);
			*flagp |= HASWIDTH|SIMPLE;
			break;
		case 's':
			ret = regnode(WHITESP);
			*flagp |= HASWIDTH|SIMPLE;
			break;
		case 'S':
			ret = regnode(NWHITESP);
			*flagp |= HASWIDTH|SIMPLE;
			break;
		case 't' :
			ret = regnode(EXACTLY);
			regc('\t');
			regc('\0');
			*flagp |= (HASWIDTH|SIMPLE);
			break;
		case 'w':
			ret = regnode(ALNUM);
			*flagp |= HASWIDTH|SIMPLE;
			break;
		case 'W':
			ret = regnode(NALNUM);
			*flagp |= HASWIDTH|SIMPLE;
			break;
		default :
			ret = regnode(EXACTLY);
			regc(*regparse);
			regc('\0');
			*flagp |= HASWIDTH|SIMPLE;
		}
		regparse++;
		break;
	default: {
			register int len;
			register char ender;

			regparse--;
			len = strcspn(regparse, META);
			if (len <= 0) {
				FAIL("internal disaster");
			}
			ender = *(regparse+len);
			if (len > 1 && ISMULT(ender)) {
				len--;		/* Back off clear of ?+* operand. */
			}
			*flagp |= HASWIDTH;
			if (len == 1) {
				*flagp |= SIMPLE;
			}
			ret = regnode(EXACTLY);
			while (len > 0) {
				regc(*regparse++);
				len--;
			}
			regc('\0');
		}
		break;
	}

	return(ret);
}
Ejemplo n.º 26
0
void CHuiFxEffectParser::ParseAnimationNodeL(CMDXMLNode* aNode, PARAM_TYPE& aParam, TIMELINE_TYPE& aTimeLine)
    {
#ifdef _HUI_FX_PARSER_LOGGING
    __ALFFXLOGSTRING1("CHuiFxEffectParser::ParseAnimationNodeL - 0x%x", this);
#endif
    switch( ResolveNode( aNode ) )
        {
        case ENodeTypeDuration:
            {
            aTimeLine.SetDuration(ParseFloatValueL(aNode->FirstChild()));
            }
            break;
        case ENodeTypeStyle:
            {
            CMDXMLNode* styleNode = aNode->FirstChild();
            if (styleNode->NodeType() != CMDXMLNode::ETextNode)
                {
                FAIL(KErrGeneral, _L("Text node expected while parsing an interpolation mode"));
                }
            TPtrC modePtr( ((CMDXMLText *)styleNode)->Data() );
            
            if( modePtr.Compare( KLitHold ) == 0 )
                {
                aTimeLine.SetInterpolationMode(EInterpolationModeHold);
                }
            else if( modePtr.Compare( KLitLinear ) == 0 )
                {
                aTimeLine.SetInterpolationMode(EInterpolationModeLinear);
                }
            else if( modePtr.Compare( KLitInQuad ) == 0 )
                {
                aTimeLine.SetInterpolationMode(EInterpolationModeInQuad);
                }
            else if( modePtr.Compare( KLitOutQuad ) == 0 )
                {
                aTimeLine.SetInterpolationMode(EInterpolationModeOutQuad);
                }
            else if( modePtr.Compare( KLitInOutQuad ) == 0 )
                {
                aTimeLine.SetInterpolationMode(EInterpolationModeInOutQuad);
                }
            else if( modePtr.Compare( KLitOutInQuad ) == 0 )
                {
                aTimeLine.SetInterpolationMode(EInterpolationModeOutInQuad);
                }
            else if( modePtr.Compare( KLitInBack ) == 0 )
                {
                aTimeLine.SetInterpolationMode(EInterpolationModeInBack);
                }
            else if( modePtr.Compare( KLitOutBack ) == 0 )
                {
                aTimeLine.SetInterpolationMode(EInterpolationModeOutBack);
                }
            else if( modePtr.Compare( KLitInOutBack ) == 0 )
                {
                aTimeLine.SetInterpolationMode(EInterpolationModeInOutBack);
                }
            else if( modePtr.Compare( KLitOutInBack ) == 0 )
                {
                aTimeLine.SetInterpolationMode(EInterpolationModeOutInBack);
                }
            else if( modePtr.Compare( KLitQuadraticBezier ) == 0 )
                {
                aTimeLine.SetInterpolationMode(EInterpolationModeQuadraticBezier);
                }
            else if( modePtr.Compare( KLitCubicBezier ) == 0 )
                {
                aTimeLine.SetInterpolationMode(EInterpolationModeCubicBezier);
                }
/*                
            else if( modePtr.Compare( KLitDeclerate ) == 0 )
                {
                aTimeLine.SetInterpolationMode(EInterpolationModeDecelerate);
                }
            else if( modePtr.Compare( KLitAccelerate ) == 0 )
                {
                aTimeLine.SetInterpolationMode(EInterpolationModeAccelerate);
                }
            else if( modePtr.Compare( KLitImpulse ) == 0 )
                {
                aTimeLine.SetInterpolationMode(EInterpolationModeImpulse);
                }
*/                
            else
                {
                // unknown (unsupported) interpolation modes default to linear
                // (at least during testing when we add modes)
                aTimeLine.SetInterpolationMode(EInterpolationModeLinear);
//                FAIL(KErrGeneral, _L("Unknown interpolation mode"));
                }
            break;
            }
        case ENodeTypeMarker:
            {
            TReal32 time = ParseFloatAttributeL(aNode, KLitAt);
            TInt typeIndex = ((CMDXMLElement*)aNode)->FindIndex( KLitType );
            
            if (typeIndex == KErrNotFound)
                {
                FAIL(KErrGeneral, _L("Marker name not found"));
                }

            TPtrC attributeValue;
            TPtrC attributeName;
            User::LeaveIfError(((CMDXMLElement*)aNode)->AttributeDetails( typeIndex, attributeName, attributeValue ));

            // TODO: Should this be controllable?
            aTimeLine.SetLoopingMode(ELoopingModeRepeat);

            if (attributeValue.Compare(KLitLoopStart) == 0)
                {
                aTimeLine.SetLoopStart(time);
                }
            else if (attributeValue.Compare(KLitLoopEnd) == 0)
                {
                aTimeLine.SetLoopEnd(time);
                }
            else
                {
                FAIL(KErrGeneral, _L("Unsupported marker type"));
                }
            break;
            }
        case ENodeTypeKeyFrame:
            {
            TReal32 time = ParseFloatAttributeL(aNode, KLitAt);
            TReal32 aux1 = ParseFloatAttributeL(aNode, KLitAux1, EFalse);
            TReal32 aux2 = ParseFloatAttributeL(aNode, KLitAux2, EFalse);
            VALUE_TYPE value = ParseAnimationKeyFrameValueL<PARAM_TYPE::ValueType, TIMELINE_TYPE>(aNode->FirstChild(), aTimeLine);
            TRAPD(err, aTimeLine.AppendKeyFrameL(time, value, aux1, aux2));
            if (err != KErrNone)
                {
                FAIL(KErrGeneral, _L("Unable to append new key frame to timeline"));
                }
            }
            break;
        case ENodeTypeStart:
            {
            TInt refIndex  = ((CMDXMLElement*)aNode)->FindIndex( KLitRef );
            TReal32 refValue = 0;
            TBool needRefValue = EFalse;
            THuiFxReferencePoint ref = EReferencePointUndefined;
            if ( refIndex != KErrNotFound )
                {
                ref = GetReferencePointL( aNode, refValue, needRefValue );
                }
            aParam.SetStartReference( ref );
            if ( needRefValue )
                {
                aParam.SetStartValue( refValue );
                }
            if ( aParam.StartReference() != EReferencePointUndefined &&
               aParam.EndReference() != EReferencePointUndefined )
                {
                aParam.SetReferencePoint( EReferencePointUndefined );
                }
	     float value = ParseFloatValueL(aNode->FirstChild());
	     aParam.SetStartMultiplier( value );

            }
            break;
        case ENodeTypeEnd:
            {
            TInt refIndex  = ((CMDXMLElement*)aNode)->FindIndex( KLitRef );
            TReal32 refValue = 0;
            TBool needRefValue = EFalse;
            THuiFxReferencePoint ref = EReferencePointUndefined;
            if ( refIndex != KErrNotFound )
                {
                ref = GetReferencePointL( aNode, refValue, needRefValue );
                }
            aParam.SetEndReference( ref );
            if ( needRefValue )
                {
                aParam.SetEndValue( refValue );
                }
            if ( aParam.StartReference() != EReferencePointUndefined &&
               aParam.EndReference() != EReferencePointUndefined )
                {
                aParam.SetReferencePoint( EReferencePointUndefined );
                }
            float value = ParseFloatValueL(aNode->FirstChild());
            aParam.SetEndMultiplier( value );

            }
            break;
        }
#ifdef _HUI_FX_PARSER_LOGGING
    __ALFFXLOGSTRING("CHuiFxEffectParser::ParseAnimationNodeL - out");
#endif
    }
Ejemplo n.º 27
0
SshTlsTransStatus
ssh_tls_trans_read_finished(SshTlsProtocolState s,
                            SshTlsHandshakeType type,
                            unsigned char *data, int data_len)
{
    unsigned char *ptr;
    int len;
    unsigned char locally_computed_verify_data[36];
    unsigned char hashes[16 + 20];

    CHECKTYPE(SSH_TLS_HS_FINISHED);
    SSH_DEBUG(7, ("Got the (expected) finished message."));

    SSH_ASSERT(s->kex.handshake_history != NULL);

#ifdef SSH_TLS_SSL_3_0_COMPAT
    if (s->protocol_version.major == 3 && s->protocol_version.minor == 0)
    {
        if (data_len != 36)
        {
            FAIL(SSH_TLS_ALERT_DECODE_ERROR,
                 ("Invalid length verify data (%d bytes).", data_len));
        }

        ptr = ssh_buffer_ptr(s->kex.handshake_history);
        len = ssh_buffer_len(s->kex.handshake_history);

        SSH_DEBUG(7, ("Verifying SSL3 finished digest, buffer len = %d.",
                      len));

        SSH_DEBUG_HEXDUMP(10, ("Handshake buffer"), ptr, len);

        if (!ssh_tls_ssl_finished_digest(s->kex.master_secret, 48,
                                         ptr, len,
                                         s->conf.is_server,
                                         locally_computed_verify_data))
        {
            FAIL(SSH_TLS_ALERT_HANDSHAKE_FAILURE,
                 ("Local and remote verify data do not match."));
        }

        if (memcmp(data, locally_computed_verify_data, 36))
        {
            SSH_DEBUG_HEXDUMP(5, ("Local and remote verify data do not match. "
                                  "Local: "),
                              locally_computed_verify_data, 36);
            SSH_DEBUG_HEXDUMP(5, ("Remote: "),
                              data, 36);
            FAIL(SSH_TLS_ALERT_HANDSHAKE_FAILURE,
                 ("Local and remote verify data do not match."));
        }
        goto accepted;
    }

#endif /* SSH_TLS_SSL_3_0_COMPAT */

    ptr = ssh_buffer_ptr(s->kex.handshake_history);
    len = ssh_buffer_len(s->kex.handshake_history);

    if (ssh_hash_of_buffer("md5", ptr, len, hashes) != SSH_CRYPTO_OK)
        return SSH_TLS_TRANS_FAILED;
    if (ssh_hash_of_buffer("sha1", ptr, len, hashes + 16) != SSH_CRYPTO_OK)
        return SSH_TLS_TRANS_FAILED;

    ssh_tls_prf(s->kex.master_secret, 48,
                (unsigned char *)
                (s->conf.is_server ? "client finished" : "server finished"),
                15 /* strlen("client finished") */,
                hashes, 16 + 20,
                locally_computed_verify_data, 12);

    memset(hashes, 0, 16 + 20);

    if (data_len != 12)
    {
        FAIL(SSH_TLS_ALERT_DECODE_ERROR,
             ("Invalid length verify data (%d bytes).", data_len));
    }

    if (memcmp(data, locally_computed_verify_data, 12))
    {
        SSH_DEBUG_HEXDUMP(5, ("Local and remote verify data do not match. "
                              "Local: "),
                          locally_computed_verify_data, 12);
        SSH_DEBUG_HEXDUMP(5, ("Remote: "),
                          data, 12);
        FAIL(SSH_TLS_ALERT_ILLEGAL_PARAMETER,
             ("Local and remote verify data do not match."));
    }

accepted:
    memset(locally_computed_verify_data, 0,
           sizeof(locally_computed_verify_data));

    SSH_DEBUG(6, ("Verify data verified."));

    /* The order of client's and server's change_cipher and finished
       messages is different depending on whether we are resuming and
       old session or defining a new one. This is another strange
       property of the TLS protocol. */
    if ((s->conf.is_server && !(s->kex.flags & SSH_TLS_KEX_NEW_SESSION))
            ||
            (!s->conf.is_server && (s->kex.flags & SSH_TLS_KEX_NEW_SESSION)))
    {
        ssh_tls_kex_finished(s);
    }
    else
    {
        if (s->conf.is_server)
        {
            s->kex.state = SSH_TLS_KEX_SEND_S_CC;
        }
        else
        {
            s->kex.state = SSH_TLS_KEX_SEND_C_CC;
        }
    }

    return SSH_TLS_TRANS_OK;
}
Ejemplo n.º 28
0
void CHuiFxEffectParser::ResolveParamL( CMDXMLNode* aNode, CHuiFxLayer* aLayer )
    {
#ifdef _HUI_FX_PARSER_LOGGING
    __ALFFXLOGSTRING1("CHuiFxEffectParser::ResolveParamL - 0x%x",this);
#endif
    ASSERT(aNode->NodeType() == CMDXMLNode::EElementNode);

    TInt nameIndex = ((CMDXMLElement*)aNode)->FindIndex( KLitName );
    TInt typeIndex = ((CMDXMLElement*)aNode)->FindIndex( KLitType );
    TInt refIndex  = ((CMDXMLElement*)aNode)->FindIndex( KLitRef );
    if( nameIndex == KErrNotFound )
        {
        FAIL(KErrGeneral, _L("Parameter name not found"));
        }
    
    THuiFxReferencePoint ref = EReferencePointIdentity;
    TBool isAnimated = EFalse;
    TPtrC paramName;
    TPtrC attributeName;
    User::LeaveIfError(((CMDXMLElement*)aNode)->AttributeDetails(nameIndex, attributeName, paramName));

    if (typeIndex != KErrNotFound)
        {
        TPtrC paramType;
        User::LeaveIfError(((CMDXMLElement*)aNode)->AttributeDetails(typeIndex, attributeName, paramType));

        if( paramType.Compare( KLitAnim ) == 0 )
            {
            isAnimated = ETrue;
            aLayer->SetAnimated(ETrue);
            }
        else
            {
            FAIL(KErrGeneral, _L("Unsupported parameter type"));
            }
        }
    
    TReal32 refValue;
    TBool needRefValue = EFalse;
    
    
    if ( refIndex != KErrNotFound )
        {
        ref = GetReferencePointL( aNode, refValue, needRefValue );
        if ( ref == EReferencePointUndefined )
            {
            // For the parameters an undefined reference point means no value for the change
            ref = EReferencePointIdentity;
            }
        }
    
    MHuiFxParameter* param = NULL;
    if (aLayer && aLayer->Type() == ELayerTypeFilter)
        {
        CHuiFxFilterLayer* filterLayer = reinterpret_cast<CHuiFxFilterLayer*>(aLayer);
        // We must check if we really have a filter.
        // If the filter type was incorrect, a filter was not created
        // We should not crash or panic even if the effect file is not syntactically correct.
        // An incorrect file should simply produce no effect.
        CHuiFxFilter& filter = filterLayer->Filter();
        
        if ( &filter )
            {
            param = filter.Parameter( paramName );
            }
        }
    else if (aLayer && aLayer->Type() == ELayerTypeVisual)
        {
        CHuiFxVisualLayer* visualLayer = reinterpret_cast<CHuiFxVisualLayer*>(aLayer); 
        param = visualLayer->Parameter(paramName);
        }
    
    if (!param)
        {
        FAIL(KErrNotFound, _L("Parameter name not recognized")); // leaves
        return; // never reached. For completeness
        }

    param->SetReferencePoint(ref);
    if ( needRefValue )
        {
        param->SetReferenceValue( refValue );
        }
    
    if (isAnimated)
        {
        // Collect animation keyframes and other parameters
        switch (param->Type())
            {
            case EParameterTypeScalar:
                {
                RHuiFxScalarTimeLine* t = new (ELeave) RHuiFxScalarTimeLine();
                CHuiFxScalarParameter* p = static_cast<CHuiFxScalarParameter*>(param); 
                CleanupStack::PushL(t);
                for (CMDXMLNode* child = aNode->FirstChild(); child; child = child->NextSibling())
                    {
                    ParseAnimationNodeL<CHuiFxScalarParameter, RHuiFxScalarTimeLine, CHuiFxScalarParameter::ValueType>(child, *p, *t);
                    }
                CleanupStack::Pop(t);
                p->SetTimeLine(t);
                if ( p->ReferencePoint() == EReferencePointUndefined )
                    {
                    if ( paramName.Compare( KLitScaleX ) == 0 )
                        {
                        p->SetReferencePoint( EReferencePointVisualWidth );
                        }
                    else if ( paramName.Compare( KLitScaleY ) == 0 )
                        {
                        p->SetReferencePoint( EReferencePointVisualHeight );
                        }
                    else
                        {
                        p->SetReferencePoint( EReferencePointIdentity );
                        }
                    }
                break;
                }
        case EParameterTypeColor:
                {
                RHuiFxColorTimeLine* t = new (ELeave) RHuiFxColorTimeLine();
                CHuiFxColorParameter* p = static_cast<CHuiFxColorParameter*>(param); 
                CleanupStack::PushL(t);
                for (CMDXMLNode* child = aNode->FirstChild(); child; child = child->NextSibling())
                    {
                    ParseAnimationNodeL<CHuiFxColorParameter, RHuiFxColorTimeLine, CHuiFxColorParameter::ValueType>(child, *p, *t);
                    }
                CleanupStack::Pop(t);
                p->SetTimeLine(t);
                if ( p->ReferencePoint() == EReferencePointUndefined )
                    {
                    p->SetReferencePoint( EReferencePointIdentity );
                    }
                break;
                }
            }
        }
    else
        {
        switch (param->Type())
            {
            case EParameterTypeScalar:
                {
                CHuiFxScalarParameter* p = static_cast<CHuiFxScalarParameter*>(param); 
                p->SetValue(ParseFloatValueL(aNode->FirstChild()));
                break;
                }
        case EParameterTypeColor:
                {
                CHuiFxColorParameter* p = static_cast<CHuiFxColorParameter*>(param); 
                p->SetValue(ParseColorValueL(aNode->FirstChild()));
                break;
                }
            }
        }
#ifdef _HUI_FX_PARSER_LOGGING
    __ALFFXLOGSTRING("CHuiFxEffectParser::ResolveParamL - out ");
#endif
    }
Ejemplo n.º 29
0
bool CSoundComponent::InitXACT(const char* engine_xgs)
{
	HRESULT hr;
	CoInitializeEx( NULL, COINIT_MULTITHREADED );  // COINIT_APARTMENTTHREADED will work too
	//TODO("Create the XACT engine");
	hr=XACT3CreateEngine(0, &mpXEngine);

	if( FAILED( hr ) || mpXEngine == NULL )
	{
		FAIL("Problems creating XACT engine","InitXACT Failed");
		return false;
	}

	// Load the global settings file and pass it into XACTInitialize
	VOID* pGlobalSettingsData = NULL;
	DWORD dwGlobalSettingsFileSize = 0;
	bool bSuccess = false;
	HANDLE hFile = CreateFile( engine_xgs, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL );
	if( hFile!=INVALID_HANDLE_VALUE )
	{
		dwGlobalSettingsFileSize = GetFileSize( hFile, NULL );
		if( dwGlobalSettingsFileSize != INVALID_FILE_SIZE )
		{
			pGlobalSettingsData = CoTaskMemAlloc( dwGlobalSettingsFileSize );
			if( pGlobalSettingsData )
			{
				DWORD dwBytesRead;
				if( 0 != ReadFile( hFile, pGlobalSettingsData, dwGlobalSettingsFileSize, &dwBytesRead, NULL ) )
				{
					bSuccess = true;
				}
			}
		}
		CloseHandle( hFile );
	}
	if( !bSuccess )
	{
		if( pGlobalSettingsData )
			CoTaskMemFree( pGlobalSettingsData );
		pGlobalSettingsData = NULL;
		dwGlobalSettingsFileSize = 0;
		FAIL(engine_xgs,"Problems opening engine file");
		return false;
	}

	// Initialize & create the XACT runtime 
	XACT_RUNTIME_PARAMETERS xrParams = {0};
	xrParams.lookAheadTime = XACT_ENGINE_LOOKAHEAD_DEFAULT;
	xrParams.pGlobalSettingsBuffer = pGlobalSettingsData;
	xrParams.globalSettingsBufferSize = dwGlobalSettingsFileSize;
	xrParams.globalSettingsFlags = XACT_FLAG_GLOBAL_SETTINGS_MANAGEDATA; // this will tell XACT to delete[] the buffer when its unneeded
	//TODO(Initalise the XACT engine);
	hr=mpXEngine->Initialize(&xrParams);
	if( FAILED( hr ) )
	{
		FAIL(engine_xgs,"Problems Initalising XACT engine");
		return false;
	}

	X3DAUDIO_EMITTER emitter = {0};
	X3DAUDIO_LISTENER listener = {0};

	listener.OrientFront = D3DXVECTOR3( 0, 0, 1 );
	listener.OrientTop = D3DXVECTOR3( 0, 1, 0 );
	listener.Position = D3DXVECTOR3( 0, 0, 0 );
	listener.Velocity = D3DXVECTOR3( 0, 0, 0 );

	// the following need to be orthonormal
	emitter.OrientFront = D3DXVECTOR3( 0, 0, 1 );
	emitter.OrientTop = D3DXVECTOR3( 0, 1, 0 );
	emitter.Position = D3DXVECTOR3( 0, 0, 0 );
	emitter.Velocity = D3DXVECTOR3( 0, 0, 0 ); // needs to not be zero if you want to hear Doppler effect

	// emitter ChannelCount and DSP Setting's SrcChannelCount must match
	emitter.ChannelCount = 2;   

	// this will be set by XACT3DCalculate if ChannelCount > 1.
	emitter.ChannelRadius = 1.0f;   

	// will be set by XACT3DCalculate
	emitter.pChannelAzimuths = NULL;

	// will be set by XACT3DCalculate
	emitter.pVolumeCurve = emitter.pLFECurve
		= emitter.pLPFDirectCurve
		= emitter.pLPFReverbCurve
		= emitter.pReverbCurve
		= NULL;

	emitter.CurveDistanceScaler = 1.0;
	emitter.DopplerScaler = 1.0f;

	hr = XACT3DInitialize(mpXEngine, xact3dInstance);

	if( FAILED( hr ) )
	{
		FAIL(engine_xgs,"Problems Initalising XACT 3D engine");
		return false;
	}

	// check how many output channels are supported
	WAVEFORMATEXTENSIBLE format;
	hr = mpXEngine->GetFinalMixFormat(&format);
	if(FAILED(hr))
	{
		FAIL("BLABLBA");
	}
	// fill the DSP
	ZeroMemory(&dspSettings,sizeof(dspSettings));
	// different code's seem to suggest 1 or 2 channels for the emitter
	dspSettings.SrcChannelCount = 1;
	dspSettings.DstChannelCount = format.Format.nChannels;  // as supported 
	dspSettings.pMatrixCoefficients = new FLOAT32[dspSettings.SrcChannelCount * dspSettings.DstChannelCount];
	ZeroMemory(dspSettings.pMatrixCoefficients ,sizeof(FLOAT32)*dspSettings.SrcChannelCount * dspSettings.DstChannelCount);

	return true;
}
Ejemplo n.º 30
0
TEST(QueryPlannerTest, testcollapseTextCliques) {
  try {
    {
      {
        ParsedQuery pq = SparqlParser::parse(
            "SELECT ?x WHERE {?x <p> <X>. ?c ql:contains-entity ?x. ?c "
            "ql:contains-word abc}");
        pq.expandPrefixes();
        QueryPlanner qp(nullptr);
        auto tg = qp.createTripleGraph(&pq._rootGraphPattern);
        ASSERT_EQ(
            "0 {s: ?x, p: <p>, o: <X>} : (1)\n"
            "1 {s: ?c, p: <QLever-internal-function/contains-entity>, o: ?x} : "
            "(0, 2)\n"
            "2 {s: ?c, p: <QLever-internal-function/contains-word>, o: abc} : "
            "(1)",
            tg.asString());
        tg.collapseTextCliques();
        ASSERT_EQ(
            "0 {TextOP for ?c, wordPart: \"abc\"} : (1)\n"
            "1 {s: ?x, p: <p>, o: <X>} : (0)",
            tg.asString());
        ASSERT_EQ(2ul, tg._nodeMap[0]->_variables.size());
        ASSERT_EQ(1ul, tg._nodeMap[1]->_variables.size());
      }
      {
        ParsedQuery pq = SparqlParser::parse(
            "SELECT ?x WHERE {?x <p> <X>. ?c "
            "<QLever-internal-function/contains-entity> ?x. ?c "
            "<QLever-internal-function/contains-word> abc . ?c "
            "ql:contains-entity ?y}");
        pq.expandPrefixes();
        QueryPlanner qp(nullptr);
        auto tg = qp.createTripleGraph(&pq._rootGraphPattern);
        ASSERT_EQ(
            "0 {s: ?x, p: <p>, o: <X>} : (1)\n"
            "1 {s: ?c, p: <QLever-internal-function/contains-entity>, o: ?x} : "
            "(0, 2, 3)\n"
            "2 {s: ?c, p: <QLever-internal-function/contains-word>, o: abc} : "
            "(1, 3)\n"
            "3 {s: ?c, p: <QLever-internal-function/contains-entity>, o: ?y} : "
            "(1, 2)",
            tg.asString());
        tg.collapseTextCliques();
        ASSERT_EQ(
            "0 {TextOP for ?c, wordPart: \"abc\"} : (1)\n"
            "1 {s: ?x, p: <p>, o: <X>} : (0)",
            tg.asString());
        ASSERT_EQ(3ul, tg._nodeMap[0]->_variables.size());
        ASSERT_EQ(1ul, tg._nodeMap[1]->_variables.size());
      }
      {
        ParsedQuery pq = SparqlParser::parse(
            "SELECT ?x WHERE {?x <p> <X>. ?c ql:contains-entity ?x. ?c "
            "ql:contains-word abc . ?c ql:contains-entity ?y. ?y <P2> <X2>}");
        pq.expandPrefixes();
        QueryPlanner qp(nullptr);
        auto tg = qp.createTripleGraph(&pq._rootGraphPattern);
        ASSERT_EQ(
            "0 {s: ?x, p: <p>, o: <X>} : (1)\n"
            "1 {s: ?c, p: <QLever-internal-function/contains-entity>, o: ?x} : "
            "(0, 2, 3)\n"
            "2 {s: ?c, p: <QLever-internal-function/contains-word>, o: abc} : "
            "(1, 3)\n"
            "3 {s: ?c, p: <QLever-internal-function/contains-entity>, o: ?y} : "
            "(1, 2, 4)\n"
            "4 {s: ?y, p: <P2>, o: <X2>} : (3)",
            tg.asString());
        tg.collapseTextCliques();
        ASSERT_EQ(
            "0 {TextOP for ?c, wordPart: \"abc\"} : (1, 2)\n"
            "1 {s: ?x, p: <p>, o: <X>} : (0)\n"
            "2 {s: ?y, p: <P2>, o: <X2>} : (0)",
            tg.asString());
        ASSERT_EQ(3ul, tg._nodeMap[0]->_variables.size());
        ASSERT_EQ(1ul, tg._nodeMap[1]->_variables.size());
        ASSERT_EQ(1ul, tg._nodeMap[2]->_variables.size());
      }
      {
        ParsedQuery pq = SparqlParser::parse(
            "(SELECT ?x WHERE {?x <p> <X>. ?c ql:contains-entity ?x. ?c "
            "ql:contains-word \"abc\" . ?c ql:contains-entity ?y. ?c2 "
            "ql:contains-entity ?y. ?c2 ql:contains-word \"xx\"})");
        pq.expandPrefixes();
        QueryPlanner qp(nullptr);
        auto tg = qp.createTripleGraph(&pq._rootGraphPattern);
        ASSERT_EQ(
            "0 {s: ?x, p: <p>, o: <X>} : (1)\n"
            "1 {s: ?c, p: <QLever-internal-function/contains-entity>, o: ?x} : "
            "(0, 2, 3)\n"
            "2 {s: ?c, p: <QLever-internal-function/contains-word>, o: abc} : "
            "(1, 3)\n"
            "3 {s: ?c, p: <QLever-internal-function/contains-entity>, o: ?y} : "
            "(1, 2, 4)\n"
            "4 {s: ?c2, p: <QLever-internal-function/contains-entity>, o: ?y} "
            ": (3, 5)\n"
            "5 {s: ?c2, p: <QLever-internal-function/contains-word>, o: xx} : "
            "(4)",
            tg.asString());
        tg.collapseTextCliques();
        ASSERT_EQ(
            "0 {TextOP for ?c, wordPart: \"abc\"} : (1, 2)\n"
            "1 {TextOP for ?c2, wordPart: \"xx\"} : (0)\n"
            "2 {s: ?x, p: <p>, o: <X>} : (0)",
            tg.asString());
        ASSERT_EQ(3ul, tg._nodeMap[0]->_variables.size());
        ASSERT_EQ(2ul, tg._nodeMap[1]->_variables.size());
        ASSERT_EQ(1ul, tg._nodeMap[2]->_variables.size());
      }
      {
        ParsedQuery pq = SparqlParser::parse(
            "SELECT ?x WHERE {?x <p> <X>. ?c ql:contains-entity ?x. ?c "
            "ql:contains-word abc . ?c ql:contains-entity ?y. ?c2 "
            "ql:contains-entity ?y. ?c2 ql:contains-word xx. ?y <P2> <X2>}");
        pq.expandPrefixes();
        QueryPlanner qp(nullptr);
        auto tg = qp.createTripleGraph(&pq._rootGraphPattern);
        ASSERT_EQ(
            "0 {s: ?x, p: <p>, o: <X>} : (1)\n"
            "1 {s: ?c, p: <QLever-internal-function/contains-entity>, o: ?x} : "
            "(0, 2, 3)\n"
            "2 {s: ?c, p: <QLever-internal-function/contains-word>, o: abc} : "
            "(1, 3)\n"
            "3 {s: ?c, p: <QLever-internal-function/contains-entity>, o: ?y} : "
            "(1, 2, 4, 6)\n"
            "4 {s: ?c2, p: <QLever-internal-function/contains-entity>, o: ?y} "
            ": (3, 5, 6)\n"
            "5 {s: ?c2, p: <QLever-internal-function/contains-word>, o: xx} : "
            "(4)\n"
            "6 {s: ?y, p: <P2>, o: <X2>} : (3, 4)",
            tg.asString());
        tg.collapseTextCliques();
        ASSERT_EQ(
            "0 {TextOP for ?c, wordPart: \"abc\"} : (1, 2, 3)\n"
            "1 {TextOP for ?c2, wordPart: \"xx\"} : (0, 3)\n"
            "2 {s: ?x, p: <p>, o: <X>} : (0)\n"
            "3 {s: ?y, p: <P2>, o: <X2>} : (0, 1)",
            tg.asString());
        ASSERT_EQ(3ul, tg._nodeMap[0]->_variables.size());
        ASSERT_EQ(2ul, tg._nodeMap[1]->_variables.size());
        ASSERT_EQ(1ul, tg._nodeMap[2]->_variables.size());
        ASSERT_EQ(1ul, tg._nodeMap[3]->_variables.size());
      }
    }
  } catch (const std::exception& e) {
    std::cout << "Caught: " << e.what() << std::endl;
    FAIL() << e.what();
  }
}