void mozTXTToHTMLConv::ScanTXT(const PRUnichar * aInString, int32_t aInStringLength, uint32_t whattodo, nsString& aOutString) { bool doURLs = 0 != (whattodo & kURLs); bool doGlyphSubstitution = 0 != (whattodo & kGlyphSubstitution); bool doStructPhrase = 0 != (whattodo & kStructPhrase); uint32_t structPhrase_strong = 0; // Number of currently open tags uint32_t structPhrase_underline = 0; uint32_t structPhrase_italic = 0; uint32_t structPhrase_code = 0; nsAutoString outputHTML; // moved here for performance increase for(uint32_t i = 0; int32_t(i) < aInStringLength;) { if (doGlyphSubstitution) { int32_t glyphTextLen; if (GlyphHit(&aInString[i], aInStringLength - i, i == 0, aOutString, glyphTextLen)) { i += glyphTextLen; continue; } } if (doStructPhrase) { const PRUnichar * newOffset = aInString; int32_t newLength = aInStringLength; if (i > 0 ) // skip the first element? { newOffset = &aInString[i-1]; newLength = aInStringLength - i + 1; } switch (aInString[i]) // Performance increase { case '*': if (StructPhraseHit(newOffset, newLength, i == 0, NS_LITERAL_STRING("*").get(), 1, "b", "class=\"moz-txt-star\"", aOutString, structPhrase_strong)) { i++; continue; } break; case '/': if (StructPhraseHit(newOffset, newLength, i == 0, NS_LITERAL_STRING("/").get(), 1, "i", "class=\"moz-txt-slash\"", aOutString, structPhrase_italic)) { i++; continue; } break; case '_': if (StructPhraseHit(newOffset, newLength, i == 0, NS_LITERAL_STRING("_").get(), 1, "span" /* <u> is deprecated */, "class=\"moz-txt-underscore\"", aOutString, structPhrase_underline)) { i++; continue; } break; case '|': if (StructPhraseHit(newOffset, newLength, i == 0, NS_LITERAL_STRING("|").get(), 1, "code", "class=\"moz-txt-verticalline\"", aOutString, structPhrase_code)) { i++; continue; } break; } } if (doURLs) { switch (aInString[i]) { case ':': case '@': case '.': if ( (i == 0 || ((i > 0) && aInString[i - 1] != ' ')) && aInString[i +1] != ' ') // Performance increase { int32_t replaceBefore; int32_t replaceAfter; if (FindURL(aInString, aInStringLength, i, whattodo, outputHTML, replaceBefore, replaceAfter) && structPhrase_strong + structPhrase_italic + structPhrase_underline + structPhrase_code == 0 /* workaround for bug #19445 */ ) { aOutString.Cut(aOutString.Length() - replaceBefore, replaceBefore); aOutString += outputHTML; i += replaceAfter + 1; continue; } } break; } //switch } switch (aInString[i]) { // Special symbols case '<': case '>': case '&': EscapeChar(aInString[i], aOutString, false); i++; break; // Normal characters default: aOutString += aInString[i]; i++; break; } } }
bool mozTXTToHTMLConv::FindURLEnd(const PRUnichar * aInString, int32_t aInStringLength, const uint32_t pos, const modetype check, const uint32_t start, uint32_t& end) { switch(check) { // no breaks, because end of blocks is never reached case RFC1738: case RFC2396E: { nsString temp(aInString, aInStringLength); int32_t i = temp.FindCharInSet(NS_LITERAL_STRING("<>\"").get(), pos + 1); if (i != kNotFound && temp[uint32_t(i--)] == (check == RFC1738 || temp[start - 1] == '<' ? '>' : '"')) { end = uint32_t(i); return end > pos; } return false; } case freetext: case abbreviated: { uint32_t i = pos + 1; bool isEmail = aInString[pos] == (PRUnichar)'@'; bool seenOpeningParenthesis = false; // there is a '(' earlier in the URL bool seenOpeningSquareBracket = false; // there is a '[' earlier in the URL for (; int32_t(i) < aInStringLength; i++) { // These chars mark the end of the URL if (aInString[i] == '>' || aInString[i] == '<' || aInString[i] == '"' || aInString[i] == '`' || aInString[i] == '}' || aInString[i] == '{' || aInString[i] == '|' || (aInString[i] == ')' && !seenOpeningParenthesis) || (aInString[i] == ']' && !seenOpeningSquareBracket) || // Allow IPv6 adresses like http://[1080::8:800:200C:417A]/foo. (aInString[i] == '[' && i > 2 && (aInString[i - 1] != '/' || aInString[i - 2] != '/')) || IsSpace(aInString[i])) break; // Disallow non-ascii-characters for email. // Currently correct, but revisit later after standards changed. if (isEmail && ( aInString[i] == '(' || aInString[i] == '\'' || !nsCRT::IsAscii(aInString[i]))) break; if (aInString[i] == '(') seenOpeningParenthesis = true; if (aInString[i] == '[') seenOpeningSquareBracket = true; } // These chars are allowed in the middle of the URL, but not at end. // Technically they are, but are used in normal text after the URL. while (--i > pos && ( aInString[i] == '.' || aInString[i] == ',' || aInString[i] == ';' || aInString[i] == '!' || aInString[i] == '?' || aInString[i] == '-' || aInString[i] == ':' || aInString[i] == '\'' )) ; if (i > pos) { end = i; return true; } return false; } default: return false; } //switch }
extern fc_packet_t * emlxs_pkt_alloc(emlxs_port_t *port, uint32_t cmdlen, uint32_t rsplen, uint32_t datalen, int32_t sleep) { emlxs_hba_t *hba = HBA; fc_packet_t *pkt; int32_t(*cb) (caddr_t); unsigned long real_len; uint32_t pkt_size; emlxs_buf_t *sbp; #if (EMLXS_MODREV >= EMLXS_MODREV3) emlxs_pkt_cookie_t *pkt_cookie; pkt_size = sizeof (fc_packet_t) + sizeof (emlxs_buf_t) + sizeof (emlxs_pkt_cookie_t); #else uint32_t num_cookie; pkt_size = sizeof (fc_packet_t) + sizeof (emlxs_buf_t); #endif /* >= EMLXS_MODREV3 */ /* Allocate some space */ if (!(pkt = (fc_packet_t *)kmem_alloc(pkt_size, sleep))) { return (NULL); } bzero(pkt, pkt_size); cb = (sleep == KM_SLEEP) ? DDI_DMA_SLEEP : DDI_DMA_DONTWAIT; pkt->pkt_ulp_private = (opaque_t)port; pkt->pkt_fca_private = (opaque_t)((uintptr_t)pkt + sizeof (fc_packet_t)); pkt->pkt_comp = emlxs_pkt_callback; pkt->pkt_tran_flags = (FC_TRAN_CLASS3 | FC_TRAN_INTR); pkt->pkt_cmdlen = cmdlen; pkt->pkt_rsplen = rsplen; pkt->pkt_datalen = datalen; #if (EMLXS_MODREV >= EMLXS_MODREV3) pkt_cookie = (emlxs_pkt_cookie_t *)((uintptr_t)pkt + sizeof (fc_packet_t) + sizeof (emlxs_buf_t)); pkt->pkt_cmd_cookie = &pkt_cookie->pkt_cmd_cookie; pkt->pkt_resp_cookie = &pkt_cookie->pkt_resp_cookie; pkt->pkt_data_cookie = &pkt_cookie->pkt_data_cookie; #endif /* >= EMLXS_MODREV3 */ if (cmdlen) { /* Allocate the cmd buf */ if (ddi_dma_alloc_handle(hba->dip, &hba->dma_attr_1sg, cb, NULL, &pkt->pkt_cmd_dma) != DDI_SUCCESS) { cmdlen = 0; rsplen = 0; datalen = 0; goto failed; } if (ddi_dma_mem_alloc(pkt->pkt_cmd_dma, cmdlen, &emlxs_data_acc_attr, DDI_DMA_CONSISTENT, cb, NULL, (caddr_t *)&pkt->pkt_cmd, &real_len, &pkt->pkt_cmd_acc) != DDI_SUCCESS) { (void) ddi_dma_free_handle(&pkt->pkt_cmd_dma); cmdlen = 0; rsplen = 0; datalen = 0; goto failed; } if (real_len < cmdlen) { (void) ddi_dma_mem_free(&pkt->pkt_cmd_acc); (void) ddi_dma_free_handle(&pkt->pkt_cmd_dma); cmdlen = 0; rsplen = 0; datalen = 0; goto failed; } #if (EMLXS_MODREV >= EMLXS_MODREV3) if (ddi_dma_addr_bind_handle(pkt->pkt_cmd_dma, NULL, pkt->pkt_cmd, real_len, DDI_DMA_WRITE | DDI_DMA_CONSISTENT, cb, NULL, pkt->pkt_cmd_cookie, &pkt->pkt_cmd_cookie_cnt) != DDI_DMA_MAPPED) #else if (ddi_dma_addr_bind_handle(pkt->pkt_cmd_dma, NULL, pkt->pkt_cmd, real_len, DDI_DMA_WRITE | DDI_DMA_CONSISTENT, cb, NULL, &pkt->pkt_cmd_cookie, &num_cookie) != DDI_DMA_MAPPED) #endif /* >= EMLXS_MODREV3 */ { (void) ddi_dma_mem_free(&pkt->pkt_cmd_acc); (void) ddi_dma_free_handle(&pkt->pkt_cmd_dma); cmdlen = 0; rsplen = 0; datalen = 0; goto failed; } #if (EMLXS_MODREV >= EMLXS_MODREV3) if (pkt->pkt_cmd_cookie_cnt != 1) #else if (num_cookie != 1) #endif /* >= EMLXS_MODREV3 */ { rsplen = 0; datalen = 0; goto failed; } bzero(pkt->pkt_cmd, cmdlen); } if (rsplen) { /* Allocate the rsp buf */ if (ddi_dma_alloc_handle(hba->dip, &hba->dma_attr_1sg, cb, NULL, &pkt->pkt_resp_dma) != DDI_SUCCESS) { rsplen = 0; datalen = 0; goto failed; } if (ddi_dma_mem_alloc(pkt->pkt_resp_dma, rsplen, &emlxs_data_acc_attr, DDI_DMA_CONSISTENT, cb, NULL, (caddr_t *)&pkt->pkt_resp, &real_len, &pkt->pkt_resp_acc) != DDI_SUCCESS) { (void) ddi_dma_free_handle(&pkt->pkt_resp_dma); rsplen = 0; datalen = 0; goto failed; } if (real_len < rsplen) { (void) ddi_dma_mem_free(&pkt->pkt_resp_acc); (void) ddi_dma_free_handle(&pkt->pkt_resp_dma); rsplen = 0; datalen = 0; goto failed; } #if (EMLXS_MODREV >= EMLXS_MODREV3) if (ddi_dma_addr_bind_handle(pkt->pkt_resp_dma, NULL, pkt->pkt_resp, real_len, DDI_DMA_READ | DDI_DMA_CONSISTENT, cb, NULL, pkt->pkt_resp_cookie, &pkt->pkt_resp_cookie_cnt) != DDI_DMA_MAPPED) #else if (ddi_dma_addr_bind_handle(pkt->pkt_resp_dma, NULL, pkt->pkt_resp, real_len, DDI_DMA_READ | DDI_DMA_CONSISTENT, cb, NULL, &pkt->pkt_resp_cookie, &num_cookie) != DDI_DMA_MAPPED) #endif /* >= EMLXS_MODREV3 */ { (void) ddi_dma_mem_free(&pkt->pkt_resp_acc); (void) ddi_dma_free_handle(&pkt->pkt_resp_dma); rsplen = 0; datalen = 0; goto failed; } #if (EMLXS_MODREV >= EMLXS_MODREV3) if (pkt->pkt_resp_cookie_cnt != 1) #else if (num_cookie != 1) #endif /* >= EMLXS_MODREV3 */ { datalen = 0; goto failed; } bzero(pkt->pkt_resp, rsplen); } /* Allocate the data buf */ if (datalen) { /* Allocate the rsp buf */ if (ddi_dma_alloc_handle(hba->dip, &hba->dma_attr_1sg, cb, NULL, &pkt->pkt_data_dma) != DDI_SUCCESS) { datalen = 0; goto failed; } if (ddi_dma_mem_alloc(pkt->pkt_data_dma, datalen, &emlxs_data_acc_attr, DDI_DMA_CONSISTENT, cb, NULL, (caddr_t *)&pkt->pkt_data, &real_len, &pkt->pkt_data_acc) != DDI_SUCCESS) { (void) ddi_dma_free_handle(&pkt->pkt_data_dma); datalen = 0; goto failed; } if (real_len < datalen) { (void) ddi_dma_mem_free(&pkt->pkt_data_acc); (void) ddi_dma_free_handle(&pkt->pkt_data_dma); datalen = 0; goto failed; } #if (EMLXS_MODREV >= EMLXS_MODREV3) if (ddi_dma_addr_bind_handle(pkt->pkt_data_dma, NULL, pkt->pkt_data, real_len, DDI_DMA_READ | DDI_DMA_WRITE | DDI_DMA_CONSISTENT, cb, NULL, pkt->pkt_data_cookie, &pkt->pkt_data_cookie_cnt) != DDI_DMA_MAPPED) #else if (ddi_dma_addr_bind_handle(pkt->pkt_data_dma, NULL, pkt->pkt_data, real_len, DDI_DMA_READ | DDI_DMA_WRITE | DDI_DMA_CONSISTENT, cb, NULL, &pkt->pkt_data_cookie, &num_cookie) != DDI_DMA_MAPPED) #endif /* >= EMLXS_MODREV3 */ { (void) ddi_dma_mem_free(&pkt->pkt_data_acc); (void) ddi_dma_free_handle(&pkt->pkt_data_dma); datalen = 0; goto failed; } #if (EMLXS_MODREV >= EMLXS_MODREV3) if (pkt->pkt_data_cookie_cnt != 1) #else if (num_cookie != 1) #endif /* >= EMLXS_MODREV3 */ { goto failed; } bzero(pkt->pkt_data, datalen); } sbp = PKT2PRIV(pkt); bzero((void *)sbp, sizeof (emlxs_buf_t)); mutex_init(&sbp->mtx, NULL, MUTEX_DRIVER, DDI_INTR_PRI(hba->intr_arg)); sbp->pkt_flags = PACKET_VALID | PACKET_ULP_OWNED | PACKET_ALLOCATED; sbp->port = port; sbp->pkt = pkt; sbp->iocbq.sbp = sbp; return (pkt); failed: if (datalen) { (void) ddi_dma_unbind_handle(pkt->pkt_data_dma); (void) ddi_dma_mem_free(&pkt->pkt_data_acc); (void) ddi_dma_free_handle(&pkt->pkt_data_dma); } if (rsplen) { (void) ddi_dma_unbind_handle(pkt->pkt_resp_dma); (void) ddi_dma_mem_free(&pkt->pkt_resp_acc); (void) ddi_dma_free_handle(&pkt->pkt_resp_dma); } if (cmdlen) { (void) ddi_dma_unbind_handle(pkt->pkt_cmd_dma); (void) ddi_dma_mem_free(&pkt->pkt_cmd_acc); (void) ddi_dma_free_handle(&pkt->pkt_cmd_dma); } if (pkt) { kmem_free(pkt, pkt_size); } return (NULL); } /* emlxs_pkt_alloc() */
int32_t mozTXTToHTMLConv::CiteLevelTXT(const PRUnichar *line, uint32_t& logLineStart) { int32_t result = 0; int32_t lineLength = NS_strlen(line); bool moreCites = true; while (moreCites) { /* E.g. the following lines count as quote: > text //#ifdef QUOTE_RECOGNITION_AGGRESSIVE >text //#ifdef QUOTE_RECOGNITION_AGGRESSIVE > text ] text USER> text USER] text //#endif logLineStart is the position of "t" in this example */ uint32_t i = logLineStart; #ifdef QUOTE_RECOGNITION_AGGRESSIVE for (; int32_t(i) < lineLength && IsSpace(line[i]); i++) ; for (; int32_t(i) < lineLength && nsCRT::IsAsciiAlpha(line[i]) && nsCRT::IsUpper(line[i]) ; i++) ; if (int32_t(i) < lineLength && (line[i] == '>' || line[i] == ']')) #else if (int32_t(i) < lineLength && line[i] == '>') #endif { i++; if (int32_t(i) < lineLength && line[i] == ' ') i++; // sendmail/mbox // Placed here for performance increase const PRUnichar * indexString = &line[logLineStart]; // here, |logLineStart < lineLength| is always true uint32_t minlength = MinInt(6, NS_strlen(indexString)); if (Substring(indexString, indexString+minlength).Equals(Substring(NS_LITERAL_STRING(">From "), 0, minlength), nsCaseInsensitiveStringComparator())) //XXX RFC2646 moreCites = false; else { result++; logLineStart = i; } } else moreCites = false; } return result; }
int main(int, char**) { int failed = 0; // Basic AMQP types RUN_TEST(failed, simple_type_test(null())); RUN_TEST(failed, simple_type_test(false)); RUN_TEST(failed, simple_type_test(uint8_t(42))); RUN_TEST(failed, simple_type_test(int8_t(-42))); RUN_TEST(failed, simple_type_test(uint16_t(4242))); RUN_TEST(failed, simple_type_test(int16_t(-4242))); RUN_TEST(failed, simple_type_test(uint32_t(4242))); RUN_TEST(failed, simple_type_test(int32_t(-4242))); RUN_TEST(failed, simple_type_test(uint64_t(4242))); RUN_TEST(failed, simple_type_test(int64_t(-4242))); RUN_TEST(failed, simple_type_test(wchar_t('X'))); RUN_TEST(failed, simple_type_test(float(1.234))); RUN_TEST(failed, simple_type_test(double(11.2233))); RUN_TEST(failed, simple_type_test(timestamp(1234))); RUN_TEST(failed, simple_type_test(make_fill<decimal32>(0))); RUN_TEST(failed, simple_type_test(make_fill<decimal64>(0))); RUN_TEST(failed, simple_type_test(make_fill<decimal128>(0))); RUN_TEST(failed, simple_type_test(uuid::copy("\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xaa\xbb\xcc\xdd\xee\xff"))); RUN_TEST(failed, simple_type_test(std::string("xxx"))); RUN_TEST(failed, simple_type_test(symbol("aaa"))); RUN_TEST(failed, simple_type_test(binary("aaa"))); // Native int type that may map differently per platform to uint types. RUN_TEST(failed, simple_type_test(char(42))); RUN_TEST(failed, simple_type_test(short(42))); RUN_TEST(failed, simple_type_test(int(42))); RUN_TEST(failed, simple_type_test(long(42))); RUN_TEST(failed, simple_type_test(static_cast<signed char>(42))); RUN_TEST(failed, simple_type_test(static_cast<signed short>(42))); RUN_TEST(failed, simple_type_test(static_cast<signed int>(42))); RUN_TEST(failed, simple_type_test(static_cast<signed long>(42))); RUN_TEST(failed, simple_type_test(static_cast<unsigned char>(42))); RUN_TEST(failed, simple_type_test(static_cast<unsigned short>(42))); RUN_TEST(failed, simple_type_test(static_cast<unsigned int>(42))); RUN_TEST(failed, simple_type_test(static_cast<unsigned long>(42))); #if PN_CPP_HAS_LONG_LONG_TYPE RUN_TEST(failed, simple_type_test(static_cast<long long>(42))); RUN_TEST(failed, simple_type_test(static_cast<signed long long>(42))); RUN_TEST(failed, simple_type_test(static_cast<unsigned long long>(42))); #endif // value and scalar types, more tests in value_test and scalar_test. RUN_TEST(failed, simple_type_test(value("foo"))); RUN_TEST(failed, value v(23); simple_type_test(v)); RUN_TEST(failed, simple_type_test(scalar(23))); RUN_TEST(failed, simple_type_test(annotation_key(42))); RUN_TEST(failed, simple_type_test(message_id(42))); // Make sure we reject uncodable types RUN_TEST(failed, (uncodable_type_test<std::pair<int, float> >())); RUN_TEST(failed, (uncodable_type_test<std::pair<scalar, value> >())); RUN_TEST(failed, (uncodable_type_test<std::basic_string<wchar_t> >())); RUN_TEST(failed, (uncodable_type_test<internal::data>())); RUN_TEST(failed, (uncodable_type_test<pn_data_t*>())); return failed; }
/*************************************************************************** * Reminder operator * (1) take value from stack * (2) take value from stack * (3) result(1) % result (2) * (4) push result (3) ***************************************************************************/ void CCilVm::reminderOperator() { assert( getEvalStackSize() >= 2 ); CVariable& rhs = getEvalStackFirstEntry(); CVariable& lhs = getEvalStackSecondEntry(); if( lhs.iOperandType == OPERAND_OBJECTREF || rhs.iOperandType == OPERAND_OBJECTREF) { OPERAND_TYPE lhsType = lhs.getPrimitiveType( PRIMITIVETYPE_NUMBER ); OPERAND_TYPE rhsType = rhs.getPrimitiveType( PRIMITIVETYPE_NUMBER ); if( lhsType == OPERAND_STRING ) { rhsType = rhs.getPrimitiveType( PRIMITIVETYPE_STRING ); } else if( rhsType == OPERAND_STRING ) { lhsType = lhs.getPrimitiveType( PRIMITIVETYPE_STRING ); } if( lhsType == OPERAND_OBJECTREF || rhsType == OPERAND_OBJECTREF ) { //Throw TypeError popThrowTypeError(); return; } if( lhsType == OPERAND_UNDEFINED || rhsType == OPERAND_UNDEFINED ) { popPushEvalStackUndefined(); return; } else if( lhsType == OPERAND_NAN || rhsType == OPERAND_NAN ) { popPushEvalStackNaN(); return; } if( lhsType == OPERAND_STRING || rhsType == OPERAND_STRING ) { float fRhs = rhs.toFloat(); float fLhs = lhs.toFloat(); if( !fLhs ) { popPushEvalStack( 0 ); return; } else if( !fRhs ) { popPushEvalStackInfinity(); return; } popPushEvalStack( (float)fmod( fLhs, fRhs ) ); } else if( lhsType == OPERAND_DOUBLE || rhsType == OPERAND_DOUBLE ) { popPushEvalStack( fmod( lhs.toDouble(), rhs.toDouble() ) ); } else if( lhsType == OPERAND_FLOAT || rhsType == OPERAND_FLOAT ) { popPushEvalStack( (float)fmod( lhs.toFloat(), rhs.toFloat() ) ); } else if( lhsType == OPERAND_INT64 || rhsType == OPERAND_INT64 ) { int64_t i64 = rhs.toInt64(); if( !i64 ) { popPushEvalStackInfinity(); return; } popPushEvalStack( lhs.toInt64() % i64 ); } else if( lhsType == OPERAND_INT || rhsType == OPERAND_INT ) { int32_t i = rhs.toInt(); if( !i ) { popPushEvalStackInfinity(); return; } popPushEvalStack( lhs.toInt() % i ); } else if( lhsType == OPERAND_BOOLEAN || rhsType == OPERAND_BOOLEAN ) { int32_t i = rhs.toInt(); if( !i ) { popPushEvalStackInfinity(); return; } popPushEvalStack( lhs.toInt() % rhs.toInt() ); } else { Debug_Fatal( "Not implemented yet" ); } return; } else if( lhs.iOperandType == OPERAND_STRING || rhs.iOperandType == OPERAND_STRING ) { popPushEvalStack( (float)fmod( lhs.toFloat(), rhs.toFloat() ) ); return; } else if( lhs.iOperandType == OPERAND_NAN || rhs.iOperandType == OPERAND_NAN ) { popPushEvalStackUndefined(); return; } else if( lhs.iOperandType == OPERAND_UNDEFINED || rhs.iOperandType == OPERAND_UNDEFINED ) { popPushEvalStackNaN(); return; } // // Check divided by 0 case // if( !lhs.i64Value ) { popEvalStack(); popEvalStack(); pushEvalStack( 0 ); return; } else if( !rhs.i64Value ) { popEvalStack(); popEvalStack(); pushEvalStackInfinity(); return; } int32_t i; int64_t i64; switch( lhs.iOperandType ) { case OPERAND_INT: switch( rhs.iOperandType ) { case OPERAND_INT: i = rhs.toInt(); if( !i ) { popPushEvalStackInfinity(); return; } popPushEvalStack( int32_t( lhs.iValue % i ) ); break; case OPERAND_INT64: i64 = rhs.toInt64(); if( !i64 ) { popPushEvalStackInfinity(); return; } popPushEvalStack( int64_t( int64_t(lhs.iValue) % i64 ) ); break; case OPERAND_FLOAT: if( !_finite( rhs.fValue ) ) popPushEvalStack( lhs.iValue ); else popPushEvalStack( (float)fmod( float( lhs.iValue ), rhs.fValue ) ); break; case OPERAND_DOUBLE: if( !_finite( rhs.dValue ) ) popPushEvalStack( lhs.iValue ); else popPushEvalStack( fmod( double( lhs.iValue ), rhs.dValue ) ); break; case OPERAND_UNDEFINED: case OPERAND_NAN: case OPERAND_STRING: case OPERAND_OBJECTREF: Debug_Fatal( "Illegal operand" ); break; default: i = rhs.toInt(); if( !i ) { popPushEvalStackInfinity(); return; } popPushEvalStack( int32_t( lhs.iValue % i ) ); break; } break; case OPERAND_INT64: switch( rhs.iOperandType ) { case OPERAND_INT: case OPERAND_INT64: i64 = rhs.toInt64(); if( !i64 ) { popPushEvalStackInfinity(); return; } popPushEvalStack( lhs.i64Value % i64 ); break; case OPERAND_FLOAT: if( !_finite( rhs.fValue ) ) popPushEvalStack( lhs.i64Value ); else popPushEvalStack( (float)fmod( float( lhs.i64Value ), rhs.fValue ) ); break; case OPERAND_DOUBLE: if( !_finite( rhs.dValue ) ) popPushEvalStack( lhs.i64Value ); else popPushEvalStack( fmod( double( lhs.i64Value ), rhs.dValue ) ); break; case OPERAND_UNDEFINED: case OPERAND_NAN: case OPERAND_STRING: case OPERAND_OBJECTREF: Debug_Fatal( "Illegal operand" ); break; default: popPushEvalStack( lhs.i64Value % rhs.toInt64() ); break; } break; case OPERAND_FLOAT: switch( rhs.iOperandType ) { case OPERAND_FLOAT: if( !_finite( rhs.fValue ) ) popPushEvalStack( lhs.fValue ); else popPushEvalStack( (float)fmod( lhs.fValue, rhs.fValue ) ); break; case OPERAND_DOUBLE: if( !_finite( rhs.dValue ) ) popPushEvalStack( lhs.fValue ); else popPushEvalStack( fmod( double(lhs.fValue), rhs.dValue ) ); break; case OPERAND_UNDEFINED: case OPERAND_NAN: case OPERAND_STRING: case OPERAND_OBJECTREF: Debug_Fatal( "Illegal operand" ); break; default: { float f = rhs.toFloat(); if( !_finite( f ) ) popPushEvalStack( lhs.fValue ); else popPushEvalStack( (float)fmod( lhs.fValue, f ) ); } break; } break; case OPERAND_DOUBLE: switch( rhs.iOperandType ) { case OPERAND_FLOAT: if( !_finite( rhs.fValue ) ) popPushEvalStack( lhs.dValue ); else popPushEvalStack( fmod( lhs.dValue, double(rhs.fValue) ) ); break; case OPERAND_DOUBLE: if( !_finite( rhs.dValue ) ) popPushEvalStack( lhs.dValue ); else popPushEvalStack( fmod( lhs.dValue, rhs.dValue ) ); break; case OPERAND_UNDEFINED: case OPERAND_NAN: case OPERAND_STRING: case OPERAND_OBJECTREF: Debug_Fatal( "Illegal operand" ); break; default: { double d = rhs.toDouble(); if( !_finite( rhs.fValue ) ) popPushEvalStack( lhs.dValue ); else popPushEvalStack( fmod( lhs.dValue, d ) ); break; } } break; case OPERAND_UNDEFINED: case OPERAND_NAN: case OPERAND_OBJECTREF: case OPERAND_STRING: Debug_Fatal( "Illegal operand" ); break; case OPERAND_BOOLEAN: switch( rhs.iOperandType ) { case OPERAND_UNDEFINED: case OPERAND_NAN: case OPERAND_STRING: case OPERAND_OBJECTREF: Debug_Fatal( "Illegal operand" ); break; default: { float f = rhs.toFloat(); if( !_finite( f ) ) popPushEvalStack( bool( lhs.toFloat() != 0 ) ); else popPushEvalStack( bool( fmod(lhs.toFloat(), f ) != 0) ); } break; } break; case OPERAND_NULL: popPushEvalStack( 0 ); break; default: Debug_Fatal( "Illegal operand" ); break; } }
void CboValidatorCore::ValidateFunctionBlob(size_t blobEnd) { const size_t functionNameIndex = ValidateQualifiedNameIndex(); ValidateSizeAndType(); ValidateParamListSignature(); AssertBytesRemaining(6 * sizeof(Value32)); const uint32_t argSize = ReadValue32().mUInt; const uint32_t packedArgSize = ReadValue32().mUInt; const uint32_t localSize = ReadValue32().mUInt; Skip(sizeof(Value32)); // Ignore the stack size. const uint32_t framePointerAlignment = ReadValue32().mUInt; const size_t codeSize = ReadValue32().mUInt; if ((packedArgSize > argSize) || ((argSize % BOND_SLOT_SIZE) != 0) || ((packedArgSize % BOND_SLOT_SIZE) != 0) || ((localSize % BOND_SLOT_SIZE) != 0) || ((framePointerAlignment % BOND_SLOT_SIZE) != 0)) { FunctionIsInvalid(); } if (functionNameIndex == mResult.mStaticInitializerNameIndex) { ++mResult.mStaticInitializerCount; } else { ++mResult.mFunctionCount; } mResult.mCodeByteCount += AlignUp(codeSize, sizeof(Value32)); AssertBytesRemaining(codeSize); const size_t codeStart = GetPosition(); const size_t codeEnd = codeStart + codeSize; // Do a validation pass on the bytecode and ensure everything is converted to the correct endianness. while (GetPosition() < codeEnd) { const OpCode opCode = static_cast<OpCode>(mStream.Read()); const OpCodeParam param = GetOpCodeParamType(opCode); switch (param) { case OC_PARAM_NONE: break; case OC_PARAM_CHAR: case OC_PARAM_UCHAR: AssertBytesRemaining(1); Skip(1); break; case OC_PARAM_UCHAR_CHAR: case OC_PARAM_SHORT: case OC_PARAM_USHORT: AssertBytesRemaining(sizeof(Value16)); ReadValue16(); break; case OC_PARAM_INT: case OC_PARAM_VAL32: { AssertBytesRemaining(sizeof(Value16)); const size_t valueIndex = ReadValue16().mUShort; if (valueIndex >= mResult.mValue32Count) { CodeIsInvalid(); } } break; case OC_PARAM_VAL64: { AssertBytesRemaining(sizeof(Value16)); const size_t valueIndex = ReadValue16().mUShort; if (valueIndex >= mResult.mValue64Count) { CodeIsInvalid(); } } break; case OC_PARAM_OFF16: { AssertBytesRemaining(sizeof(Value16)); const int32_t offset = ReadValue16().mShort; const int32_t baseAddress = int32_t(GetPosition() - codeStart); const int32_t targetAddress = baseAddress + offset; if ((targetAddress < 0) || (uint32_t(targetAddress) > codeSize)) { CodeIsInvalid(); } } break; case OC_PARAM_OFF32: { AssertBytesRemaining(sizeof(Value16)); const size_t offsetIndex = ReadValue16().mUShort; if (offsetIndex >= mResult.mValue32Count) { CodeIsInvalid(); } else { const int32_t offset = ReadValue32TableAt(offsetIndex).mInt; const int32_t baseAddress = int32_t(GetPosition() - codeStart); const int32_t targetAddress = baseAddress + offset; if ((targetAddress < 0) || (uint32_t(targetAddress) > codeSize)) { CodeIsInvalid(); } } } break; case OC_PARAM_STRING: { AssertBytesRemaining(sizeof(Value16)); const size_t stringIndex = ReadValue16().mUShort; if (stringIndex >= mResult.mStringCount) { CodeIsInvalid(); } } break; case OC_PARAM_NAME: { AssertBytesRemaining(sizeof(Value16)); const size_t nameIndex = ReadValue16().mUShort; if (nameIndex >= mResult.mQualifiedNameCount) { CodeIsInvalid(); } } break; case OC_PARAM_LOOKUPSWITCH: { Skip(AlignUpDelta(GetPosition() - codeStart, sizeof(Value32))); AssertBytesRemaining(2 * sizeof(Value32)); const int32_t defaultOffset = ReadValue32().mInt; const uint32_t numMatches = ReadValue32().mUInt; const size_t tableSize = numMatches * 2 * sizeof(Value32); const int32_t baseAddress = int32_t(GetPosition() + tableSize - codeStart); const int32_t defaultAddress = baseAddress + defaultOffset; AssertBytesRemaining(tableSize); if ((defaultAddress < 0) || (uint32_t(defaultAddress) > codeSize)) { CodeIsInvalid(); } for (uint32_t i = 0; i < numMatches; ++i) { // Skip the match. Skip(sizeof(Value32)); const int32_t offset = ReadValue32().mInt; const int32_t targetAddress = baseAddress + offset; if ((targetAddress < 0) || (uint32_t(targetAddress) > codeSize)) { CodeIsInvalid(); } } } break; case OC_PARAM_TABLESWITCH: { Skip(AlignUpDelta(GetPosition() - codeStart, sizeof(Value32))); AssertBytesRemaining(3 * sizeof(Value32)); const int32_t defaultOffset = ReadValue32().mInt; const int32_t minMatch = ReadValue32().mInt; const int32_t maxMatch = ReadValue32().mInt; const uint32_t numMatches = uint32_t(maxMatch - minMatch + 1); const size_t tableSize = numMatches * sizeof(Value32); const int32_t baseAddress = int32_t(GetPosition() + tableSize - codeStart); const int32_t defaultAddress = baseAddress + defaultOffset; AssertBytesRemaining(tableSize); if (minMatch > maxMatch) { CodeIsInvalid(); } if ((defaultAddress < 0) || (uint32_t(defaultAddress) > codeSize)) { CodeIsInvalid(); } for (size_t i = 0; i < numMatches; ++i) { const int32_t offset = ReadValue32().mInt; const int32_t targetAddress = baseAddress + offset; if ((targetAddress < 0) || (uint32_t(targetAddress) > codeSize)) { CodeIsInvalid(); } } } break; } } // Validate the optional metadata blob. if (GetPosition() < blobEnd) { ValidateBlob(); } }
/** * Read content of file or create file list from directory * @param aBuf read destination buffer * @param aCount length of destination buffer * @param aCountRead number of read characters * @return NS_OK when read successfully, NS_BASE_STREAM_CLOSED when end of file, * error code otherwise */ nsresult nsGIOInputStream::DoRead(char *aBuf, uint32_t aCount, uint32_t *aCountRead) { nsresult rv = NS_ERROR_NOT_AVAILABLE; if (mStream) { // file read GError *error = nullptr; uint32_t bytes_read = g_input_stream_read(G_INPUT_STREAM(mStream), aBuf, aCount, nullptr, &error); if (error) { rv = MapGIOResult(error); *aCountRead = 0; g_warning("Cannot read from file: %s", error->message); g_error_free(error); return rv; } *aCountRead = bytes_read; mBytesRemaining -= *aCountRead; return NS_OK; } else if (mDirOpen) { // directory read while (aCount && rv != NS_BASE_STREAM_CLOSED) { // Copy data out of our buffer uint32_t bufLen = mDirBuf.Length() - mDirBufCursor; if (bufLen) { uint32_t n = std::min(bufLen, aCount); memcpy(aBuf, mDirBuf.get() + mDirBufCursor, n); *aCountRead += n; aBuf += n; aCount -= n; mDirBufCursor += n; } if (!mDirListPtr) // Are we at the end of the directory list? { rv = NS_BASE_STREAM_CLOSED; } else if (aCount) // Do we need more data? { GFileInfo *info = (GFileInfo *) mDirListPtr->data; // Prune '.' and '..' from directory listing. const char * fname = g_file_info_get_name(info); if (fname && fname[0] == '.' && (fname[1] == '\0' || (fname[1] == '.' && fname[2] == '\0'))) { mDirListPtr = mDirListPtr->next; continue; } mDirBuf.AssignLiteral("201: "); // The "filename" field nsCString escName; nsCOMPtr<nsINetUtil> nu = do_GetService(NS_NETUTIL_CONTRACTID); if (nu && fname) { nu->EscapeString(nsDependentCString(fname), nsINetUtil::ESCAPE_URL_PATH, escName); mDirBuf.Append(escName); mDirBuf.Append(' '); } // The "content-length" field // XXX truncates size from 64-bit to 32-bit mDirBuf.AppendInt(int32_t(g_file_info_get_size(info))); mDirBuf.Append(' '); // The "last-modified" field // // NSPR promises: PRTime is compatible with time_t // we just need to convert from seconds to microseconds GTimeVal gtime; g_file_info_get_modification_time(info, >ime); PRExplodedTime tm; PRTime pt = ((PRTime) gtime.tv_sec) * 1000000; PR_ExplodeTime(pt, PR_GMTParameters, &tm); { char buf[64]; PR_FormatTimeUSEnglish(buf, sizeof(buf), "%a,%%20%d%%20%b%%20%Y%%20%H:%M:%S%%20GMT ", &tm); mDirBuf.Append(buf); } // The "file-type" field switch (g_file_info_get_file_type(info)) { case G_FILE_TYPE_REGULAR: mDirBuf.AppendLiteral("FILE "); break; case G_FILE_TYPE_DIRECTORY: mDirBuf.AppendLiteral("DIRECTORY "); break; case G_FILE_TYPE_SYMBOLIC_LINK: mDirBuf.AppendLiteral("SYMBOLIC-LINK "); break; default: break; } mDirBuf.Append('\n'); mDirBufCursor = 0; mDirListPtr = mDirListPtr->next; } } } return rv; }
// ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void FindNeighbors::execute() { setErrorCondition(0); dataCheck(); if(getErrorCondition() < 0) { return; } DataContainer::Pointer m = getDataContainerArray()->getDataContainer(m_FeatureIdsArrayPath.getDataContainerName()); size_t totalPoints = m_FeatureIdsPtr.lock()->getNumberOfTuples(); size_t totalFeatures = m_NumNeighborsPtr.lock()->getNumberOfTuples(); size_t udims[3] = { 0, 0, 0 }; m->getGeometryAs<ImageGeom>()->getDimensions(udims); #if (CMP_SIZEOF_SIZE_T == 4) typedef int32_t DimType; #else typedef int64_t DimType; #endif DimType dims[3] = { static_cast<DimType>(udims[0]), static_cast<DimType>(udims[1]), static_cast<DimType>(udims[2]), }; DimType neighpoints[6] = { 0, 0, 0, 0, 0, 0 }; neighpoints[0] = -dims[0] * dims[1]; neighpoints[1] = -dims[0]; neighpoints[2] = -1; neighpoints[3] = 1; neighpoints[4] = dims[0]; neighpoints[5] = dims[0] * dims[1]; DimType column = 0, row = 0, plane = 0; int32_t feature = 0; int32_t nnum = 0; int8_t onsurf = 0; bool good = false; DimType neighbor = 0; std::vector<std::vector<int32_t> > neighborlist; std::vector<std::vector<float> > neighborsurfacearealist; int32_t nListSize = 100; neighborlist.resize(totalFeatures); neighborsurfacearealist.resize(totalFeatures); uint64_t millis = QDateTime::currentMSecsSinceEpoch(); uint64_t currentMillis = millis; for (size_t i = 1; i < totalFeatures; i++) { currentMillis = QDateTime::currentMSecsSinceEpoch(); if (currentMillis - millis > 1000) { QString ss = QObject::tr("Finding Neighbors || Initializing Neighbor Lists || %1% Complete").arg((static_cast<float>(i) / totalFeatures) * 100); notifyStatusMessage(getMessagePrefix(), getHumanLabel(), ss); millis = QDateTime::currentMSecsSinceEpoch(); } if (getCancel() == true) { return; } m_NumNeighbors[i] = 0; neighborlist[i].resize(nListSize); neighborsurfacearealist[i].assign(nListSize, -1.0f); if (m_StoreSurfaceFeatures == true) { m_SurfaceFeatures[i] = false; } } for (size_t j = 0; j < totalPoints; j++) { currentMillis = QDateTime::currentMSecsSinceEpoch(); if (currentMillis - millis > 1000) { QString ss = QObject::tr("Finding Neighbors || Determining Neighbor Lists || %1% Complete").arg((static_cast<float>(j) / totalPoints) * 100); notifyStatusMessage(getMessagePrefix(), getHumanLabel(), ss); millis = QDateTime::currentMSecsSinceEpoch(); } if (getCancel() == true) { return; } onsurf = 0; feature = m_FeatureIds[j]; if (feature > 0) { column = static_cast<DimType>( j % m->getGeometryAs<ImageGeom>()->getXPoints() ); row = static_cast<DimType>( (j / m->getGeometryAs<ImageGeom>()->getXPoints()) % m->getGeometryAs<ImageGeom>()->getYPoints() ); plane = static_cast<DimType>( j / (m->getGeometryAs<ImageGeom>()->getXPoints() * m->getGeometryAs<ImageGeom>()->getYPoints()) ); if (m_StoreSurfaceFeatures == true) { if ((column == 0 || column == DimType((m->getGeometryAs<ImageGeom>()->getXPoints() - 1)) || row == 0 || row == DimType((m->getGeometryAs<ImageGeom>()->getYPoints()) - 1) || plane == 0 || plane == DimType((m->getGeometryAs<ImageGeom>()->getZPoints() - 1))) && m->getGeometryAs<ImageGeom>()->getZPoints() != 1) { m_SurfaceFeatures[feature] = true; } if ((column == 0 || column == DimType((m->getGeometryAs<ImageGeom>()->getXPoints() - 1)) || row == 0 || row == DimType((m->getGeometryAs<ImageGeom>()->getYPoints() - 1))) && m->getGeometryAs<ImageGeom>()->getZPoints() == 1) { m_SurfaceFeatures[feature] = true; } } for (int32_t k = 0; k < 6; k++) { good = true; neighbor = static_cast<DimType>( j + neighpoints[k] ); if (k == 0 && plane == 0) { good = false; } if (k == 5 && plane == (m->getGeometryAs<ImageGeom>()->getZPoints() - 1)) { good = false; } if (k == 1 && row == 0) { good = false; } if (k == 4 && row == (m->getGeometryAs<ImageGeom>()->getYPoints() - 1)) { good = false; } if (k == 2 && column == 0) { good = false; } if (k == 3 && column == (m->getGeometryAs<ImageGeom>()->getXPoints() - 1)) { good = false; } if (good == true && m_FeatureIds[neighbor] != feature && m_FeatureIds[neighbor] > 0) { onsurf++; nnum = m_NumNeighbors[feature]; neighborlist[feature].push_back(m_FeatureIds[neighbor]); nnum++; m_NumNeighbors[feature] = nnum; } } } if (m_StoreBoundaryCells == true) { m_BoundaryCells[j] = onsurf; } } // We do this to create new set of NeighborList objects for (size_t i = 1; i < totalFeatures; i++) { currentMillis = QDateTime::currentMSecsSinceEpoch(); if (currentMillis - millis > 1000) { QString ss = QObject::tr("Finding Neighbors || Calculating Surface Areas || %1% Complete").arg(((float)i / totalFeatures) * 100); notifyStatusMessage(getMessagePrefix(), getHumanLabel(), ss); millis = QDateTime::currentMSecsSinceEpoch(); } if(getCancel() == true) { return; } QMap<int32_t, int32_t> neighToCount; int32_t numneighs = static_cast<int32_t>( neighborlist[i].size() ); // this increments the voxel counts for each feature for (int32_t j = 0; j < numneighs; j++) { neighToCount[neighborlist[i][j]]++; } QMap<int32_t, int32_t>::Iterator neighiter = neighToCount.find(0); neighToCount.erase(neighiter); neighiter = neighToCount.find(-1); neighToCount.erase(neighiter); // Resize the features neighbor list to zero neighborlist[i].resize(0); neighborsurfacearealist[i].resize(0); for (QMap<int32_t, int32_t>::iterator iter = neighToCount.begin(); iter != neighToCount.end(); ++iter) { int32_t neigh = iter.key(); // get the neighbor feature int32_t number = iter.value(); // get the number of voxels float area = float(number) * m->getGeometryAs<ImageGeom>()->getXRes() * m->getGeometryAs<ImageGeom>()->getYRes(); // Push the neighbor feature id back onto the list so we stay synced up neighborlist[i].push_back(neigh); neighborsurfacearealist[i].push_back(area); } m_NumNeighbors[i] = int32_t(neighborlist[i].size()); // Set the vector for each list into the NeighborList Object NeighborList<int32_t>::SharedVectorType sharedNeiLst(new std::vector<int32_t>); sharedNeiLst->assign(neighborlist[i].begin(), neighborlist[i].end()); m_NeighborList.lock()->setList(static_cast<int32_t>(i), sharedNeiLst); NeighborList<float>::SharedVectorType sharedSAL(new std::vector<float>); sharedSAL->assign(neighborsurfacearealist[i].begin(), neighborsurfacearealist[i].end()); m_SharedSurfaceAreaList.lock()->setList(static_cast<int32_t>(i), sharedSAL); } notifyStatusMessage(getHumanLabel(), "Complete"); }
std::string Item::getDescription(const ItemType& it, int32_t lookDistance, const Item* item/* = NULL*/, int32_t subType/* = -1*/, bool addArticle/* = true*/) { std::stringstream s; s << getNameDescription(it, item, subType, addArticle); if(item) subType = item->getSubType(); bool dot = true; if(it.isRune()) { if(!it.runeSpellName.empty()) s << "(\"" << it.runeSpellName << "\")"; if(it.runeLevel > 0 || it.runeMagLevel > 0 || (it.vocationString != "" && it.wieldInfo == 0)) { s << "." << std::endl << "It can only be used"; if(it.vocationString != "" && it.wieldInfo == 0) s << " by " << it.vocationString; bool begin = true; if(it.runeLevel > 0) { begin = false; s << " with level " << it.runeLevel; } if(it.runeMagLevel > 0) { begin = false; s << " " << (begin ? "with" : "and") << " magic level " << it.runeMagLevel; } if(!begin) s << " or higher"; } } else if(it.weaponType != WEAPON_NONE) { bool begin = true; if(it.weaponType == WEAPON_DIST && it.ammoType != AMMO_NONE) { begin = false; s << " (Range:" << int32_t(item ? item->getShootRange() : it.shootRange); if(it.attack || it.extraAttack || (item && (item->getAttack() || item->getExtraAttack()))) { s << ", Atk " << std::showpos << int32_t(item ? item->getAttack() : it.attack); if(it.extraAttack || (item && item->getExtraAttack())) s << " " << std::showpos << int32_t(item ? item->getExtraAttack() : it.extraAttack) << std::noshowpos; } if(it.hitChance != -1 || (item && item->getHitChance() != -1)) s << ", Hit% " << std::showpos << (item ? item->getHitChance() : it.hitChance) << std::noshowpos; } else if(it.weaponType != WEAPON_AMMO && it.weaponType != WEAPON_WAND) { if(it.attack || it.extraAttack || (item && (item->getAttack() || item->getExtraAttack()))) { begin = false; s << " (Atk:"; if(it.abilities.elementType != COMBAT_NONE && it.decayTo < 1) { s << std::max((int32_t)0, int32_t((item ? item->getAttack() : it.attack) - it.abilities.elementDamage)); if(it.extraAttack || (item && item->getExtraAttack())) s << " " << std::showpos << int32_t(item ? item->getExtraAttack() : it.extraAttack) << std::noshowpos; s << " physical + " << it.abilities.elementDamage << " " << getCombatName(it.abilities.elementType); } else { s << int32_t(item ? item->getAttack() : it.attack); if(it.extraAttack || (item && item->getExtraAttack())) s << " " << std::showpos << int32_t(item ? item->getExtraAttack() : it.extraAttack) << std::noshowpos; } } if(it.defense || it.extraDefense || (item && (item->getDefense() || item->getExtraDefense()))) { if(begin) { begin = false; s << " ("; } else s << ", "; s << "Def:" << int32_t(item ? item->getDefense() : it.defense); if(it.extraDefense || (item && item->getExtraDefense())) s << " " << std::showpos << int32_t(item ? item->getExtraDefense() : it.extraDefense) << std::noshowpos; } } for(uint16_t i = SKILL_FIRST; i <= SKILL_LAST; i++) { if(!it.abilities.skills[i]) continue; if(begin) { begin = false; s << " ("; } else s << ", "; s << getSkillName(i) << " " << std::showpos << (int32_t)it.abilities.skills[i] << std::noshowpos; } if(it.abilities.stats[STAT_MAGICLEVEL]) { if(begin) { begin = false; s << " ("; } else s << ", "; s << "magic level " << std::showpos << (int32_t)it.abilities.stats[STAT_MAGICLEVEL] << std::noshowpos; } // TODO: we should find some better way of completing this int32_t show = it.abilities.absorb[COMBAT_FIRST]; for(int32_t i = (COMBAT_FIRST + 1); i <= COMBAT_LAST; i++) { if(it.abilities.absorb[i] == show) continue; show = 0; break; } if(!show) { bool tmp = true; for(int32_t i = COMBAT_FIRST; i <= COMBAT_LAST; i++) { if(!it.abilities.absorb[i]) continue; if(tmp) { tmp = false; if(begin) { begin = false; s << " ("; } else s << ", "; s << "protection "; } else s << ", "; s << getCombatName((CombatType_t)i) << " " << std::showpos << it.abilities.absorb[i] << std::noshowpos << "%"; } } else { if(begin) { begin = false; s << " ("; } else s << ", "; s << "protection all " << std::showpos << show << std::noshowpos << "%"; } // TODO: same case as absorbs... show = it.abilities.reflect[REFLECT_CHANCE][COMBAT_FIRST]; for(int32_t i = (COMBAT_FIRST + 1); i <= COMBAT_LAST; i++) { if(it.abilities.reflect[REFLECT_CHANCE][i] == show) continue; show = 0; break; } if(!show) { bool tmp = true; for(int32_t i = COMBAT_FIRST; i <= COMBAT_LAST; i++) { if(!it.abilities.reflect[REFLECT_CHANCE][i] || !it.abilities.reflect[REFLECT_PERCENT][i]) continue; if(tmp) { tmp = false; if(begin) { begin = false; s << " ("; } else s << ", "; s << "reflect: "; } else s << ", "; s << it.abilities.reflect[REFLECT_CHANCE][i] << "% for "; if(it.abilities.reflect[REFLECT_PERCENT][i] > 99) s << "whole"; else if(it.abilities.reflect[REFLECT_PERCENT][i] >= 75) s << "huge"; else if(it.abilities.reflect[REFLECT_PERCENT][i] >= 50) s << "medium"; else if(it.abilities.reflect[REFLECT_PERCENT][i] >= 25) s << "small"; else s << "tiny"; s << getCombatName((CombatType_t)i); } if(!tmp) s << " damage"; } else { if(begin) { begin = false; s << " ("; } else s << ", "; int32_t tmp = it.abilities.reflect[REFLECT_PERCENT][COMBAT_FIRST]; for(int32_t i = (COMBAT_FIRST + 1); i <= COMBAT_LAST; i++) { if(it.abilities.reflect[REFLECT_PERCENT][i] == tmp) continue; tmp = 0; break; } s << "reflect: " << show << "% for "; if(tmp) { if(tmp > 99) s << "whole"; else if(tmp >= 75) s << "huge"; else if(tmp >= 50) s << "medium"; else if(tmp >= 25) s << "small"; else s << "tiny"; } else s << "mixed"; s << " damage"; } if(it.abilities.speed) { if(begin) { begin = false; s << " ("; } else s << ", "; s << "speed " << std::showpos << (int32_t)(it.abilities.speed / 2) << std::noshowpos; } if(it.abilities.invisible) { if(begin) { begin = false; s << " ("; } else s << ", "; s << "invisibility"; } if(it.abilities.regeneration) { if(begin) { begin = false; s << " ("; } else s << ", "; s << "faster regeneration"; } if(it.abilities.manaShield) { if(begin) { begin = false; s << " ("; } else s << ", "; s << "mana shield"; } if(hasBitSet(CONDITION_DRUNK, it.abilities.conditionSuppressions)) { if(begin) { begin = false; s << " ("; } else s << ", "; s << "hard drinking"; } if(it.dualWield || (item && item->isDualWield())) { if(begin) { begin = false; s << " ("; } else s << ", "; s << "dual wielding"; } if(!begin) s << ")"; } else if(it.armor || (item && item->getArmor()) || it.showAttributes) { int32_t tmp = it.armor; if(item) tmp = item->getArmor(); bool begin = true; if(tmp) { s << " (Arm:" << tmp; begin = false; } for(uint16_t i = SKILL_FIRST; i <= SKILL_LAST; i++) { if(!it.abilities.skills[i]) continue; if(begin) { begin = false; s << " ("; } else s << ", "; s << getSkillName(i) << " " << std::showpos << (int32_t)it.abilities.skills[i] << std::noshowpos; } if(it.abilities.stats[STAT_MAGICLEVEL]) { if(begin) { begin = false; s << " ("; } else s << ", "; s << "magic level " << std::showpos << (int32_t)it.abilities.stats[STAT_MAGICLEVEL] << std::noshowpos; } // TODO: we should find some better way of completing this int32_t show = it.abilities.absorb[COMBAT_FIRST]; for(int32_t i = (COMBAT_FIRST + 1); i <= COMBAT_LAST; i++) { if(it.abilities.absorb[i] == show) continue; show = 0; break; } if(!show) { bool tmp = true; for(int32_t i = COMBAT_FIRST; i <= COMBAT_LAST; i++) { if(!it.abilities.absorb[i]) continue; if(tmp) { tmp = false; if(begin) { begin = false; s << " ("; } else s << ", "; s << "protection "; } else s << ", "; s << getCombatName((CombatType_t)i) << " " << std::showpos << it.abilities.absorb[i] << std::noshowpos << "%"; } } else { if(begin) { begin = false; s << " ("; } else s << ", "; s << "protection all " << std::showpos << show << std::noshowpos << "%"; } // TODO: same case as absorbs... show = it.abilities.reflect[REFLECT_CHANCE][COMBAT_FIRST]; for(int32_t i = (COMBAT_FIRST + 1); i <= COMBAT_LAST; i++) { if(it.abilities.reflect[REFLECT_CHANCE][i] == show) continue; show = 0; break; } if(!show) { bool tmp = true; for(int32_t i = COMBAT_FIRST; i <= COMBAT_LAST; i++) { if(!it.abilities.reflect[REFLECT_CHANCE][i] || !it.abilities.reflect[REFLECT_PERCENT][i]) continue; if(tmp) { tmp = false; if(begin) { begin = false; s << " ("; } else s << ", "; s << "reflect: "; } else s << ", "; s << it.abilities.reflect[REFLECT_CHANCE][i] << "% for "; if(it.abilities.reflect[REFLECT_PERCENT][i] > 99) s << "whole"; else if(it.abilities.reflect[REFLECT_PERCENT][i] >= 75) s << "huge"; else if(it.abilities.reflect[REFLECT_PERCENT][i] >= 50) s << "medium"; else if(it.abilities.reflect[REFLECT_PERCENT][i] >= 25) s << "small"; else s << "tiny"; s << getCombatName((CombatType_t)i); } if(!tmp) s << " damage"; } else { if(begin) { begin = false; s << " ("; } else s << ", "; int32_t tmp = it.abilities.reflect[REFLECT_PERCENT][COMBAT_FIRST]; for(int32_t i = (COMBAT_FIRST + 1); i <= COMBAT_LAST; i++) { if(it.abilities.reflect[REFLECT_PERCENT][i] == tmp) continue; tmp = 0; break; } s << "reflect: " << show << "% for "; if(tmp) { if(tmp > 99) s << "whole"; else if(tmp >= 75) s << "huge"; else if(tmp >= 50) s << "medium"; else if(tmp >= 25) s << "small"; else s << "tiny"; } else s << "mixed"; s << " damage"; } if(it.abilities.speed) { if(begin) { begin = false; s << " ("; } else s << ", "; s << "speed " << std::showpos << (int32_t)(it.abilities.speed / 2) << std::noshowpos; } if(it.abilities.invisible) { if(begin) { begin = false; s << " ("; } else s << ", "; s << "invisibility"; } if(it.abilities.regeneration) { if(begin) { begin = false; s << " ("; } else s << ", "; s << "faster regeneration"; } if(it.abilities.manaShield) { if(begin) { begin = false; s << " ("; } else s << ", "; s << "mana shield"; } if(hasBitSet(CONDITION_DRUNK, it.abilities.conditionSuppressions)) { if(begin) { begin = false; s << " ("; } else s << ", "; s << "hard drinking"; } if(!begin) s << ")"; } else if(it.isContainer()) s << " (Vol:" << (int32_t)it.maxItems << ")"; else if(it.isKey()) s << " (Key:" << (item ? (int32_t)item->getActionId() : 0) << ")"; else if(it.isFluidContainer()) { if(subType > 0) s << " of " << (items[subType].name.length() ? items[subType].name : "unknown"); else s << ". It is empty"; } else if(it.isSplash()) { s << " of "; if(subType > 0 && items[subType].name.length()) s << items[subType].name; else s << "unknown"; } else if(it.allowDistRead) { s << "." << std::endl; if(item && !item->getText().empty()) { if(lookDistance <= 4) { if(!item->getWriter().empty()) { s << item->getWriter() << " wrote"; time_t date = item->getDate(); if(date > 0) s << " on " << formatDate(date); s << ": "; } else s << "You read: "; std::string text = item->getText(); s << text; char end = *text.rbegin(); if(end == '?' || end == '!' || end == '.') dot = false; } else s << "You are too far away to read it"; } else s << "Nothing is written on it"; } else if(it.levelDoor && item && item->getActionId() >= (int32_t)it.levelDoor && item->getActionId() <= ((int32_t)it.levelDoor + g_config.getNumber(ConfigManager::MAXIMUM_DOOR_LEVEL))) s << " for level " << item->getActionId() - it.levelDoor; if(it.showCharges) s << " that has " << subType << " charge" << (subType != 1 ? "s" : "") << " left"; if(it.showDuration) { if(item && item->hasIntegerAttribute("duration")) { int32_t duration = item->getDuration() / 1000; s << " that has energy for "; if(duration >= 120) s << duration / 60 << " minutes left"; else if(duration > 60) s << "1 minute left"; else s << " less than a minute left"; } else s << " that is brand-new"; } if(dot) s << "."; if(it.wieldInfo) { s << std::endl << "It can only be wielded properly by "; if(it.wieldInfo & WIELDINFO_PREMIUM) s << "premium "; if(it.wieldInfo & WIELDINFO_VOCREQ) s << it.vocationString; else s << "players"; if(it.wieldInfo & WIELDINFO_LEVEL) s << " of level " << (int32_t)it.minReqLevel << " or higher"; if(it.wieldInfo & WIELDINFO_MAGLV) { if(it.wieldInfo & WIELDINFO_LEVEL) s << " and"; else s << " of"; s << " magic level " << (int32_t)it.minReqMagicLevel << " or higher"; } s << "."; } if(lookDistance <= 1 && it.pickupable) { std::string tmp; if(!item) tmp = getWeightDescription(it.weight, it.stackable && it.showCount, subType); else tmp = item->getWeightDescription(); if(!tmp.empty()) s << std::endl << tmp; } if(it.abilities.elementType != COMBAT_NONE && it.decayTo > 0) { s << std::endl << "It is temporarily enchanted with " << getCombatName(it.abilities.elementType) << " ("; s << std::max((int32_t)0, int32_t((item ? item->getAttack() : it.attack) - it.abilities.elementDamage)); if(it.extraAttack || (item && item->getExtraAttack())) s << " " << std::showpos << int32_t(item ? item->getExtraAttack() : it.extraAttack) << std::noshowpos; s << " physical + " << it.abilities.elementDamage << " " << getCombatName(it.abilities.elementType) << " damage)."; } std::string str; if(item && !item->getSpecialDescription().empty()) str = item->getSpecialDescription(); else if(!it.description.empty() && lookDistance <= 1) str = it.description; if(str.empty()) return s.str(); if(str.find("|PLAYERNAME|") != std::string::npos) { std::string tmp = "You"; if(item) { if(const Player* player = item->getHoldingPlayer()) tmp = player->getName(); } replaceString(str, "|PLAYERNAME|", tmp); } if(str.find("|TIME|") != std::string::npos || str.find("|DATE|") != std::string::npos || str.find( "|DAY|") != std::string::npos || str.find("|MONTH|") != std::string::npos || str.find( "|YEAR|") != std::string::npos || str.find("|HOUR|") != std::string::npos || str.find( "|MINUTES|") != std::string::npos || str.find("|SECONDS|") != std::string::npos || str.find("|WEEKDAY|") != std::string::npos || str.find("|YEARDAY|") != std::string::npos) { time_t now = time(NULL); tm* ts = localtime(&now); std::stringstream ss; ss << ts->tm_sec; replaceString(str, "|SECONDS|", ss.str()); ss.str(""); ss << ts->tm_min; replaceString(str, "|MINUTES|", ss.str()); ss.str(""); ss << ts->tm_hour; replaceString(str, "|HOUR|", ss.str()); ss.str(""); ss << ts->tm_mday; replaceString(str, "|DAY|", ss.str()); ss.str(""); ss << (ts->tm_mon + 1); replaceString(str, "|MONTH|", ss.str()); ss.str(""); ss << (ts->tm_year + 1900); replaceString(str, "|YEAR|", ss.str()); ss.str(""); ss << ts->tm_wday; replaceString(str, "|WEEKDAY|", ss.str()); ss.str(""); ss << ts->tm_yday; replaceString(str, "|YEARDAY|", ss.str()); ss.str(""); ss << ts->tm_hour << ":" << ts->tm_min << ":" << ts->tm_sec; replaceString(str, "|TIME|", ss.str()); ss.str(""); replaceString(str, "|DATE|", formatDateEx(now)); } s << std::endl << str; return s.str(); }
void RasterImage::NotifyDecodeComplete(const DecoderFinalStatus& aStatus, const ImageMetadata& aMetadata, const DecoderTelemetry& aTelemetry, Progress aProgress, const IntRect& aInvalidRect, const Maybe<uint32_t>& aFrameCount, DecoderFlags aDecoderFlags, SurfaceFlags aSurfaceFlags) { MOZ_ASSERT(NS_IsMainThread()); // If the decoder detected an error, log it to the error console. if (aStatus.mShouldReportError) { ReportDecoderError(); } // Record all the metadata the decoder gathered about this image. bool metadataOK = SetMetadata(aMetadata, aStatus.mWasMetadataDecode); if (!metadataOK) { // This indicates a serious error that requires us to discard all existing // surfaces and redecode to recover. We'll drop the results from this // decoder on the floor, since they aren't valid. RecoverFromInvalidFrames(mSize, FromSurfaceFlags(aSurfaceFlags)); return; } MOZ_ASSERT(mError || mHasSize || !aMetadata.HasSize(), "SetMetadata should've gotten a size"); if (!aStatus.mWasMetadataDecode && aStatus.mFinished) { // Flag that we've been decoded before. mHasBeenDecoded = true; } // Send out any final notifications. NotifyProgress(aProgress, aInvalidRect, aFrameCount, aDecoderFlags, aSurfaceFlags); if (!(aDecoderFlags & DecoderFlags::FIRST_FRAME_ONLY) && mHasBeenDecoded && mAnimationState) { // We've finished a full decode of all animation frames and our AnimationState // has been notified about them all, so let it know not to expect anymore. mAnimationState->SetDoneDecoding(true); } // Do some telemetry if this isn't a metadata decode. if (!aStatus.mWasMetadataDecode) { if (aTelemetry.mChunkCount) { Telemetry::Accumulate(Telemetry::IMAGE_DECODE_CHUNKS, aTelemetry.mChunkCount); } if (aStatus.mFinished) { Telemetry::Accumulate(Telemetry::IMAGE_DECODE_TIME, int32_t(aTelemetry.mDecodeTime.ToMicroseconds())); if (aTelemetry.mSpeedHistogram) { Telemetry::Accumulate(*aTelemetry.mSpeedHistogram, aTelemetry.Speed()); } } } // Only act on errors if we have no usable frames from the decoder. if (aStatus.mHadError && (!mAnimationState || mAnimationState->KnownFrameCount() == 0)) { DoError(); } else if (aStatus.mWasMetadataDecode && !mHasSize) { DoError(); } // XXX(aosmond): Can we get this far without mFinished == true? if (aStatus.mFinished && aStatus.mWasMetadataDecode) { // If we were waiting to fire the load event, go ahead and fire it now. if (mLoadProgress) { NotifyForLoadEvent(*mLoadProgress); mLoadProgress = Nothing(); NotifyProgress(FLAG_ONLOAD_UNBLOCKED); } // If we were a metadata decode and a full decode was requested, do it. if (mWantFullDecode) { mWantFullDecode = false; RequestDecodeForSize(mSize, DECODE_FLAGS_DEFAULT); } } }
RasterImage::Draw(gfxContext* aContext, const IntSize& aSize, const ImageRegion& aRegion, uint32_t aWhichFrame, SamplingFilter aSamplingFilter, const Maybe<SVGImageContext>& /*aSVGContext - ignored*/, uint32_t aFlags, float aOpacity) { if (aWhichFrame > FRAME_MAX_VALUE) { return DrawResult::BAD_ARGS; } if (mError) { return DrawResult::BAD_IMAGE; } // Illegal -- you can't draw with non-default decode flags. // (Disabling colorspace conversion might make sense to allow, but // we don't currently.) if (ToSurfaceFlags(aFlags) != DefaultSurfaceFlags()) { return DrawResult::BAD_ARGS; } if (!aContext) { return DrawResult::BAD_ARGS; } if (IsUnlocked()) { SendOnUnlockedDraw(aFlags); } // If we're not using SamplingFilter::GOOD, we shouldn't high-quality scale or // downscale during decode. uint32_t flags = aSamplingFilter == SamplingFilter::GOOD ? aFlags : aFlags & ~FLAG_HIGH_QUALITY_SCALING; DrawableSurface surface = LookupFrame(aSize, flags, ToPlaybackType(aWhichFrame)); if (!surface) { // Getting the frame (above) touches the image and kicks off decoding. if (mDrawStartTime.IsNull()) { mDrawStartTime = TimeStamp::Now(); } return DrawResult::NOT_READY; } bool shouldRecordTelemetry = !mDrawStartTime.IsNull() && surface->IsFinished(); auto result = DrawInternal(Move(surface), aContext, aSize, aRegion, aSamplingFilter, flags, aOpacity); if (shouldRecordTelemetry) { TimeDuration drawLatency = TimeStamp::Now() - mDrawStartTime; Telemetry::Accumulate(Telemetry::IMAGE_DECODE_ON_DRAW_LATENCY, int32_t(drawLatency.ToMicroseconds())); mDrawStartTime = TimeStamp(); } return result; }
bool shape_record_factory(bit_stream_ptr bits, int version, unsigned& fill_bits, unsigned& line_bits, std::vector<shape_record_ptr>* records) { bool edge_record = bits->read_unsigned_bits(1) ? true : false; unsigned flags = unsigned(bits->read_unsigned_bits(5)); if(flags == 0) { bits->force_byte_align(); return false; } if(edge_record) { if(flags & 16) { // straight auto srp = std::make_shared<shape_record>(ShapeRecordTypes::LINE); unsigned num_bits = (flags & 0x0f) + 2; bool general_line = bits->read_unsigned_bits(1) ? true : false; delta_record dr; if(general_line) { dr.delta_x = int32_t(bits->read_unsigned_bits(num_bits)); dr.delta_y = int32_t(bits->read_unsigned_bits(num_bits)); } else { bool vertical_line = bits->read_unsigned_bits(1) ? true : false; if(vertical_line) { dr.delta_x = int32_t(bits->read_signed_bits(num_bits)); dr.delta_y = 0; } else { dr.delta_x = 0; dr.delta_y = int32_t(bits->read_signed_bits(num_bits)); } } srp->set_delta(dr); records->emplace_back(srp); return true; } else { auto cer = std::make_shared<curve_edge_record>(); unsigned num_bits = (flags & 0x0f) + 2; delta_record dr; dr.delta_x = int32_t(bits->read_signed_bits(num_bits)); dr.delta_y = int32_t(bits->read_signed_bits(num_bits)); cer->set_control(dr); dr.delta_x = int32_t(bits->read_signed_bits(num_bits)); dr.delta_y = int32_t(bits->read_signed_bits(num_bits)); cer->set_anchor(dr); records->emplace_back(cer); return true; } } else { if(flags & 1) { std::shared_ptr<move_record> mrp = std::make_shared<move_record>(); delta_record moves; unsigned move_bits = unsigned(bits->read_unsigned_bits(5)); moves.delta_x = int32_t(bits->read_signed_bits(move_bits)); moves.delta_y = int32_t(bits->read_signed_bits(move_bits)); mrp->set_delta(moves); records->emplace_back(mrp); } if(flags & (2|4|8|16)) { std::shared_ptr<style_change_record> srp = std::make_shared<style_change_record>(); if(flags & 2) { srp->set_fillstyle0_index(bits->read_unsigned_bits(fill_bits)); } if(flags & 4) { srp->set_fillstyle1_index(bits->read_unsigned_bits(fill_bits)); } if(flags & 8) { srp->set_linestyle_index(bits->read_unsigned_bits(line_bits)); } if(flags & 16) { styles ss; ss.fill_styles_ = bits->read_fillstyle_array(version); ss.line_styles_ = bits->read_linestyle_array(version); fill_bits = ss.fill_bits_ = bits->read_unsigned_bits(4); line_bits = ss.line_bits_ = bits->read_unsigned_bits(4); srp->set_styles(ss); } records->emplace_back(srp); } return true; } }
void GlContext::create(uint32_t _width, uint32_t _height) { # if BX_PLATFORM_RPI bcm_host_init(); # endif // BX_PLATFORM_RPI m_eglLibrary = eglOpen(); if (NULL == g_platformData.context) { # if BX_PLATFORM_RPI g_platformData.ndt = EGL_DEFAULT_DISPLAY; # endif // BX_PLATFORM_RPI BX_UNUSED(_width, _height); EGLNativeDisplayType ndt = (EGLNativeDisplayType)g_platformData.ndt; EGLNativeWindowType nwh = (EGLNativeWindowType )g_platformData.nwh; # if BX_PLATFORM_WINDOWS if (NULL == g_platformData.ndt) { ndt = GetDC( (HWND)g_platformData.nwh); } # endif // BX_PLATFORM_WINDOWS m_display = eglGetDisplay(ndt); BGFX_FATAL(m_display != EGL_NO_DISPLAY, Fatal::UnableToInitialize, "Failed to create display %p", m_display); EGLint major = 0; EGLint minor = 0; EGLBoolean success = eglInitialize(m_display, &major, &minor); BGFX_FATAL(success && major >= 1 && minor >= 3, Fatal::UnableToInitialize, "Failed to initialize %d.%d", major, minor); BX_TRACE("EGL info:"); const char* clientApis = eglQueryString(m_display, EGL_CLIENT_APIS); BX_TRACE(" APIs: %s", clientApis); BX_UNUSED(clientApis); const char* vendor = eglQueryString(m_display, EGL_VENDOR); BX_TRACE(" Vendor: %s", vendor); BX_UNUSED(vendor); const char* version = eglQueryString(m_display, EGL_VERSION); BX_TRACE("Version: %s", version); BX_UNUSED(version); const char* extensions = eglQueryString(m_display, EGL_EXTENSIONS); BX_TRACE("Supported EGL extensions:"); dumpExtensions(extensions); EGLint attrs[] = { EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, # if BX_PLATFORM_ANDROID EGL_DEPTH_SIZE, 16, # else EGL_DEPTH_SIZE, 24, # endif // BX_PLATFORM_ EGL_STENCIL_SIZE, 8, EGL_NONE }; EGLint numConfig = 0; success = eglChooseConfig(m_display, attrs, &m_config, 1, &numConfig); BGFX_FATAL(success, Fatal::UnableToInitialize, "eglChooseConfig"); # if BX_PLATFORM_ANDROID EGLint format; eglGetConfigAttrib(m_display, m_config, EGL_NATIVE_VISUAL_ID, &format); ANativeWindow_setBuffersGeometry( (ANativeWindow*)g_platformData.nwh, _width, _height, format); # elif BX_PLATFORM_RPI DISPMANX_DISPLAY_HANDLE_T dispmanDisplay = vc_dispmanx_display_open(0); DISPMANX_UPDATE_HANDLE_T dispmanUpdate = vc_dispmanx_update_start(0); VC_RECT_T dstRect = { 0, 0, int32_t(_width), int32_t(_height) }; VC_RECT_T srcRect = { 0, 0, int32_t(_width) << 16, int32_t(_height) << 16 }; DISPMANX_ELEMENT_HANDLE_T dispmanElement = vc_dispmanx_element_add(dispmanUpdate , dispmanDisplay , 0 , &dstRect , 0 , &srcRect , DISPMANX_PROTECTION_NONE , NULL , NULL , DISPMANX_NO_ROTATE ); s_dispmanWindow.element = dispmanElement; s_dispmanWindow.width = _width; s_dispmanWindow.height = _height; nwh = &s_dispmanWindow; vc_dispmanx_update_submit_sync(dispmanUpdate); # endif // BX_PLATFORM_ANDROID m_surface = eglCreateWindowSurface(m_display, m_config, nwh, NULL); BGFX_FATAL(m_surface != EGL_NO_SURFACE, Fatal::UnableToInitialize, "Failed to create surface."); const bool hasEglKhrCreateContext = !!bx::findIdentifierMatch(extensions, "EGL_KHR_create_context"); const bool hasEglKhrNoError = !!bx::findIdentifierMatch(extensions, "EGL_KHR_create_context_no_error"); for (uint32_t ii = 0; ii < 2; ++ii) { bx::StaticMemoryBlockWriter writer(s_contextAttrs, sizeof(s_contextAttrs) ); EGLint flags = 0; # if BX_PLATFORM_RPI BX_UNUSED(hasEglKhrCreateContext, hasEglKhrNoError); #else if (hasEglKhrCreateContext) { bx::write(&writer, EGLint(EGL_CONTEXT_MAJOR_VERSION_KHR) ); bx::write(&writer, EGLint(BGFX_CONFIG_RENDERER_OPENGLES / 10) ); bx::write(&writer, EGLint(EGL_CONTEXT_MINOR_VERSION_KHR) ); bx::write(&writer, EGLint(BGFX_CONFIG_RENDERER_OPENGLES % 10) ); flags |= BGFX_CONFIG_DEBUG && hasEglKhrNoError ? 0 | EGL_CONTEXT_FLAG_NO_ERROR_BIT_KHR : 0 ; if (0 == ii) { flags |= BGFX_CONFIG_DEBUG ? 0 | EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR // | EGL_OPENGL_ES3_BIT_KHR : 0 ; bx::write(&writer, EGLint(EGL_CONTEXT_FLAGS_KHR) ); bx::write(&writer, flags); } } else # endif // BX_PLATFORM_RPI { bx::write(&writer, EGLint(EGL_CONTEXT_CLIENT_VERSION) ); bx::write(&writer, 2); } bx::write(&writer, EGLint(EGL_NONE) ); m_context = eglCreateContext(m_display, m_config, EGL_NO_CONTEXT, s_contextAttrs); if (NULL != m_context) { break; } BX_TRACE("Failed to create EGL context with EGL_CONTEXT_FLAGS_KHR (%08x).", flags); } BGFX_FATAL(m_context != EGL_NO_CONTEXT, Fatal::UnableToInitialize, "Failed to create context."); success = eglMakeCurrent(m_display, m_surface, m_surface, m_context); BGFX_FATAL(success, Fatal::UnableToInitialize, "Failed to set context."); m_current = NULL; eglSwapInterval(m_display, 0); } import(); }
JS_REQUIRES_STACK AbortableRecordingStatus TraceRecorder::upRecursion() { JS_ASSERT((JSOp)*cx->fp->down->regs->pc == JSOP_CALL); JS_ASSERT(js_CodeSpec[js_GetOpcode(cx, cx->fp->down->script, cx->fp->down->regs->pc)].length == JSOP_CALL_LENGTH); JS_ASSERT(callDepth == 0); /* * If some operation involving interpreter frame slurping failed, go to * that code right away, and don't bother with emitting the up-recursive * guards again. */ if (anchor && (anchor->exitType == RECURSIVE_EMPTY_RP_EXIT || anchor->exitType == RECURSIVE_SLURP_MISMATCH_EXIT || anchor->exitType == RECURSIVE_SLURP_FAIL_EXIT)) { return slurpDownFrames(cx->fp->down->regs->pc); } jsbytecode* return_pc = cx->fp->down->regs->pc; jsbytecode* recursive_pc = return_pc + JSOP_CALL_LENGTH; /* * It is possible that the down frame isn't the same at runtime. It's not * enough to guard on the PC, since the typemap could be different as well. * To deal with this, guard that the FrameInfo on the callstack is 100% * identical. * * Note that though the counted slots is called "downPostSlots", this is * the number of slots after the CALL instruction has theoretically popped * callee/this/argv, but before the return value is pushed. This is * intended since the FrameInfo pushed by down recursion would not have * the return value yet. Instead, when closing the loop, the return value * becomes the sole stack type that deduces type stability. */ unsigned totalSlots = NativeStackSlots(cx, 1); unsigned downPostSlots = totalSlots - NativeStackSlots(cx, 0); FrameInfo* fi = (FrameInfo*)alloca(sizeof(FrameInfo) + totalSlots * sizeof(TraceType)); fi->block = NULL; fi->pc = (jsbytecode*)return_pc; fi->imacpc = NULL; /* * Need to compute this from the down frame, since the stack could have * moved on this one. */ fi->spdist = cx->fp->down->regs->sp - cx->fp->down->slots; JS_ASSERT(cx->fp->argc == cx->fp->down->argc); fi->set_argc(cx->fp->argc, false); fi->callerHeight = downPostSlots; fi->callerArgc = cx->fp->down->argc; if (anchor && anchor->exitType == RECURSIVE_MISMATCH_EXIT) { /* * Case 0: Anchoring off a RECURSIVE_MISMATCH guard. Guard on this FrameInfo. * This is always safe because this point is only reached on simple "call myself" * recursive functions. */ #if defined DEBUG AssertDownFrameIsConsistent(cx, anchor, fi); #endif fi = anchor->recursive_down; } else if (recursive_pc != fragment->root->ip) { /* * Case 1: Guess that down-recursion has to started back out, infer types * from the down frame. */ CaptureStackTypes(cx, 1, fi->get_typemap()); } else { /* Case 2: Guess that up-recursion is backing out, infer types from our Tree. */ JS_ASSERT(tree->nStackTypes == downPostSlots + 1); TraceType* typeMap = fi->get_typemap(); for (unsigned i = 0; i < downPostSlots; i++) typeMap[i] = tree->typeMap[i]; } fi = traceMonitor->frameCache->memoize(fi); /* * Guard that there are more recursive frames. If coming from an anchor * where this was already computed, don't bother doing it again. */ if (!anchor || anchor->exitType != RECURSIVE_MISMATCH_EXIT) { VMSideExit* exit = snapshot(RECURSIVE_EMPTY_RP_EXIT); /* Guard that rp >= sr + 1 */ guard(true, lir->ins2(LIR_pge, lirbuf->rp, lir->ins2(LIR_piadd, lir->insLoad(LIR_ldp, lirbuf->state, offsetof(InterpState, sor)), INS_CONSTWORD(sizeof(FrameInfo*)))), exit); } debug_only_printf(LC_TMRecorder, "guardUpRecursive fragment->root=%p fi=%p\n", (void*)fragment->root, (void*)fi); /* Guard that the FrameInfo above is the same FrameInfo pointer. */ VMSideExit* exit = snapshot(RECURSIVE_MISMATCH_EXIT); LIns* prev_rp = lir->insLoad(LIR_ldp, lirbuf->rp, -int32_t(sizeof(FrameInfo*))); guard(true, lir->ins2(LIR_peq, prev_rp, INS_CONSTPTR(fi)), exit); /* * Now it's time to try and close the loop. Get a special exit that points * at the down frame, after the return has been propagated up. */ exit = downSnapshot(fi); LIns* rval_ins = (!anchor || anchor->exitType != RECURSIVE_SLURP_FAIL_EXIT) ? get(&stackval(-1)) : NULL; JS_ASSERT(rval_ins != NULL); TraceType returnType = exit->stackTypeMap()[downPostSlots]; if (returnType == TT_INT32) { JS_ASSERT(determineSlotType(&stackval(-1)) == TT_INT32); JS_ASSERT(isPromoteInt(rval_ins)); rval_ins = demote(lir, rval_ins); } UpRecursiveSlotMap slotMap(*this, downPostSlots, rval_ins); for (unsigned i = 0; i < downPostSlots; i++) slotMap.addSlot(exit->stackType(i)); slotMap.addSlot(&stackval(-1)); VisitGlobalSlots(slotMap, cx, *tree->globalSlots); if (recursive_pc == (jsbytecode*)fragment->root->ip) { debug_only_print0(LC_TMTracer, "Compiling up-recursive loop...\n"); } else { debug_only_print0(LC_TMTracer, "Compiling up-recursive branch...\n"); exit->exitType = RECURSIVE_UNLINKED_EXIT; exit->recursive_pc = recursive_pc; } JS_ASSERT(tree->recursion != Recursion_Disallowed); if (tree->recursion != Recursion_Detected) tree->recursion = Recursion_Unwinds; return closeLoop(slotMap, exit); }