Example #1
0
void CookieManager::getRawCookies(Vector<RefPtr<ParsedCookie> > &stackOfCookies, const URL& requestURL, CookieFilter filter) const
{
    // Force a sync load of the database
    if (!m_syncedWithDatabase && !m_privateMode)
        m_cookieBackingStore->openAndLoadDatabaseSynchronously(cookieJar());

    CookieLog("CookieManager - getRawCookies - processing url with domain - %s & protocol: %s & path: %s\n", requestURL.host().utf8().data(), requestURL.protocol().utf8().data(), requestURL.path().utf8().data());

    const bool invalidScheme = shouldIgnoreScheme(requestURL.protocol());
    const bool specialCaseForWebWorks = invalidScheme && m_shouldDumpAllCookies;
    const bool isConnectionSecure = requestURL.protocolIs("https") || requestURL.protocolIs("wss") || specialCaseForWebWorks;

    Vector<RefPtr<ParsedCookie> > cookieCandidates;
    Vector<CookieMap*> protocolsToSearch;

    // Special Case: If a server sets a "secure" cookie over a non-secure channel and tries to access the cookie
    // over a secure channel, it will not succeed because the secure protocol isn't mapped to the insecure protocol yet.
    // Set the map to the non-secure version, so it'll search the mapping for a secure cookie.
    CookieMap* targetMap = m_managerMap.get(requestURL.protocol());
    if (!targetMap && isConnectionSecure) {
        CookieLog("CookieManager - special case: secure protocol are not linked yet.");
        if (requestURL.protocolIs("https"))
            targetMap = m_managerMap.get("http");
        else if (requestURL.protocolIs("wss"))
            targetMap = m_managerMap.get("ws");
    }

    // Decide which scheme tree we should look at.
    // Return on invalid schemes. cookies are currently disabled on file and local.
    // We only want to enable them for WebWorks that enabled a special flag.
    if (specialCaseForWebWorks)
        copyValuesToVector(m_managerMap, protocolsToSearch);
    else if (invalidScheme)
        return;
    else {
        protocolsToSearch.append(targetMap);
        // FIXME: this is a hack for webworks apps; RFC 6265 says "Cookies do not provide isolation by scheme"
        // so we should not be checking protocols at all. See PR 135595
        if (m_shouldDumpAllCookies) {
            protocolsToSearch.append(m_managerMap.get("file"));
            protocolsToSearch.append(m_managerMap.get("local"));
        }
    }

    Vector<String> delimitedHost;

    // IP addresses are stored in a particular format (due to ipv6). Reduce the ip address so we can match
    // it with the one in memory.
    BlackBerry::Platform::String canonicalIP = BlackBerry::Platform::getCanonicalIPFormat(requestURL.host());
    if (!canonicalIP.empty())
        delimitedHost.append(String(canonicalIP.c_str()));
    else
        requestURL.host().lower().split(".", true, delimitedHost);

    // Go through all the protocol trees that we need to search for
    // and get all cookies that are valid for this domain
    for (size_t k = 0; k < protocolsToSearch.size(); k++) {
        CookieMap* currentMap = protocolsToSearch[k];

        // if no cookies exist for this protocol, break right away
        if (!currentMap)
            continue;

        CookieLog("CookieManager - looking at protocol map %s \n", currentMap->getName().utf8().data());

        // Special case for local and files - because WebApps expect to get ALL cookies from the backing-store on local protocol
        if (specialCaseForWebWorks) {
            CookieLog("CookieManager - special case find in protocol map - %s\n", currentMap->getName().utf8().data());
            currentMap->getAllChildCookies(&cookieCandidates);
        } else {
            // Get cookies from the null domain map
            currentMap->getAllCookies(&cookieCandidates);

            // Get cookies from Host-only cookies
            if (canonicalIP.empty()) {
                CookieLog("CookieManager - looking for host-only cookies for host - %s", requestURL.host().utf8().data());
                CookieMap* hostMap = currentMap->getSubdomainMap(requestURL.host());
                if (hostMap)
                    hostMap->getAllCookies(&cookieCandidates);
            }

            // Get cookies from the valid domain maps
            int i = delimitedHost.size() - 1;
            while (i >= 0) {
                CookieLog("CookieManager - finding %s in currentmap\n", delimitedHost[i].utf8().data());
                currentMap = currentMap->getSubdomainMap(delimitedHost[i]);
                // if this subdomain/domain does not exist in our mapping then we simply exit
                if (!currentMap) {
                    CookieLog("CookieManager - cannot find next map exiting the while loop.\n");
                    break;
                }
                CookieLog("CookieManager - found the map, grabbing cookies from this map\n");
                currentMap->getAllCookies(&cookieCandidates);
                i--;
            }
        }
    }

    CookieLog("CookieManager - there are %d cookies in candidate\n", cookieCandidates.size());

    for (size_t i = 0; i < cookieCandidates.size(); ++i) {
        RefPtr<ParsedCookie> cookie = cookieCandidates[i];

        // According to the path-matches rules in RFC6265, section 5.1.4,
        // we should add a '/' at the end of cookie-path for comparison if the cookie-path is not end with '/'.
        String path = cookie->path();
        CookieLog("CookieManager - comparing cookie path %s (len %d) to request path %s (len %d)", path.utf8().data(), path.length(), requestURL.path().utf8().data(), path.length());
        if (!equalIgnoringCase(path, requestURL.path()) && !path.endsWith("/", false))
            path = path + "/";

        // Only secure connections have access to secure cookies. Unless specialCaseForWebWorks is true.
        // Get the cookies filtering out HttpOnly cookies if requested.
        if (requestURL.path().startsWith(path, false) && (isConnectionSecure || !cookie->isSecure()) && (filter == WithHttpOnlyCookies || !cookie->isHttpOnly())) {
            CookieLog("CookieManager - cookie chosen - %s\n", cookie->toString().utf8().data());
            cookie->setLastAccessed(currentTime());
            stackOfCookies.append(cookie);
        }
    }

    std::stable_sort(stackOfCookies.begin(), stackOfCookies.end(), cookieSorter);
}
Example #2
0
static void writeLayers(TextStream& ts, const RenderLayer* rootLayer, RenderLayer* l,
                        const LayoutRect& paintRect, int indent, RenderAsTextBehavior behavior)
{
    // FIXME: Apply overflow to the root layer to not break every test.  Complete hack.  Sigh.
    LayoutRect paintDirtyRect(paintRect);
    if (rootLayer == l) {
        paintDirtyRect.setWidth(max<LayoutUnit>(paintDirtyRect.width(), rootLayer->renderBox()->layoutOverflowRect().maxX()));
        paintDirtyRect.setHeight(max<LayoutUnit>(paintDirtyRect.height(), rootLayer->renderBox()->layoutOverflowRect().maxY()));
        l->setSize(l->size().expandedTo(pixelSnappedIntSize(l->renderBox()->maxLayoutOverflow(), LayoutPoint(0, 0))));
    }
    
    // Calculate the clip rects we should use.
    LayoutRect layerBounds;
    ClipRect damageRect, clipRectToApply, outlineRect;
    l->calculateRects(rootLayer, 0, TemporaryClipRects, paintDirtyRect, layerBounds, damageRect, clipRectToApply, outlineRect);

    // Ensure our lists are up-to-date.
    l->updateLayerListsIfNeeded();

    bool shouldPaint = (behavior & RenderAsTextShowAllLayers) ? true : l->intersectsDamageRect(layerBounds, damageRect.rect(), rootLayer);
    Vector<RenderLayer*>* negList = l->negZOrderList();
    bool paintsBackgroundSeparately = negList && negList->size() > 0;
    if (shouldPaint && paintsBackgroundSeparately)
        write(ts, *l, layerBounds, damageRect.rect(), clipRectToApply.rect(), outlineRect.rect(), LayerPaintPhaseBackground, indent, behavior);

    if (negList) {
        int currIndent = indent;
        if (behavior & RenderAsTextShowLayerNesting) {
            writeIndent(ts, indent);
            ts << " negative z-order list(" << negList->size() << ")\n";
            ++currIndent;
        }
        for (unsigned i = 0; i != negList->size(); ++i)
            writeLayers(ts, rootLayer, negList->at(i), paintDirtyRect, currIndent, behavior);
    }

    if (shouldPaint)
        write(ts, *l, layerBounds, damageRect.rect(), clipRectToApply.rect(), outlineRect.rect(), paintsBackgroundSeparately ? LayerPaintPhaseForeground : LayerPaintPhaseAll, indent, behavior);

    if (Vector<RenderLayer*>* normalFlowList = l->normalFlowList()) {
        int currIndent = indent;
        if (behavior & RenderAsTextShowLayerNesting) {
            writeIndent(ts, indent);
            ts << " normal flow list(" << normalFlowList->size() << ")\n";
            ++currIndent;
        }
        for (unsigned i = 0; i != normalFlowList->size(); ++i)
            writeLayers(ts, rootLayer, normalFlowList->at(i), paintDirtyRect, currIndent, behavior);
    }

    if (Vector<RenderLayer*>* posList = l->posZOrderList()) {
        int currIndent = indent;
        if (behavior & RenderAsTextShowLayerNesting) {
            writeIndent(ts, indent);
            ts << " positive z-order list(" << posList->size() << ")\n";
            ++currIndent;
        }
        for (unsigned i = 0; i != posList->size(); ++i)
            writeLayers(ts, rootLayer, posList->at(i), paintDirtyRect, currIndent, behavior);
    }
    
    // Altough the RenderFlowThread requires a layer, it is not collected by its parent,
    // so we have to treat it as a special case.
    if (l->renderer()->isRenderView()) {
        RenderView* renderView = toRenderView(l->renderer());
        writeRenderNamedFlowThreads(ts, renderView, rootLayer, paintDirtyRect, indent, behavior);
    }
}
Example #3
0
void LocaleWin::initializeLocalizerData()
{
    if (m_didInitializeNumberData)
        return;

    Vector<String, DecimalSymbolsSize> symbols;
    enum DigitSubstitution {
        DigitSubstitutionContext = 0,
        DigitSubstitution0to9 = 1,
        DigitSubstitutionNative = 2,
    };
    DWORD digitSubstitution = DigitSubstitution0to9;
    getLocaleInfo(LOCALE_IDIGITSUBSTITUTION, digitSubstitution);
    if (digitSubstitution == DigitSubstitution0to9) {
        symbols.append("0");
        symbols.append("1");
        symbols.append("2");
        symbols.append("3");
        symbols.append("4");
        symbols.append("5");
        symbols.append("6");
        symbols.append("7");
        symbols.append("8");
        symbols.append("9");
    } else {
        String digits = getLocaleInfoString(LOCALE_SNATIVEDIGITS);
        ASSERT(digits.length() >= 10);
        for (unsigned i = 0; i < 10; ++i)
            symbols.append(digits.substring(i, 1));
    }
    ASSERT(symbols.size() == DecimalSeparatorIndex);
    symbols.append(getLocaleInfoString(LOCALE_SDECIMAL));
    ASSERT(symbols.size() == GroupSeparatorIndex);
    symbols.append(getLocaleInfoString(LOCALE_STHOUSAND));
    ASSERT(symbols.size() == DecimalSymbolsSize);

    String negativeSign = getLocaleInfoString(LOCALE_SNEGATIVESIGN);
    enum NegativeFormat {
        NegativeFormatParenthesis = 0,
        NegativeFormatSignPrefix = 1,
        NegativeFormatSignSpacePrefix = 2,
        NegativeFormatSignSuffix = 3,
        NegativeFormatSpaceSignSuffix = 4,
    };
    DWORD negativeFormat = NegativeFormatSignPrefix;
    getLocaleInfo(LOCALE_INEGNUMBER, negativeFormat);
    String negativePrefix = emptyString();
    String negativeSuffix = emptyString();
    switch (negativeFormat) {
    case NegativeFormatParenthesis:
        negativePrefix = "(";
        negativeSuffix = ")";
        break;
    case NegativeFormatSignSpacePrefix:
        negativePrefix = negativeSign + " ";
        break;
    case NegativeFormatSignSuffix:
        negativeSuffix = negativeSign;
        break;
    case NegativeFormatSpaceSignSuffix:
        negativeSuffix = " " + negativeSign;
        break;
    case NegativeFormatSignPrefix: // Fall through.
    default:
        negativePrefix = negativeSign;
        break;
    }
    m_didInitializeNumberData = true;
    setLocalizerData(symbols, emptyString(), emptyString(), negativePrefix, negativeSuffix);
}
Example #4
0
double RootMeanSquaredError::calculate_performance(const Vector<double>& parameters) const
{
   // Control sentence (if debug)

   #ifdef __OPENNN_DEBUG__ 
   
   check();

   #endif

   #ifdef __OPENNN_DEBUG__ 

   std::ostringstream buffer;

   const size_t size = parameters.size();

   const size_t parameters_number = neural_network_pointer->count_parameters_number();

   if(size != parameters_number)
   {
      buffer << "OpenNN Exception: RootMeanSquaredError class.\n"
             << "double calculate_performance(const Vector<double>&) const method.\n"
             << "Size (" << size << ") must be equal to number of parameters (" << parameters_number << ").\n";

      throw std::logic_error(buffer.str());	  
   }

   #endif

   // Neural network stuff

   const MultilayerPerceptron* multilayer_perceptron_pointer = neural_network_pointer->get_multilayer_perceptron_pointer();

   const size_t inputs_number = multilayer_perceptron_pointer->get_inputs_number();
   const size_t outputs_number = multilayer_perceptron_pointer->get_outputs_number();

   // Data set stuff

   const Instances& instances = data_set_pointer->get_instances();

   const size_t training_instances_number = instances.count_training_instances_number();

   const Vector<size_t> training_indices = instances.arrange_training_indices();

   size_t training_index;

   const Variables& variables = data_set_pointer->get_variables();

   const Vector<size_t> inputs_indices = variables.arrange_inputs_indices();
   const Vector<size_t> targets_indices = variables.arrange_targets_indices();

   // Root mean squared error

   Vector<double> inputs(inputs_number);
   Vector<double> outputs(outputs_number);
   Vector<double> targets(outputs_number);

   double sum_squared_error = 0.0;

   int i = 0;

   #pragma omp parallel for private(i, training_index, inputs, outputs, targets) reduction(+:sum_squared_error)

   for(i = 0; i < (int)training_instances_number; i++)
   {
       training_index = training_indices[i];

      // Input vector

      inputs = data_set_pointer->get_instance(training_index, inputs_indices);

      // Output vector

      outputs = multilayer_perceptron_pointer->calculate_outputs(inputs, parameters);

      // Target vector

      targets = data_set_pointer->get_instance(training_index, targets_indices);

      // Sum squaresd error

      sum_squared_error += outputs.calculate_sum_squared_error(targets);
   }

   return(sqrt(sum_squared_error/(double)training_instances_number));
}
Example #5
0
void TextureMapperLayer::setChildren(const Vector<TextureMapperLayer*>& newChildren)
{
    removeAllChildren();
    for (size_t i = 0; i < newChildren.size(); ++i)
        addChild(newChildren[i]);
}
Example #6
0
// The spawnDelay mechansim is complex and interacts with other weird things like levelUp messages and server suspension
TEST(SpawnDelayTest, SpawnDelayTests)
{
   GamePair gamePair;     // An empty level should work fine here
   ClientGame *clientGame = gamePair.getClient(0);
   ServerGame *serverGame = gamePair.server;

   ASSERT_TRUE(serverGame->getGameType()) << "Expect a GameType by now!";

   // Idle for a while, let things settle
   gamePair.idle(10, 5);

   ASSERT_TRUE(clientGame->getGameType()) << "Expect a GameType by now!";

   Vector<DatabaseObject *> fillVector;

   // Ship should have spawned by now... check for it on the client and server
   fillVector.clear();
   serverGame->getLevel()->findObjects(PlayerShipTypeNumber, fillVector);
   ASSERT_EQ(1, fillVector.size());    // Ship should have spawned by now

   Ship *ship = static_cast<Ship *>(fillVector[0]);      // Server's copy of the ship

   fillVector.clear();
   clientGame->getLevel()->findObjects(PlayerShipTypeNumber, fillVector);
   ASSERT_EQ(1, fillVector.size());    // And it should be on the client, too

   ASSERT_FALSE(clientGame->isSpawnDelayed());     // Should not be spawn-delayed at this point

   killShip(ship);

   gamePair.idle(10, 5);      // 5 cycles

   // Ship should have spawned by now... check for it on the client and server
   fillVector.clear();
   serverGame->getLevel()->findObjects(PlayerShipTypeNumber, fillVector);
   ASSERT_EQ(1, fillVector.size());    //  Ship should have respawned and be available on the server...
   fillVector.clear();
   clientGame->getLevel()->findObjects(PlayerShipTypeNumber, fillVector);
   ASSERT_EQ(1, fillVector.size());    // ...and also on the client

   // Scenario 1: Player is idle and gets spawn delayed -- no other players in game
   // TODO: Also need a scenario where palyer goes idle and gets spawn delayed, but game does not get suspended due to other players
   doScenario1(gamePair);

   // Scenario 2: Player enters idle command, other players, so server does not suspend itself.  Since
   // player used idle command, a 5 second penalty will be levied against them.
   doScenario2(gamePair);

   // Scenarios 3 & 4 -- Player enters /idle command, no other players, so server suspends itself partially (3) or fully (4)
   // See https://code.google.com/p/googletest/wiki/AdvancedGuide#Using_Assertions_in_Sub-routines for details on this technique
   {
      SCOPED_TRACE("Scenario 3, letGameSlipIntoFullSuspendMode is false");
      doScenario34(gamePair, false);
   }
   {
      SCOPED_TRACE("Scenario 4, letGameSlipIntoFullSuspendMode is true");
      doScenario34(gamePair, true);
   }

   // Scenario 5 -- Player enters idle when in punishment delay period for pervious /idle command
   doScenario5(gamePair);  // Not complete

   // Scenario 6 -- Player is shown a new levelup screen
   doScenario6(gamePair);  // Not complete

   // Scenario 7 -- Player is shown a levelup screen they have already seen
   doScenario7(gamePair);  // Not complete

   // Scenario 8 -- Player is shown (new) levelup screen while they are idle due to inaction

   // Scenario 9 -- Player is shown (new) levelup screen while they are idle due to idle command

   // Scenario 10 -- Player is shown (new) levelup screen while they are in penalty phase of idle command

   // Scenario 11 -- Player is changing their loadout when the level changes.  This triggers a delayed spawn.
   doScenario11(gamePair);
}
Example #7
0
void PluginDatabase::loadPersistentMetadataCache()
{
    if (!isPersistentMetadataCacheEnabled() || persistentMetadataCachePath().isEmpty())
        return;

    PlatformFileHandle file;
    String absoluteCachePath = pathByAppendingComponent(persistentMetadataCachePath(), persistentPluginMetadataCacheFilename);
    file = openFile(absoluteCachePath, OpenForRead);

    if (!isHandleValid(file))
        return;

    // Mark cache as loaded regardless of success or failure. If
    // there's error in the cache, we won't try to load it anymore.
    m_persistentMetadataCacheIsLoaded = true;

    Vector<char> fileContents;
    fillBufferWithContentsOfFile(file, fileContents);
    closeFile(file);

    if (fileContents.size() < 2 || fileContents.first() != schemaVersion || fileContents.last() != '\0') {
        LOG_ERROR("Unable to read plugin metadata cache: corrupt schema");
        deleteFile(absoluteCachePath);
        return;
    }

    char* bufferPos = fileContents.data() + 1;
    char* end = fileContents.data() + fileContents.size();

    PluginSet cachedPlugins;
    HashMap<String, time_t> cachedPluginPathsWithTimes;
    HashMap<String, RefPtr<PluginPackage> > cachedPluginsByPath;

    while (bufferPos < end) {
        String path;
        time_t lastModified;
        String name;
        String desc;
        String mimeDesc;
        if (!(readUTF8String(path, bufferPos, end)
              && readTime(lastModified, bufferPos, end)
              && readUTF8String(name, bufferPos, end)
              && readUTF8String(desc, bufferPos, end)
              && readUTF8String(mimeDesc, bufferPos, end))) {
            LOG_ERROR("Unable to read plugin metadata cache: corrupt data");
            deleteFile(absoluteCachePath);
            return;
        }

        // Skip metadata that points to plugins from directories that
        // are not part of plugin directory list anymore.
        String pluginDirectoryName = directoryName(path);
        if (m_pluginDirectories.find(pluginDirectoryName) == WTF::notFound)
            continue;

        RefPtr<PluginPackage> package = PluginPackage::createPackageFromCache(path, lastModified, name, desc, mimeDesc);

        if (package && cachedPlugins.add(package).isNewEntry) {
            cachedPluginPathsWithTimes.add(package->path(), package->lastModified());
            cachedPluginsByPath.add(package->path(), package);
        }
    }

    m_plugins.swap(cachedPlugins);
    m_pluginsByPath.swap(cachedPluginsByPath);
    m_pluginPathsWithTimes.swap(cachedPluginPathsWithTimes);
}
Example #8
0
static void _disassemble_class(const Ref<GDScript> &p_class, const Vector<String> &p_code) {

	const Map<StringName, GDScriptFunction *> &mf = p_class->debug_get_member_functions();

	for (const Map<StringName, GDScriptFunction *>::Element *E = mf.front(); E; E = E->next()) {

		const GDScriptFunction &func = *E->get();
		const int *code = func.get_code();
		int codelen = func.get_code_size();
		String defargs;
		if (func.get_default_argument_count()) {
			defargs = "defarg at: ";
			for (int i = 0; i < func.get_default_argument_count(); i++) {

				if (i > 0)
					defargs += ",";
				defargs += itos(func.get_default_argument_addr(i));
			}
			defargs += " ";
		}
		print_line("== function " + String(func.get_name()) + "() :: stack size: " + itos(func.get_max_stack_size()) + " " + defargs + "==");

#define DADDR(m_ip) (_disassemble_addr(p_class, func, code[ip + m_ip]))

		for (int ip = 0; ip < codelen;) {

			int incr = 0;
			String txt = itos(ip) + " ";

			switch (code[ip]) {

				case GDScriptFunction::OPCODE_OPERATOR: {

					int op = code[ip + 1];
					txt += "op ";

					String opname = Variant::get_operator_name(Variant::Operator(op));

					txt += DADDR(4);
					txt += " = ";
					txt += DADDR(2);
					txt += " " + opname + " ";
					txt += DADDR(3);
					incr += 5;

				} break;
				case GDScriptFunction::OPCODE_SET: {

					txt += "set ";
					txt += DADDR(1);
					txt += "[";
					txt += DADDR(2);
					txt += "]=";
					txt += DADDR(3);
					incr += 4;

				} break;
				case GDScriptFunction::OPCODE_GET: {

					txt += " get ";
					txt += DADDR(3);
					txt += "=";
					txt += DADDR(1);
					txt += "[";
					txt += DADDR(2);
					txt += "]";
					incr += 4;

				} break;
				case GDScriptFunction::OPCODE_SET_NAMED: {

					txt += " set_named ";
					txt += DADDR(1);
					txt += "[\"";
					txt += func.get_global_name(code[ip + 2]);
					txt += "\"]=";
					txt += DADDR(3);
					incr += 4;

				} break;
				case GDScriptFunction::OPCODE_GET_NAMED: {

					txt += " get_named ";
					txt += DADDR(3);
					txt += "=";
					txt += DADDR(1);
					txt += "[\"";
					txt += func.get_global_name(code[ip + 2]);
					txt += "\"]";
					incr += 4;

				} break;
				case GDScriptFunction::OPCODE_SET_MEMBER: {

					txt += " set_member ";
					txt += "[\"";
					txt += func.get_global_name(code[ip + 1]);
					txt += "\"]=";
					txt += DADDR(2);
					incr += 3;

				} break;
				case GDScriptFunction::OPCODE_GET_MEMBER: {

					txt += " get_member ";
					txt += DADDR(2);
					txt += "=";
					txt += "[\"";
					txt += func.get_global_name(code[ip + 1]);
					txt += "\"]";
					incr += 3;

				} break;
				case GDScriptFunction::OPCODE_ASSIGN: {

					txt += " assign ";
					txt += DADDR(1);
					txt += "=";
					txt += DADDR(2);
					incr += 3;

				} break;
				case GDScriptFunction::OPCODE_ASSIGN_TRUE: {

					txt += " assign ";
					txt += DADDR(1);
					txt += "= true";
					incr += 2;

				} break;
				case GDScriptFunction::OPCODE_ASSIGN_FALSE: {

					txt += " assign ";
					txt += DADDR(1);
					txt += "= false";
					incr += 2;

				} break;
				case GDScriptFunction::OPCODE_CONSTRUCT: {

					Variant::Type t = Variant::Type(code[ip + 1]);
					int argc = code[ip + 2];

					txt += " construct ";
					txt += DADDR(3 + argc);
					txt += " = ";

					txt += Variant::get_type_name(t) + "(";
					for (int i = 0; i < argc; i++) {

						if (i > 0)
							txt += ", ";
						txt += DADDR(i + 3);
					}
					txt += ")";

					incr = 4 + argc;

				} break;
				case GDScriptFunction::OPCODE_CONSTRUCT_ARRAY: {

					int argc = code[ip + 1];
					txt += " make_array ";
					txt += DADDR(2 + argc);
					txt += " = [ ";

					for (int i = 0; i < argc; i++) {
						if (i > 0)
							txt += ", ";
						txt += DADDR(2 + i);
					}

					txt += "]";

					incr += 3 + argc;

				} break;
				case GDScriptFunction::OPCODE_CONSTRUCT_DICTIONARY: {

					int argc = code[ip + 1];
					txt += " make_dict ";
					txt += DADDR(2 + argc * 2);
					txt += " = { ";

					for (int i = 0; i < argc; i++) {
						if (i > 0)
							txt += ", ";
						txt += DADDR(2 + i * 2 + 0);
						txt += ":";
						txt += DADDR(2 + i * 2 + 1);
					}

					txt += "}";

					incr += 3 + argc * 2;

				} break;

				case GDScriptFunction::OPCODE_CALL:
				case GDScriptFunction::OPCODE_CALL_RETURN: {

					bool ret = code[ip] == GDScriptFunction::OPCODE_CALL_RETURN;

					if (ret)
						txt += " call-ret ";
					else
						txt += " call ";

					int argc = code[ip + 1];
					if (ret) {
						txt += DADDR(4 + argc) + "=";
					}

					txt += DADDR(2) + ".";
					txt += String(func.get_global_name(code[ip + 3]));
					txt += "(";

					for (int i = 0; i < argc; i++) {
						if (i > 0)
							txt += ", ";
						txt += DADDR(4 + i);
					}
					txt += ")";

					incr = 5 + argc;

				} break;
				case GDScriptFunction::OPCODE_CALL_BUILT_IN: {

					txt += " call-built-in ";

					int argc = code[ip + 2];
					txt += DADDR(3 + argc) + "=";

					txt += GDScriptFunctions::get_func_name(GDScriptFunctions::Function(code[ip + 1]));
					txt += "(";

					for (int i = 0; i < argc; i++) {
						if (i > 0)
							txt += ", ";
						txt += DADDR(3 + i);
					}
					txt += ")";

					incr = 4 + argc;

				} break;
				case GDScriptFunction::OPCODE_CALL_SELF_BASE: {

					txt += " call-self-base ";

					int argc = code[ip + 2];
					txt += DADDR(3 + argc) + "=";

					txt += func.get_global_name(code[ip + 1]);
					txt += "(";

					for (int i = 0; i < argc; i++) {
						if (i > 0)
							txt += ", ";
						txt += DADDR(3 + i);
					}
					txt += ")";

					incr = 4 + argc;

				} break;
				case GDScriptFunction::OPCODE_YIELD: {

					txt += " yield ";
					incr = 1;

				} break;
				case GDScriptFunction::OPCODE_YIELD_SIGNAL: {

					txt += " yield_signal ";
					txt += DADDR(1);
					txt += ",";
					txt += DADDR(2);
					incr = 3;
				} break;
				case GDScriptFunction::OPCODE_YIELD_RESUME: {

					txt += " yield resume: ";
					txt += DADDR(1);
					incr = 2;
				} break;
				case GDScriptFunction::OPCODE_JUMP: {

					txt += " jump ";
					txt += itos(code[ip + 1]);

					incr = 2;

				} break;
				case GDScriptFunction::OPCODE_JUMP_IF: {

					txt += " jump-if ";
					txt += DADDR(1);
					txt += " to ";
					txt += itos(code[ip + 2]);

					incr = 3;
				} break;
				case GDScriptFunction::OPCODE_JUMP_IF_NOT: {

					txt += " jump-if-not ";
					txt += DADDR(1);
					txt += " to ";
					txt += itos(code[ip + 2]);

					incr = 3;
				} break;
				case GDScriptFunction::OPCODE_JUMP_TO_DEF_ARGUMENT: {

					txt += " jump-to-default-argument ";
					incr = 1;
				} break;
				case GDScriptFunction::OPCODE_RETURN: {

					txt += " return ";
					txt += DADDR(1);

					incr = 2;

				} break;
				case GDScriptFunction::OPCODE_ITERATE_BEGIN: {

					txt += " for-init " + DADDR(4) + " in " + DADDR(2) + " counter " + DADDR(1) + " end " + itos(code[ip + 3]);
					incr += 5;

				} break;
				case GDScriptFunction::OPCODE_ITERATE: {

					txt += " for-loop " + DADDR(4) + " in " + DADDR(2) + " counter " + DADDR(1) + " end " + itos(code[ip + 3]);
					incr += 5;

				} break;
				case GDScriptFunction::OPCODE_LINE: {

					int line = code[ip + 1] - 1;
					if (line >= 0 && line < p_code.size())
						txt = "\n" + itos(line + 1) + ": " + p_code[line] + "\n";
					else
						txt = "";
					incr += 2;
				} break;
				case GDScriptFunction::OPCODE_END: {

					txt += " end";
					incr += 1;
				} break;
				case GDScriptFunction::OPCODE_ASSERT: {

					txt += " assert ";
					txt += DADDR(1);
					incr += 2;

				} break;
			}

			if (incr == 0) {

				ERR_EXPLAIN("unhandled opcode: " + itos(code[ip]));
				ERR_BREAK(incr == 0);
			}

			ip += incr;
			if (txt != "")
				print_line(txt);
		}
	}
}
Example #9
0
MainLoop *test(TestType p_type) {

	List<String> cmdlargs = OS::get_singleton()->get_cmdline_args();

	if (cmdlargs.empty()) {
		//try editor!
		return NULL;
	}

	String test = cmdlargs.back()->get();

	FileAccess *fa = FileAccess::open(test, FileAccess::READ);

	if (!fa) {
		ERR_EXPLAIN("Could not open file: " + test);
		ERR_FAIL_V(NULL);
	}

	Vector<uint8_t> buf;
	int flen = fa->get_len();
	buf.resize(fa->get_len() + 1);
	fa->get_buffer(&buf[0], flen);
	buf[flen] = 0;

	String code;
	code.parse_utf8((const char *)&buf[0]);

	Vector<String> lines;
	int last = 0;

	for (int i = 0; i <= code.length(); i++) {

		if (code[i] == '\n' || code[i] == 0) {

			lines.push_back(code.substr(last, i - last));
			last = i + 1;
		}
	}

	if (p_type == TEST_TOKENIZER) {

		GDScriptTokenizerText tk;
		tk.set_code(code);
		int line = -1;
		while (tk.get_token() != GDScriptTokenizer::TK_EOF) {

			String text;
			if (tk.get_token() == GDScriptTokenizer::TK_IDENTIFIER)
				text = "'" + tk.get_token_identifier() + "' (identifier)";
			else if (tk.get_token() == GDScriptTokenizer::TK_CONSTANT) {
				Variant c = tk.get_token_constant();
				if (c.get_type() == Variant::STRING)
					text = "\"" + String(c) + "\"";
				else
					text = c;

				text = text + " (" + Variant::get_type_name(c.get_type()) + " constant)";
			} else if (tk.get_token() == GDScriptTokenizer::TK_ERROR)
				text = "ERROR: " + tk.get_token_error();
			else if (tk.get_token() == GDScriptTokenizer::TK_NEWLINE)
				text = "newline (" + itos(tk.get_token_line()) + ") + indent: " + itos(tk.get_token_line_indent());
			else if (tk.get_token() == GDScriptTokenizer::TK_BUILT_IN_FUNC)
				text = "'" + String(GDScriptFunctions::get_func_name(tk.get_token_built_in_func())) + "' (built-in function)";
			else
				text = tk.get_token_name(tk.get_token());

			if (tk.get_token_line() != line) {
				int from = line + 1;
				line = tk.get_token_line();

				for (int i = from; i <= line; i++) {
					int l = i - 1;
					if (l >= 0 && l < lines.size()) {
						print_line("\n" + itos(i) + ": " + lines[l] + "\n");
					}
				}
			}
			print_line("\t(" + itos(tk.get_token_column()) + "): " + text);
			tk.advance();
		}
	}

	if (p_type == TEST_PARSER) {

		GDScriptParser parser;
		Error err = parser.parse(code);
		if (err) {
			print_line("Parse Error:\n" + itos(parser.get_error_line()) + ":" + itos(parser.get_error_column()) + ":" + parser.get_error());
			memdelete(fa);
			return NULL;
		}

		const GDScriptParser::Node *root = parser.get_parse_tree();
		ERR_FAIL_COND_V(root->type != GDScriptParser::Node::TYPE_CLASS, NULL);
		const GDScriptParser::ClassNode *cnode = static_cast<const GDScriptParser::ClassNode *>(root);

		_parser_show_class(cnode, 0, lines);
	}

	if (p_type == TEST_COMPILER) {

		GDScriptParser parser;

		Error err = parser.parse(code);
		if (err) {
			print_line("Parse Error:\n" + itos(parser.get_error_line()) + ":" + itos(parser.get_error_column()) + ":" + parser.get_error());
			memdelete(fa);
			return NULL;
		}

		GDScript *script = memnew(GDScript);

		GDScriptCompiler gdc;
		err = gdc.compile(&parser, script);
		if (err) {

			print_line("Compile Error:\n" + itos(gdc.get_error_line()) + ":" + itos(gdc.get_error_column()) + ":" + gdc.get_error());
			memdelete(script);
			return NULL;
		}

		Ref<GDScript> gds = Ref<GDScript>(script);

		Ref<GDScript> current = gds;

		while (current.is_valid()) {

			print_line("** CLASS **");
			_disassemble_class(current, lines);

			current = current->get_base();
		}

	} else if (p_type == TEST_BYTECODE) {

		Vector<uint8_t> buf = GDScriptTokenizerBuffer::parse_code_string(code);
		String dst = test.get_basename() + ".gdc";
		FileAccess *fw = FileAccess::open(dst, FileAccess::WRITE);
		fw->store_buffer(buf.ptr(), buf.size());
		memdelete(fw);
	}

	memdelete(fa);

	return NULL;
}
Example #10
0
void ScriptEditorDebugger::_performance_draw() {


	Vector<int> which;
	for(int i=0;i<perf_items.size();i++) {


		if (perf_items[i]->is_selected(0))
			which.push_back(i);
	}


	if(which.empty())
		return;

	Color graph_color=get_color("font_color","TextEdit");
	Ref<StyleBox> graph_sb = get_stylebox("normal","TextEdit");
	Ref<Font> graph_font = get_font("font","TextEdit");

	int cols = Math::ceil(Math::sqrt(which.size()));
	int rows = (which.size()+1)/cols;
	if (which.size()==1)
		rows=1;


	int margin =3;
	int point_sep=5;
	Size2i s = Size2i(perf_draw->get_size())/Size2i(cols,rows);
	for(int i=0;i<which.size();i++) {

		Point2i p(i%cols,i/cols);
		Rect2i r(p*s,s);
		r.pos+=Point2(margin,margin);
		r.size-=Point2(margin,margin)*2.0;
		perf_draw->draw_style_box(graph_sb,r);
		r.pos+=graph_sb->get_offset();
		r.size-=graph_sb->get_minimum_size();
		int pi=which[i];
		Color c = Color(0.7,0.9,0.5);
		c.set_hsv(Math::fmod(c.get_h()+pi*0.7654,1),c.get_s(),c.get_v());

		c.a=0.8;
		perf_draw->draw_string(graph_font,r.pos+Point2(0,graph_font->get_ascent()),perf_items[pi]->get_text(0),c,r.size.x);
		c.a=0.6;
		perf_draw->draw_string(graph_font,r.pos+Point2(graph_font->get_char_size('X').width,graph_font->get_ascent()+graph_font->get_height()),perf_items[pi]->get_text(1),c,r.size.y);

		float spacing=point_sep/float(cols);
		float from = r.size.width;

		List<Vector<float> >::Element *E=perf_history.front();
		float prev=-1;
		while(from>=0 && E) {

			float m = perf_max[pi];
			if (m==0)
				m=0.00001;
			float h = E->get()[pi]/m;
			h=(1.0-h)*r.size.y;

			c.a=0.7;
			if (E!=perf_history.front())
				perf_draw->draw_line(r.pos+Point2(from,h),r.pos+Point2(from+spacing,prev),c,2.0);
			prev=h;
			E=E->next();
			from-=spacing;
		}

	}

}
Example #11
0
 void RowObserver::operator()(const Vector &v) {
   assert(v.size() == m.ncol());
   m = mp->value();
   std::copy(v.begin(), v.end(), m.row_begin(i));
   mp->set(m, false);
 }
void HTMLViewSourceDocument::addViewSourceToken(Token* token)
{
    if (!m_current)
        createContainingTable();

    if (token->tagName == textAtom)
        addText(token->text.get(), "");
    else if (token->tagName == commentAtom) {
        if (token->beginTag) {
            m_current = addSpanWithClassName("webkit-html-comment");
            addText(String("<!--") + token->text.get() + "-->", "webkit-html-comment");
        }
    } else {
        // Handle the tag.
        String classNameStr = "webkit-html-tag";
        m_current = addSpanWithClassName(classNameStr);

        String text = "<";
        if (!token->beginTag)
            text += "/";
        text += token->tagName;
        Vector<UChar>* guide = token->m_sourceInfo.get();
        if (!guide || !guide->size())
            text += ">";

        addText(text, classNameStr);

        // Walk our guide string that tells us where attribute names/values should go.
        if (guide && guide->size()) {
            unsigned size = guide->size();
            unsigned begin = 0;
            unsigned currAttr = 0;
            RefPtr<Attribute> attr = 0;
            for (unsigned i = 0; i < size; i++) {
                if (guide->at(i) == 'a' || guide->at(i) == 'x' || guide->at(i) == 'v') {
                    // Add in the string.
                    addText(String(static_cast<UChar*>(guide->data()) + begin, i - begin), classNameStr);
                     
                    begin = i + 1;

                    if (guide->at(i) == 'a') {
                        if (token->attrs && currAttr < token->attrs->length())
                            attr = token->attrs->attributeItem(currAttr++);
                        else
                            attr = 0;
                    }
                    if (attr) {
                        if (guide->at(i) == 'a') {
                            String name = attr->name().toString();
                            
                            m_current = addSpanWithClassName("webkit-html-attribute-name");
                            addText(name, "webkit-html-attribute-name");
                            if (m_current != m_tbody)
                                m_current = static_cast<Element*>(m_current->parent());
                        } else {
                            const String& value = attr->value().string();

                            // Compare ignoring case since HTMLDocumentParser doesn't
                            // lower names when passing in tokens to
                            // HTMLViewSourceDocument.
                            if (equalIgnoringCase(token->tagName, "base") && equalIgnoringCase(attr->name().localName(), "href")) {
                                // Catch the href attribute in the base element.
                                // It will be used for rendering anchors created
                                // by addLink() below.
                                setBaseElementURL(KURL(url(), value));
                            }

                            // FIXME: XML could use namespace prefixes and confuse us.
                            if (equalIgnoringCase(attr->name().localName(), "src") || equalIgnoringCase(attr->name().localName(), "href"))
                                m_current = addLink(value, equalIgnoringCase(token->tagName, "a"));
                            else
                                m_current = addSpanWithClassName("webkit-html-attribute-value");
                            addText(value, "webkit-html-attribute-value");
                            if (m_current != m_tbody)
                                m_current = static_cast<Element*>(m_current->parent());
                        }
                    }
                }
            }
            
            // Add in any string that might be left.
            if (begin < size)
                addText(String(static_cast<UChar*>(guide->data()) + begin, size - begin), classNameStr);

            // Add in the end tag.
            addText(">", classNameStr);
        }
        
        m_current = m_td;
    }
}
Example #13
0
bool parse(const String8& str, ConfigDescription* out) {
    Vector<String8> parts = AaptUtil::splitAndLowerCase(str, '-');

    ConfigDescription config;
    AaptLocaleValue locale;
    ssize_t index = 0;
    ssize_t localeIndex = 0;
    const ssize_t N = parts.size();
    const char* part = parts[index].string();

    if (str.length() == 0) {
        goto success;
    }

    if (parseMcc(part, &config)) {
        index++;
        if (index == N) {
            goto success;
        }
        part = parts[index].string();
    }

    if (parseMnc(part, &config)) {
        index++;
        if (index == N) {
            goto success;
        }
        part = parts[index].string();
    }

    // Locale spans a few '-' separators, so we let it
    // control the index.
    localeIndex = locale.initFromDirName(parts, index);
    if (localeIndex < 0) {
        return false;
    } else if (localeIndex > index) {
        locale.writeTo(&config);
        index = localeIndex;
        if (index >= N) {
            goto success;
        }
        part = parts[index].string();
    }

    if (parseLayoutDirection(part, &config)) {
        index++;
        if (index == N) {
            goto success;
        }
        part = parts[index].string();
    }

    if (parseSmallestScreenWidthDp(part, &config)) {
        index++;
        if (index == N) {
            goto success;
        }
        part = parts[index].string();
    }

    if (parseScreenWidthDp(part, &config)) {
        index++;
        if (index == N) {
            goto success;
        }
        part = parts[index].string();
    }

    if (parseScreenHeightDp(part, &config)) {
        index++;
        if (index == N) {
            goto success;
        }
        part = parts[index].string();
    }

    if (parseScreenLayoutSize(part, &config)) {
        index++;
        if (index == N) {
            goto success;
        }
        part = parts[index].string();
    }

    if (parseScreenLayoutLong(part, &config)) {
        index++;
        if (index == N) {
            goto success;
        }
        part = parts[index].string();
    }

    if (parseOrientation(part, &config)) {
        index++;
        if (index == N) {
            goto success;
        }
        part = parts[index].string();
    }

    if (parseUiModeType(part, &config)) {
        index++;
        if (index == N) {
            goto success;
        }
        part = parts[index].string();
    }

    if (parseUiModeNight(part, &config)) {
        index++;
        if (index == N) {
            goto success;
        }
        part = parts[index].string();
    }

    if (parseDensity(part, &config)) {
        index++;
        if (index == N) {
            goto success;
        }
        part = parts[index].string();
    }

    if (parseTouchscreen(part, &config)) {
        index++;
        if (index == N) {
            goto success;
        }
        part = parts[index].string();
    }

    if (parseKeysHidden(part, &config)) {
        index++;
        if (index == N) {
            goto success;
        }
        part = parts[index].string();
    }

    if (parseKeyboard(part, &config)) {
        index++;
        if (index == N) {
            goto success;
        }
        part = parts[index].string();
    }

    if (parseNavHidden(part, &config)) {
        index++;
        if (index == N) {
            goto success;
        }
        part = parts[index].string();
    }

    if (parseNavigation(part, &config)) {
        index++;
        if (index == N) {
            goto success;
        }
        part = parts[index].string();
    }

    if (parseScreenSize(part, &config)) {
        index++;
        if (index == N) {
            goto success;
        }
        part = parts[index].string();
    }

    if (parseVersion(part, &config)) {
        index++;
        if (index == N) {
            goto success;
        }
        part = parts[index].string();
    }

    // Unrecognized.
    return false;

success:
    if (out != NULL) {
#ifndef HAVE_ANDROID_OS
        applyVersionForCompatibility(&config);
#else
        // Calling applyVersionForCompatibility when compiling a theme can cause
        // the path to be changed by AAPT which results in the themed assets not being
        // loaded.  The only time (as of right now) that aapt is run on an android device
        // is when it is being used for themes, so this should be the correct behavior
        // in this case.  If AAPT is ever used on an android device for some other reason,
        // we will need to change this.
        printf("AAPT is running on Android, skipping applyVersionForCompatibility");
#endif
        *out = config;
    }

    return true;
}
Example #14
0
static bool runWithScripts(GlobalObject* globalObject, const Vector<Script>& scripts, bool dump)
{
    UString script;
    UString fileName;
    Vector<char> scriptBuffer;

    if (dump)
        BytecodeGenerator::setDumpsGeneratedCode(true);

#if ENABLE(OPCODE_SAMPLING)
    Interpreter* interpreter = globalObject->globalData()->interpreter;
    interpreter->setSampler(new SamplingTool(interpreter));
    interpreter->sampler()->setup();
#endif
#if ENABLE(SAMPLING_FLAGS)
    SamplingFlags::start();
#endif

    bool success = true;
    for (size_t i = 0; i < scripts.size(); i++) {
        if (scripts[i].isFile) {
            fileName = scripts[i].argument;
            if (!fillBufferWithContentsOfFile(fileName, scriptBuffer))
                return false; // fail early so we can catch missing files
            script = scriptBuffer.data();
        } else {
            script = scripts[i].argument;
            fileName = "[Command Line]";
        }

#if ENABLE(SAMPLING_THREAD)
        SamplingThread::start();
#endif

        Completion completion = evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), makeSource(script, fileName));
        success = success && completion.complType() != Throw;
        if (dump) {
            if (completion.complType() == Throw)
                printf("Exception: %s\n", completion.value().toString(globalObject->globalExec()).ascii());
            else
                printf("End: %s\n", completion.value().toString(globalObject->globalExec()).ascii());
        }

#if ENABLE(SAMPLING_THREAD)
        SamplingThread::stop();
#endif

        globalObject->globalExec()->clearException();
    }

#if ENABLE(SAMPLING_FLAGS)
    SamplingFlags::stop();
#endif
#if ENABLE(OPCODE_SAMPLING)
    interpreter->sampler()->dump(globalObject->globalExec());
    delete interpreter->sampler();
#endif
#if ENABLE(SAMPLING_COUNTERS)
    AbstractSamplingCounter::dump();
#endif
    return success;
}
Example #15
0
File: parse_op.cpp Project: 8l/zl
 const Syntax * parse(const Syntax * p, const char * l_i) {
   //printf("ParseExpImpl::parse: %s %s\n", ~p->sample_w_loc(), ~p->to_string());
   opr_s.clear();
   val_s.clear();
   list_is = l_i;
   Op::Types prev = 0;
   try {
     for (parts_iterator i = p->args_begin(), e = p->args_end(); i != e; ++i) {
       const Syntax * pop = *i; // parsed op
       Op::Types cur = ops.lookup_types(pop);
       if (cur & Op::Special) {
         const Syntax * res = ops.try_special(pop, i, e);
         if (res) {
           pop = res;
           cur = ops.lookup_types(pop);
         } else {
           cur &= ~Op::Special;
         }
       } 
       assert(!(cur & Op::Special));
       if (prev == 0 || prev & (Op::Prefix | Op::Bin)) {
         cur &= (Op::Prefix | Op::Other);
         if (cur == 0) 
           throw error(pop, "Expected an operand or a prefix operator.");
       } else {
         cur &= (Op::Bin | Op::Postfix);
         if (cur == 0) 
           throw error(pop, "Expected a binary or postfix operator.");
       }
       //if (cur == (Op::Prefix | Op::Other)) {
       //  if (i + 1 == sz || (ops.lookup_types(p->arg(i+1)) & (Op::Postfix | Op::Bin))) {
       //    cur &= (Op::Postfix | Op::Other);
       //    if (cur == 0)
       //      throw error(pop, "Expected an operand or a postfix operator.");
       //  } else {
       //    cur &= (Op::Bin | Op::Prefix);
       //    if (cur == 0)
       //      throw error(pop, "Expected an binary or prefix operator.");
       //  }
       //}
       const Op * op = ops.lookup(pop, cur);
       
       if (op->type == Op::Other) {
         val_s.push_back(pop);
       } else {
         while (!opr_s.empty() && 
                (opr_s.back().op->level < op->level || 
                 (opr_s.back().op->level == op->level && op->assoc == Left)))
           reduce();
         if (!opr_s.empty() && opr_s.back().op->level == op->level && op->assoc == None)
           throw error(pop, "\"%s\" is non-associative.", 
                       op->what.c_str());
         opr_s.push_back(OpInfo(op, pop)); 
       }
       prev = cur;
     }
     while (!opr_s.empty())
       reduce();
     if (val_s.size() == 0)
       throw error(p, "Empty expression.");
     if (val_s.size() > 1)
       throw error(val_s[val_s.size()-2], "Extra operand(s).");
     assert(val_s.size() == 1);
     Syntax * res = val_s.front();
     if (!res->is_a("syntax") && !res->is_a("raw_syntax"))
       res->str_ = p->str();
     return res;
   } catch (Error * err) {
     //printf("?? %s %s\n", ~p->sample_w_loc(), ~p->to_string());
     //abort();
     err->msg.span.source = p->str().source;
     err->add_note(extra_parse_info(p->str(), "<op exp>"));
     throw err;
   }
 }
bool PlatformCertificateInfo::decode(CoreIPC::ArgumentDecoder* decoder, PlatformCertificateInfo& c)
{
    uint64_t length;
    if (!decoder->decode(length))
        return false;

    if (length == std::numeric_limits<uint64_t>::max()) {
        // This is the no certificates case.
        return true;
    }

    for (size_t i = 0; i < length; ++i) {
        Vector<uint8_t> bytes;
        if (!decoder->decodeBytes(bytes)) {
            c.clearCertificateChain();
            return false;
        }

        PCCERT_CONTEXT certificateContext = ::CertCreateCertificateContext(PKCS_7_ASN_ENCODING | X509_ASN_ENCODING, bytes.data(), bytes.size());
        if (!certificateContext) {
            c.clearCertificateChain();
            return false;
        }
        
        c.m_certificateChain.append(certificateContext);
    }

    return true;
}
Example #17
0
File: parse_op.cpp Project: 8l/zl
 void reduce() {
   const OpInfo & opi = opr_s.back();
   const Op * op = opi.op;
   SyntaxBuilder res;
   if (op->name == "<list>")
     res.add_part(SYN(list_is));
   else
     res.add_part(op->parse);
   SourceStr str = opi.parse->str(); // FIXME: Is this right
   if (op->assoc == List) {
     if (val_s.size() < 2)
       throw error(opi.parse, "\"%s\" operator needs 2 operands.",
                   op->what.c_str());
     int num = 1;
     while (!opr_s.empty() && opr_s.back().op->level == op->level) {
       ++num; 
       opr_s.pop_back();
     }
     // FIXME: This isn't right when the parts of the list are not
     // from the same file
     str.begin = val_s[val_s.size() - num]->str().begin;
     str.end = val_s.back()->str().end;
     for (int i = val_s.size() - num; i != val_s.size(); ++i)
       res.add_part(val_s[i]);
     val_s.resize(val_s.size() - num);
   } else if (op->type == Op::Bin) {
     if (val_s.size() < 2)
       throw error(opi.parse, "\"%s\" operator needs 2 operands.",
                   op->what.c_str());
     const Syntax * p2 = val_s.back(); val_s.pop_back();
     const Syntax * p1 = val_s.back(); val_s.pop_back();
     str = opi.parse->str();
     if (p1->str().block() == str.block())
       str.begin = p1->str().begin;
     if (p2->str().block() == str.block())
       str.end   = p2->str().end;
     res.add_part(p1);
     if (op->capture_op_itself()) res.add_part(opi.parse);
     res.add_part(p2);
     opr_s.pop_back();
   } else {
     if (val_s.size() < 1)
       throw error(opi.parse, "\"%s\" operator needs an operand.",
                   op->what.c_str());
     const Syntax * p1 = val_s.back(); val_s.pop_back();
     if (op->type == Op::Prefix) {
       str = opi.parse->str();
       if (p1->str().block() == str.block())
         str.end = p1->str().end;
       if (op->capture_op_itself())
         res.add_part(opi.parse);
       res.add_part(p1);
     } else if (op->type == Op::Postfix) {
       str = opi.parse->str();
       if (p1->str().block() == str.block())
         str.begin = p1->str().begin;
       res.add_part(p1);
       if (op->capture_op_itself())
         res.add_part(opi.parse);
     } 
     opr_s.pop_back();
   }
   val_s.push_back(res.build(str));
 }
void PrintVectorInt(Vector<int> arr){
    for(int i = 0; i < arr.size(); i++){
        cout << arr[i] << " ";
    }
    cout << endl << endl << endl;
}
Example #19
0
void SharedBuffer::append(const Vector<char>& data)
{
    append(data.data(), data.size());
}
void PrintVectorString(Vector<string> arr){
    for(int i = 0; i < arr.size(); i++){
        cout << arr[i] << endl;
    }
    cout << endl << endl << endl;
}
bool CollisionPolygon2DEditor::forward_gui_input(const Ref<InputEvent> &p_event) {

	if (!node)
		return false;

	Ref<InputEventMouseButton> mb = p_event;

	if (mb.is_valid()) {
		Transform2D xform = canvas_item_editor->get_canvas_transform() * node->get_global_transform();

		Vector2 gpoint = mb->get_position();
		Vector2 cpoint = canvas_item_editor->get_canvas_transform().affine_inverse().xform(gpoint);
		cpoint = canvas_item_editor->snap_point(cpoint);
		cpoint = node->get_global_transform().affine_inverse().xform(cpoint);

		Vector<Vector2> poly = node->get_polygon();

		//first check if a point is to be added (segment split)
		real_t grab_threshold = EDITOR_DEF("editors/poly_editor/point_grab_radius", 8);

		switch (mode) {

			case MODE_CREATE: {

				if (mb->get_button_index() == BUTTON_LEFT && mb->is_pressed()) {

					if (!wip_active) {

						wip.clear();
						wip.push_back(cpoint);
						wip_active = true;
						edited_point_pos = cpoint;
						canvas_item_editor->get_viewport_control()->update();
						edited_point = 1;
						return true;
					} else {

						if (wip.size() > 1 && xform.xform(wip[0]).distance_to(gpoint) < grab_threshold) {
							//wip closed
							_wip_close();

							return true;
						} else {

							wip.push_back(cpoint);
							edited_point = wip.size();
							canvas_item_editor->get_viewport_control()->update();
							return true;

							//add wip point
						}
					}
				} else if (mb->get_button_index() == BUTTON_RIGHT && mb->is_pressed() && wip_active) {
					_wip_close();
				}

			} break;

			case MODE_EDIT: {

				if (mb->get_button_index() == BUTTON_LEFT) {
					if (mb->is_pressed()) {

						if (mb->get_control()) {

							if (poly.size() < 3) {

								undo_redo->create_action(TTR("Edit Poly"));
								undo_redo->add_undo_method(node, "set_polygon", poly);
								poly.push_back(cpoint);
								undo_redo->add_do_method(node, "set_polygon", poly);
								undo_redo->add_do_method(canvas_item_editor->get_viewport_control(), "update");
								undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(), "update");
								undo_redo->commit_action();
								return true;
							}

							//search edges
							int closest_idx = -1;
							Vector2 closest_pos;
							real_t closest_dist = 1e10;
							for (int i = 0; i < poly.size(); i++) {

								Vector2 points[2] = { xform.xform(poly[i]),
									xform.xform(poly[(i + 1) % poly.size()]) };

								Vector2 cp = Geometry::get_closest_point_to_segment_2d(gpoint, points);
								if (cp.distance_squared_to(points[0]) < CMP_EPSILON2 || cp.distance_squared_to(points[1]) < CMP_EPSILON2)
									continue; //not valid to reuse point

								real_t d = cp.distance_to(gpoint);
								if (d < closest_dist && d < grab_threshold) {
									closest_dist = d;
									closest_pos = cp;
									closest_idx = i;
								}
							}

							if (closest_idx >= 0) {

								pre_move_edit = poly;
								poly.insert(closest_idx + 1, xform.affine_inverse().xform(closest_pos));
								edited_point = closest_idx + 1;
								edited_point_pos = xform.affine_inverse().xform(closest_pos);
								node->set_polygon(poly);
								canvas_item_editor->get_viewport_control()->update();
								return true;
							}
						} else {

							//look for points to move

							int closest_idx = -1;
							Vector2 closest_pos;
							real_t closest_dist = 1e10;
							for (int i = 0; i < poly.size(); i++) {

								Vector2 cp = xform.xform(poly[i]);

								real_t d = cp.distance_to(gpoint);
								if (d < closest_dist && d < grab_threshold) {
									closest_dist = d;
									closest_pos = cp;
									closest_idx = i;
								}
							}

							if (closest_idx >= 0) {

								pre_move_edit = poly;
								edited_point = closest_idx;
								edited_point_pos = xform.affine_inverse().xform(closest_pos);
								canvas_item_editor->get_viewport_control()->update();
								return true;
							}
						}
					} else {

						if (edited_point != -1) {

							//apply

							ERR_FAIL_INDEX_V(edited_point, poly.size(), false);
							poly[edited_point] = edited_point_pos;
							undo_redo->create_action(TTR("Edit Poly"));
							undo_redo->add_do_method(node, "set_polygon", poly);
							undo_redo->add_undo_method(node, "set_polygon", pre_move_edit);
							undo_redo->add_do_method(canvas_item_editor->get_viewport_control(), "update");
							undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(), "update");
							undo_redo->commit_action();

							edited_point = -1;
							return true;
						}
					}
				} else if (mb->get_button_index() == BUTTON_RIGHT && mb->is_pressed() && edited_point == -1) {

					int closest_idx = -1;
					Vector2 closest_pos;
					real_t closest_dist = 1e10;
					for (int i = 0; i < poly.size(); i++) {

						Vector2 cp = xform.xform(poly[i]);

						real_t d = cp.distance_to(gpoint);
						if (d < closest_dist && d < grab_threshold) {
							closest_dist = d;
							closest_pos = cp;
							closest_idx = i;
						}
					}

					if (closest_idx >= 0) {

						undo_redo->create_action(TTR("Edit Poly (Remove Point)"));
						undo_redo->add_undo_method(node, "set_polygon", poly);
						poly.remove(closest_idx);
						undo_redo->add_do_method(node, "set_polygon", poly);
						undo_redo->add_do_method(canvas_item_editor->get_viewport_control(), "update");
						undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(), "update");
						undo_redo->commit_action();
						return true;
					}
				}

			} break;
		}
	}

	Ref<InputEventMouseMotion> mm = p_event;

	if (mm.is_valid()) {

		if (edited_point != -1 && (wip_active || mm->get_button_mask() & BUTTON_MASK_LEFT)) {

			Vector2 gpoint = mm->get_position();
			Vector2 cpoint = canvas_item_editor->get_canvas_transform().affine_inverse().xform(gpoint);
			cpoint = canvas_item_editor->snap_point(cpoint);
			edited_point_pos = node->get_global_transform().affine_inverse().xform(cpoint);

			canvas_item_editor->get_viewport_control()->update();
		}
	}

	return false;
}
Example #22
0
void Topology::makeSwitchesPerChip(Vector< Vector < SwitchID > > &nodePairs, Vector<int> &latencies, Vector<int> &bw_multis, int numberOfChipSwitches)
{

  Vector < SwitchID > nodes;  // temporary buffer
  nodes.setSize(2);

  Vector<bool> endpointConnectionExist;  // used to ensure all endpoints are connected to the network
  endpointConnectionExist.setSize(m_nodes);
  // initialize endpoint check vector
  for (int k = 0; k < endpointConnectionExist.size(); k++) {
    endpointConnectionExist[k] = false;
  }

  Vector<int> componentCount;
  componentCount.setSize(MachineType_NUM);
  for (MachineType mType = MachineType_FIRST; mType < MachineType_NUM; ++mType) {
    componentCount[mType] = 0;
  }

  // components to/from network links
  for (int chip = 0; chip < RubyConfig::numberOfChips(); chip++) {
    for (MachineType mType = MachineType_FIRST; mType < MachineType_NUM; ++mType) {
      for (int component = 0; component < MachineType_chip_count(mType, chip); component++) {
        
        int latency = -1;
        int bw_multiplier = -1;  // internal link bw multiplier of the global bandwidth
        if (mType != MachineType_Directory) {
          latency = ON_CHIP_LINK_LATENCY;  // internal link latency
          bw_multiplier = 10;  // internal link bw multiplier of the global bandwidth
        } else {
          latency = NETWORK_LINK_LATENCY;  // local memory latency
          bw_multiplier = 1;  // local memory link bw multiplier of the global bandwidth
        }
        nodes[0] = MachineType_base_number(mType)+componentCount[mType];
        nodes[1] = chip+m_nodes*2; // this is the chip's internal switch id #

        // insert link
        nodePairs.insertAtBottom(nodes);
        latencies.insertAtBottom(latency);
        //bw_multis.insertAtBottom(bw_multiplier);
        bw_multis.insertAtBottom(componentCount[mType]+MachineType_base_number((MachineType)mType));
        
        // opposite direction link
        Vector < SwitchID > otherDirectionNodes;
        otherDirectionNodes.setSize(2);
        otherDirectionNodes[0] = nodes[1];
        otherDirectionNodes[1] = nodes[0]+m_nodes;
        nodePairs.insertAtBottom(otherDirectionNodes);
        latencies.insertAtBottom(latency);
        bw_multis.insertAtBottom(bw_multiplier);
        
        assert(!endpointConnectionExist[nodes[0]]);
        endpointConnectionExist[nodes[0]] = true; 
        componentCount[mType]++;
      }
    }
  }

  // make sure all enpoints are connected in the soon to be created network
  for (int k = 0; k < endpointConnectionExist.size(); k++) {
    if (endpointConnectionExist[k] == false) {
      cerr << "Error: Unconnected Endpoint: " << k << endl;
      exit(1);
    }
  }

  // secondary check to ensure we saw the correct machine counts
  for (MachineType mType = MachineType_FIRST; mType < MachineType_NUM; ++mType) {
    assert(componentCount[mType] == MachineType_base_count((MachineType)mType));
  }

}
Example #23
0
void TextureMapperLayer::sortByZOrder(Vector<TextureMapperLayer* >& array)
{
    qsort(array.data(), array.size(), sizeof(TextureMapperLayer*), compareGraphicsLayersZValue);
}
Example #24
0
void Topology::make2DTorus()
{
  Vector< Vector < SwitchID > > nodePairs;  // node pairs extracted from the file
  Vector<int> latencies;  // link latencies for each link extracted
  Vector<int> bw_multis;  // bw multipliers for each link extracted

  Vector < SwitchID > nodes;  // temporary buffer
  nodes.setSize(2);

  // number of inter-chip switches
  int numberOfTorusSwitches = m_nodes/MachineType_base_level(MachineType_NUM);
  // one switch per machine node grouping
  Vector<SwitchID> torusSwitches;
  for(int i=0; i<numberOfTorusSwitches; i++){
    SwitchID new_switch = newSwitchID();
    torusSwitches.insertAtBottom(new_switch);
  }

  makeSwitchesPerChip(nodePairs, latencies, bw_multis, numberOfTorusSwitches);

  int lengthOfSide = (int)sqrt((double)numberOfTorusSwitches);

  // Now connect the inter-chip torus links
  
  int latency = NETWORK_LINK_LATENCY;  // external link latency
  int bw_multiplier = 1;  // external link bw multiplier of the global bandwidth

  for(int i=0; i<numberOfTorusSwitches; i++){
    nodes[0] = torusSwitches[i];  // current switch

    // left
    if(nodes[0]%lengthOfSide == 0){ // determine left neighbor
      nodes[1] = nodes[0] - 1 + lengthOfSide; 
    } else {
      nodes[1] = nodes[0] - 1;
    }
    nodePairs.insertAtBottom(nodes);
    latencies.insertAtBottom(latency);
    bw_multis.insertAtBottom(bw_multiplier);

    // right
    if((nodes[0] + 1)%lengthOfSide == 0){ // determine right neighbor
      nodes[1] = nodes[0] + 1 - lengthOfSide;
    } else { 
      nodes[1] = nodes[0] + 1;
    }
    nodePairs.insertAtBottom(nodes);
    latencies.insertAtBottom(latency);
    bw_multis.insertAtBottom(bw_multiplier);

    // top
    if(nodes[0] - lengthOfSide < 2*m_nodes){ // determine if node is on the top
      nodes[1] = nodes[0] - lengthOfSide + (lengthOfSide*lengthOfSide);
    } else {
      nodes[1] = nodes[0] - lengthOfSide;
    }
    nodePairs.insertAtBottom(nodes);
    latencies.insertAtBottom(latency);
    bw_multis.insertAtBottom(bw_multiplier);
    
    // bottom
    if(nodes[0] + lengthOfSide >= 2*m_nodes+numberOfTorusSwitches){ // determine if node is on the bottom
      // sorin: bad bug if this is a > instead of a >=
      nodes[1] = nodes[0] + lengthOfSide - (lengthOfSide*lengthOfSide);
    } else {
      nodes[1] = nodes[0] + lengthOfSide;
    }
    nodePairs.insertAtBottom(nodes);
    latencies.insertAtBottom(latency);
    bw_multis.insertAtBottom(bw_multiplier);
    
  }
  
  // add links
  ASSERT(nodePairs.size() == latencies.size() && latencies.size() == bw_multis.size())
  for (int k = 0; k < nodePairs.size(); k++) {
    ASSERT(nodePairs[k].size() == 2);
    addLink(nodePairs[k][0], nodePairs[k][1], latencies[k], bw_multis[k]);
  }

}
Example #25
0
bool Connection::sendOutgoingMessage(MessageID messageID, PassOwnPtr<MessageEncoder> encoder)
{
    Vector<Attachment> attachments = encoder->releaseAttachments();

    size_t numberOfPortDescriptors = 0;
    size_t numberOfOOLMemoryDescriptors = 0;
    for (size_t i = 0; i < attachments.size(); ++i) {
        Attachment::Type type = attachments[i].type();
        if (type == Attachment::MachPortType)
            numberOfPortDescriptors++;
        else if (type == Attachment::MachOOLMemoryType)
            numberOfOOLMemoryDescriptors++;
    }

    size_t messageSize = machMessageSize(encoder->bufferSize(), numberOfPortDescriptors, numberOfOOLMemoryDescriptors);
    char buffer[inlineMessageMaxSize];

    bool messageBodyIsOOL = false;
    if (messageSize > sizeof(buffer)) {
        messageBodyIsOOL = true;

        attachments.append(Attachment(encoder->buffer(), encoder->bufferSize(), MACH_MSG_VIRTUAL_COPY, false));
        numberOfOOLMemoryDescriptors++;
        messageSize = machMessageSize(0, numberOfPortDescriptors, numberOfOOLMemoryDescriptors);
    }

    bool isComplex = (numberOfPortDescriptors + numberOfOOLMemoryDescriptors > 0);

    mach_msg_header_t* header = reinterpret_cast<mach_msg_header_t*>(&buffer);
    header->msgh_bits = isComplex ? MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND | MACH_MSGH_BITS_COMPLEX, 0) : MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND, 0);
    header->msgh_size = messageSize;
    header->msgh_remote_port = m_sendPort;
    header->msgh_local_port = MACH_PORT_NULL;
    header->msgh_id = messageID.toInt();
    if (messageBodyIsOOL)
        header->msgh_id |= MessageBodyIsOOL;

    uint8_t* messageData;

    if (isComplex) {
        mach_msg_body_t* body = reinterpret_cast<mach_msg_body_t*>(header + 1);
        body->msgh_descriptor_count = numberOfPortDescriptors + numberOfOOLMemoryDescriptors;

        uint8_t* descriptorData = reinterpret_cast<uint8_t*>(body + 1);
        for (size_t i = 0; i < attachments.size(); ++i) {
            Attachment attachment = attachments[i];

            mach_msg_descriptor_t* descriptor = reinterpret_cast<mach_msg_descriptor_t*>(descriptorData);
            switch (attachment.type()) {
            case Attachment::MachPortType:
                descriptor->port.name = attachment.port();
                descriptor->port.disposition = attachment.disposition();
                descriptor->port.type = MACH_MSG_PORT_DESCRIPTOR;

                descriptorData += sizeof(mach_msg_port_descriptor_t);
                break;
            case Attachment::MachOOLMemoryType:
                descriptor->out_of_line.address = attachment.address();
                descriptor->out_of_line.size = attachment.size();
                descriptor->out_of_line.copy = attachment.copyOptions();
                descriptor->out_of_line.deallocate = attachment.deallocate();
                descriptor->out_of_line.type = MACH_MSG_OOL_DESCRIPTOR;

                descriptorData += sizeof(mach_msg_ool_descriptor_t);
                break;
            default:
                ASSERT_NOT_REACHED();
            }
        }

        messageData = descriptorData;
    } else
        messageData = (uint8_t*)(header + 1);

    // Copy the data if it is not being sent out-of-line.
    if (!messageBodyIsOOL)
        memcpy(messageData, encoder->buffer(), encoder->bufferSize());

    ASSERT(m_sendPort);

    // Send the message.
    kern_return_t kr = mach_msg(header, MACH_SEND_MSG, messageSize, 0, MACH_PORT_NULL, MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL);
    if (kr != KERN_SUCCESS) {
        // FIXME: What should we do here?
    }

    return true;
}
Example #26
0
// one internal node per chip, point to point links between chips
void Topology::makePtToPt()
{
  Vector< Vector < SwitchID > > nodePairs;  // node pairs extracted from the file
  Vector<int> latencies;  // link latencies for each link extracted
  Vector<int> bw_multis;  // bw multipliers for each link extracted

  Vector < SwitchID > nodes;
  nodes.setSize(2);

  // number of inter-chip switches
  int numberOfChipSwitches = m_nodes/MachineType_base_level(MachineType_NUM);
  // two switches per machine node grouping
  // one intra-chip switch and one inter-chip switch per chip
  for(int i=0; i<numberOfChipSwitches; i++){
    SwitchID new_switch = newSwitchID();
    new_switch = newSwitchID();
  }

  makeSwitchesPerChip(nodePairs, latencies, bw_multis, numberOfChipSwitches);

  // connect intra-chip switch to inter-chip switch
  for (int chip = 0; chip < RubyConfig::numberOfChips(); chip++) {
      
    int latency = ON_CHIP_LINK_LATENCY;  // internal link latency
    int bw_multiplier = 10;  // external link bw multiplier of the global bandwidth
    
    nodes[0] = chip+m_nodes*2;
    nodes[1] = chip+m_nodes*2+RubyConfig::numberOfChips();
    
    // insert link
    nodePairs.insertAtBottom(nodes);
    latencies.insertAtBottom(latency);
    bw_multis.insertAtBottom(bw_multiplier);

    // opposite direction link
    Vector < SwitchID > otherDirectionNodes;
    otherDirectionNodes.setSize(2);
    otherDirectionNodes[0] = nodes[1];
    otherDirectionNodes[1] = nodes[0];
    nodePairs.insertAtBottom(otherDirectionNodes);
    latencies.insertAtBottom(latency);
    bw_multis.insertAtBottom(bw_multiplier);
  }

  // point-to-point network between chips
  for (int chip = 0; chip < RubyConfig::numberOfChips(); chip++) {
    for (int other_chip = chip+1; other_chip < RubyConfig::numberOfChips(); other_chip++) {
      
      int latency = NETWORK_LINK_LATENCY;  // external link latency
      int bw_multiplier = 1;  // external link bw multiplier of the global bandwidth
      
      nodes[0] = chip+m_nodes*2+RubyConfig::numberOfChips();
      nodes[1] = other_chip+m_nodes*2+RubyConfig::numberOfChips();
    
      // insert link
      nodePairs.insertAtBottom(nodes);
      latencies.insertAtBottom(latency);
      bw_multis.insertAtBottom(bw_multiplier);

      // opposite direction link
      Vector < SwitchID > otherDirectionNodes;
      otherDirectionNodes.setSize(2);
      otherDirectionNodes[0] = nodes[1];
      otherDirectionNodes[1] = nodes[0];
      nodePairs.insertAtBottom(otherDirectionNodes);
      latencies.insertAtBottom(latency);
      bw_multis.insertAtBottom(bw_multiplier);
    }
  }

  // add links
  ASSERT(nodePairs.size() == latencies.size() && latencies.size() == bw_multis.size())
  for (int k = 0; k < nodePairs.size(); k++) {
    ASSERT(nodePairs[k].size() == 2);
    addLink(nodePairs[k][0], nodePairs[k][1], latencies[k], bw_multis[k]);
  }
}
Example #27
0
double LocaleWin::parseDate(const Vector<DateFormatToken>& tokens, int baseYear, const String& input)
{
    ensureShortMonthLabels();
    ensureMonthLabels();
    const double NaN = numeric_limits<double>::quiet_NaN();
    unsigned inputIndex = 0;
    int day = -1, month = -1, year = -1;
    for (unsigned i = 0; i < tokens.size(); ++i) {
        switch (tokens[i].type) {
        case DateFormatToken::Literal: {
            String data = tokens[i].data;
            unsigned literalLength = data.length();
            if (input.substring(inputIndex, literalLength) == data)
                inputIndex += literalLength;
            // Go ahead even if the input doesn't have this string.
            break;
        }
        case DateFormatToken::Day1:
        case DateFormatToken::Day2:
            day = parseNumber(input, inputIndex);
            if (day < 1 || day > 31)
                return NaN;
            break;
        case DateFormatToken::Month1:
        case DateFormatToken::Month2:
        case DateFormatToken::Month3:
        case DateFormatToken::Month4:
            month = parseNumberOrMonth(input, inputIndex);
            if (month < 0 || month > 11)
                return NaN;
            break;
        case DateFormatToken::Year1: {
            unsigned oldIndex = inputIndex;
            year = parseNumber(input, inputIndex);
            if (year <= 0)
                return NaN;
            if (inputIndex - oldIndex == 1) {
                int shortYear = baseYear % 10;
                int decade = baseYear - shortYear;
                if (shortYear >= 5)
                    year += shortYear - 4 <= year ? decade : decade + 10;
                else
                    year += shortYear + 5 >= year ? decade : decade - 10;
            }
            break;
        }
        case DateFormatToken::Year2: {
            unsigned oldIndex = inputIndex;
            year = parseNumber(input, inputIndex);
            if (year <= 0)
                return NaN;
            if (inputIndex - oldIndex == 2) {
                int shortYear = baseYear % 100;
                int century = baseYear - shortYear;
                if (shortYear >= 50)
                    year += shortYear - 49 <= year ? century : century + 100;
                else
                    year += shortYear + 50 >= year ? century : century - 100;
            }
            break;
        }
        case DateFormatToken::Year4:
            year = parseNumber(input, inputIndex);
            if (year <= 0)
                return NaN;
            break;
        }
    }
    if (year <= 0 || month < 0 || day <= 0)
        return NaN;
    return dateToDaysFrom1970(year, month, day) * msPerDay;
}
Example #28
0
// make a network as described by the networkFile
void Topology::makeFileSpecified(TopoType topoType)
{

  Vector< Vector < SwitchID > > nodePairs;  // node pairs extracted from the file
  Vector<int> latencies;  // link latencies for each link extracted
  Vector<int> bw_multis;  // bw multipliers for each link extracted
  Vector<int> weights;  // link weights used to enfore e-cube deadlock free routing
  Vector< SwitchID > int_network_switches;  // internal switches extracted from the file
  Vector<bool> endpointConnectionExist;  // used to ensure all endpoints are connected to the network
 
  endpointConnectionExist.setSize(m_nodes);

  // initialize endpoint check vector
  for (int k = 0; k < endpointConnectionExist.size(); k++) {
    endpointConnectionExist[k] = false;
  }

  string filename = "";
  if (g_SIMICS) {
      filename = "../ruby/";
  }
  else
      filename = "/curr/ghodrat/cdsc-simulation-platform/trunk/gems-2.1/ruby/";
  filename = filename + "network/simple/Network_Files/";

  if(topoType == TopoType_Default)
  {
      if(RubyConfig::networkConfigFile() && strcmp(RubyConfig::networkConfigFile(), "DEFAULT") != 0)
          filename = RubyConfig::RubyConfig::networkConfigFile(); 
      else
          filename = filename+g_CACHE_DESIGN
              +"_Procs-"+int_to_string(RubyConfig::numberOfProcessors())
              +"_ProcsPerChip-"+int_to_string(RubyConfig::numberOfProcsPerChip())
              +"_L2Banks-"+int_to_string(RubyConfig::numberOfL2Cache())
              +"_Memories-"+int_to_string(RubyConfig::numberOfMemories())
#ifdef SIM_NET_PORTS
              ; if (RubyConfig::numberOfSimicsNetworkPort() > 0) filename = filename
              +"_SimPorts-"+int_to_string(RubyConfig::numberOfSimicsNetworkPort())
              ; filename = filename
#endif
              +".txt";
  }
  else if (topoType == TopoType_Dir2Buf)
  {
     filename = filename+g_CACHE_DESIGN  
              +"_Procs-"+int_to_string(RubyConfig::numberOfProcessors())
              +"_ProcsPerChip-"+int_to_string(RubyConfig::numberOfProcsPerChip())
              +"_L2Banks-"+int_to_string(RubyConfig::numberOfL2Cache())
              +"_Memories-"+int_to_string(RubyConfig::numberOfMemories())
#ifdef SIM_NET_PORTS
              ; if (RubyConfig::numberOfSimicsNetworkPort() > 0) filename = filename
              +"_SimPorts-"+int_to_string(RubyConfig::numberOfSimicsNetworkPort())
              ; filename = filename
#endif
              +"_Dir2Buf"
              +".txt";
  }
  else
  {

  }

  cout << "Opening network file: " << filename << std::endl;

  ifstream networkFile( filename.c_str() , ios::in);
  if (!networkFile.is_open()) {
      cerr << "Error: Could not open network file: " << filename << endl;
      cerr << "Probably no network file exists for " << RubyConfig::numberOfProcessors()
         << " processors and " << RubyConfig::numberOfProcsPerChip() << " procs per chip " << endl;
    exit(1);
  }

  string line = "";

  while (!networkFile.eof()) {
    
    Vector < SwitchID > nodes;
    nodes.setSize(2);
    int latency = -1;  // null latency
    int weight = -1;  // null weight
    int bw_multiplier = DEFAULT_BW_MULTIPLIER;  // default multiplier incase the network file doesn't define it
    int i = 0;  // node pair index 
    int varsFound = 0;  // number of varsFound on the line
    int internalNodes = 0;  // used to determine if the link is between 2 internal nodes
    std::getline(networkFile, line, '\n');
    string varStr = string_split(line, ' ');

    // parse the current line in the file
    while (varStr != "") {
      string label = string_split(varStr, ':');

      // valid node labels
      if (label == "ext_node" || label == "int_node") {
        ASSERT(i < 2); // one link between 2 switches per line
        varsFound++;
        bool isNewIntSwitch = true;
        if (label == "ext_node") { // input link to node
          MachineType machine = string_to_MachineType(string_split(varStr, ':'));
          string nodeStr = string_split(varStr, ':');
          if (string_split(varStr, ':') == "bank") {
            nodes[i] = MachineType_base_number(machine)
              + atoi(nodeStr.c_str())
              + atoi((string_split(varStr, ':')).c_str())*RubyConfig::numberOfChips();
          } else {
            nodes[i] = MachineType_base_number(machine)
              + atoi(nodeStr.c_str());
          }
          // in nodes should be numbered 0 to m_nodes-1
          ASSERT(nodes[i] >= 0 && nodes[i] < m_nodes);
          isNewIntSwitch = false;
          endpointConnectionExist[nodes[i]] = true;
        }
        if (label == "int_node") { // interior node
          nodes[i] = atoi((string_split(varStr, ':')).c_str())+m_nodes*2;
          // in nodes should be numbered >= m_nodes*2
          ASSERT(nodes[i] >= m_nodes*2);
          for (int k = 0; k < int_network_switches.size(); k++) {
            if (int_network_switches[k] == nodes[i]) {
              isNewIntSwitch = false;
            }
          }
          if (isNewIntSwitch) {  // if internal switch
            m_number_of_switches++;
            int_network_switches.insertAtBottom(nodes[i]);
          }
          internalNodes++;
        }
        i++;
      } else if (label == "link_latency") {
        latency = atoi((string_split(varStr, ':')).c_str());
        varsFound++;
      } else if (label == "bw_multiplier") {  // not necessary, defaults to DEFAULT_BW_MULTIPLIER
        bw_multiplier = atoi((string_split(varStr, ':')).c_str());
      } else if (label == "link_weight") {  // not necessary, defaults to link_latency
        weight = atoi((string_split(varStr, ':')).c_str());
      } else if (label == "processors") {
        ASSERT(atoi((string_split(varStr, ':')).c_str()) == RubyConfig::numberOfProcessors());
      } else if (label == "bw_unit") {
        ASSERT(atoi((string_split(varStr, ':')).c_str()) == g_endpoint_bandwidth);
      } else if (label == "procs_per_chip") {
        ASSERT(atoi((string_split(varStr, ':')).c_str()) == RubyConfig::numberOfProcsPerChip());         
      } else if (label == "L2banks") {
        ASSERT(atoi((string_split(varStr, ':')).c_str()) == RubyConfig::numberOfL2Cache());        
      } else if (label == "memories") {
        ASSERT(atoi((string_split(varStr, ':')).c_str()) == RubyConfig::numberOfMemories());
#ifdef SIM_NET_PORTS
      } else if (label == "simicsPorts") {
        ASSERT(atoi((string_split(varStr, ':')).c_str()) == RubyConfig::numberOfSimicsNetworkPort());
#endif
      } else {
        cerr << "Error: Unexpected Identifier: " << label << endl;
        exit(1);
      }
      varStr = string_split(line, ' ');
    }
    if (varsFound == 3) { // all three necessary link variables where found so add the link
      nodePairs.insertAtBottom(nodes);
      latencies.insertAtBottom(latency);
      if (weight != -1) {
        weights.insertAtBottom(weight);
      } else {
        weights.insertAtBottom(latency);
      }
      bw_multis.insertAtBottom(bw_multiplier);
      Vector < SwitchID > otherDirectionNodes;
      otherDirectionNodes.setSize(2);
      otherDirectionNodes[0] = nodes[1];
      if (internalNodes == 2) {  // this is an internal link
        otherDirectionNodes[1] = nodes[0];
      } else {
        otherDirectionNodes[1] = nodes[0]+m_nodes;
      }
      nodePairs.insertAtBottom(otherDirectionNodes);
      latencies.insertAtBottom(latency);
      if (weight != -1) {
        weights.insertAtBottom(weight);
      } else {
        weights.insertAtBottom(latency);
      }
      bw_multis.insertAtBottom(bw_multiplier);
    } else {
      if (varsFound != 0) {  // if this is not a valid link, then no vars should have been found
        cerr << "Error in line: " << line << endl;
        exit(1);
      }
    }
  } // end of file

  // makes sure all enpoints are connected in the soon to be created network
  for (int k = 0; k < endpointConnectionExist.size(); k++) {
    if (endpointConnectionExist[k] == false) {
      cerr << "Error: Unconnected Endpoint: " << k << endl;
      exit(1);
    }
  }

  //cerr << "Num nodes "<<m_nodes<<"\n";
  //cerr << "Node pairs "<<nodePairs.size()<<"\n";
  ASSERT(nodePairs.size() == latencies.size() && latencies.size() == bw_multis.size() && latencies.size() == weights.size())
  for (int k = 0; k < nodePairs.size(); k++) {
    ASSERT(nodePairs[k].size() == 2);
    addLink(nodePairs[k][0], nodePairs[k][1], latencies[k], bw_multis[k], weights[k]);
  }

  networkFile.close();
}
Example #29
0
bool convertWOFFToSfnt(SharedBuffer* woff, Vector<char>& sfnt)
{
    ASSERT_ARG(sfnt, sfnt.isEmpty());

    size_t offset = 0;

    // Read the WOFF header.
    uint32_t signature;
    if (!readUInt32(woff, offset, signature) || signature != woffSignature) {
        ASSERT_NOT_REACHED();
        return false;
    }

    uint32_t flavor;
    if (!readUInt32(woff, offset, flavor))
        return false;

    uint32_t length;
    if (!readUInt32(woff, offset, length) || length != woff->size())
        return false;

    uint16_t numTables;
    if (!readUInt16(woff, offset, numTables))
        return false;

    if (!numTables || numTables > 0x0fff)
        return false;

    uint16_t reserved;
    if (!readUInt16(woff, offset, reserved) || reserved)
        return false;

    uint32_t totalSfntSize;
    if (!readUInt32(woff, offset, totalSfntSize))
        return false;

    if (woff->size() - offset < sizeof(uint16_t) + sizeof(uint16_t) + sizeof(uint32_t) + sizeof(uint32_t) + sizeof(uint32_t) + sizeof(uint32_t) + sizeof(uint32_t))
        return false;

    offset += sizeof(uint16_t); // majorVersion
    offset += sizeof(uint16_t); // minorVersion
    offset += sizeof(uint32_t); // metaOffset
    offset += sizeof(uint32_t); // metaLength
    offset += sizeof(uint32_t); // metaOrigLength
    offset += sizeof(uint32_t); // privOffset
    offset += sizeof(uint32_t); // privLength

    // Check if the WOFF can supply as many tables as it claims it has.
    if (woff->size() - offset < numTables * 5 * sizeof(uint32_t))
        return false;

    // Write the sfnt offset subtable.
    uint16_t entrySelector = 0;
    uint16_t searchRange = 1;
    while (searchRange < numTables >> 1) {
        entrySelector++;
        searchRange <<= 1;
    }
    searchRange <<= 4;
    uint16_t rangeShift = (numTables << 4) - searchRange;

    if (!writeUInt32(sfnt, flavor)
        || !writeUInt16(sfnt, numTables)
        || !writeUInt16(sfnt, searchRange)
        || !writeUInt16(sfnt, entrySelector)
        || !writeUInt16(sfnt, rangeShift))
        return false;

    if (sfnt.size() > totalSfntSize)
        return false;

    if (totalSfntSize - sfnt.size() < numTables * 4 * sizeof(uint32_t))
        return false;

    size_t sfntTableDirectoryCursor = sfnt.size();
    sfnt.grow(sfnt.size() + numTables * 4 * sizeof(uint32_t));

    // Process tables.
    for (uint16_t i = 0; i < numTables; ++i) {
        // Read a WOFF table directory entry.
        uint32_t tableTag;
        if (!readUInt32(woff, offset, tableTag))
            return false;

        uint32_t tableOffset;
        if (!readUInt32(woff, offset, tableOffset))
            return false;

        uint32_t tableCompLength;
        if (!readUInt32(woff, offset, tableCompLength))
            return false;

        if (tableOffset > woff->size() || tableCompLength > woff->size() - tableOffset)
            return false;

        uint32_t tableOrigLength;
        if (!readUInt32(woff, offset, tableOrigLength) || tableCompLength > tableOrigLength)
            return false;

        if (tableOrigLength > totalSfntSize || sfnt.size() > totalSfntSize - tableOrigLength)
            return false;

        uint32_t tableOrigChecksum;
        if (!readUInt32(woff, offset, tableOrigChecksum))
            return false;

        // Write an sfnt table directory entry.
        uint32_t* sfntTableDirectoryPtr = reinterpret_cast<uint32_t*>(sfnt.data() + sfntTableDirectoryCursor);
        *sfntTableDirectoryPtr++ = htonl(tableTag);
        *sfntTableDirectoryPtr++ = htonl(tableOrigChecksum);
        *sfntTableDirectoryPtr++ = htonl(sfnt.size());
        *sfntTableDirectoryPtr++ = htonl(tableOrigLength);
        sfntTableDirectoryCursor += 4 * sizeof(uint32_t);

        if (tableCompLength == tableOrigLength) {
            // The table is not compressed.
            if (!sfnt.tryAppend(woff->data() + tableOffset, tableCompLength))
                return false;
        } else {
            uLongf destLen = tableOrigLength;
            if (!sfnt.tryReserveCapacity(sfnt.size() + tableOrigLength))
                return false;
            Bytef* dest = reinterpret_cast<Bytef*>(sfnt.end());
            sfnt.grow(sfnt.size() + tableOrigLength);
            if (uncompress(dest, &destLen, reinterpret_cast<const Bytef*>(woff->data() + tableOffset), tableCompLength) != Z_OK)
                return false;
            if (destLen != tableOrigLength)
                return false;
        }

        // Pad to a multiple of 4 bytes.
        while (sfnt.size() % 4)
            sfnt.append(0);
    }

    return sfnt.size() == totalSfntSize;
}
void CookieDatabaseBackingStore::upgradeTableIfNeeded(const String& databaseFields, const String& primaryKeyFields)
{
    ASSERT(isCurrentThread());

    bool creationTimeExists = false;
    bool protocolExists = false;

    if (!m_db.tableExists(m_tableName))
        return;

    // Check if the existing table has the required database fields
    {
        String query = "PRAGMA table_info(" + m_tableName + ");";

        SQLiteStatement statement(m_db, query);
        if (statement.prepare()) {
            LOG_ERROR("Cannot prepare statement to query cookie table info. sql:%s", query.utf8().data());
            LOG_ERROR("SQLite Error Message: %s", m_db.lastErrorMsg());
            return;
        }

        while (statement.step() == SQLResultRow) {
            DEFINE_STATIC_LOCAL(String, creationTime, (ASCIILiteral("creationTime")));
            DEFINE_STATIC_LOCAL(String, protocol, (ASCIILiteral("protocol")));
            String name = statement.getColumnText(1);
            if (name == creationTime)
                creationTimeExists = true;
            if (name == protocol)
                protocolExists = true;
            if (creationTimeExists && protocolExists)
                return;
        }
        LOG(Network, "Need to update cookie table schema.");
    }

    // Drop and recreate the cookie table to update to the latest database fields.
    // We do not use alter table - add column because that method cannot add primary keys.
    Vector<String> commands;

    // Backup existing table
    String renameQuery = "ALTER TABLE " + m_tableName + " RENAME TO Backup_" + m_tableName + ";";
    commands.append(renameQuery);

    // Recreate the cookie table using the new database and primary key fields
    StringBuilder createTableQuery;
    createTableQuery.append("CREATE TABLE ");
    createTableQuery.append(m_tableName);
    createTableQuery.append(" (" + databaseFields + ", " + primaryKeyFields + ");");
    commands.append(createTableQuery.toString());

    // Copy the old data into the new table. If a column does not exists,
    // we have to put a '' in the select statement to make the number of columns
    // equal in the insert statement.
    StringBuilder migrationQuery;
    migrationQuery.append("INSERT OR REPLACE INTO ");
    migrationQuery.append(m_tableName);
    migrationQuery.append(" SELECT *");
    if (!creationTimeExists)
        migrationQuery.append(",''");
    if (!protocolExists)
        migrationQuery.append(",''");
    migrationQuery.append(" FROM Backup_" + m_tableName);
    commands.append(migrationQuery.toString());

    // The new columns will be blank, set the new values.
    if (!creationTimeExists) {
        String setCreationTimeQuery = "UPDATE " + m_tableName + " SET creationTime = lastAccessed;";
        commands.append(setCreationTimeQuery);
    }

    if (!protocolExists) {
        String setProtocolQuery = "UPDATE " + m_tableName + " SET protocol = 'http' WHERE isSecure = '0';";
        String setProtocolQuery2 = "UPDATE " + m_tableName + " SET protocol = 'https' WHERE isSecure = '1';";
        commands.append(setProtocolQuery);
        commands.append(setProtocolQuery2);
    }

    // Drop the backup table
    String dropBackupQuery = "DROP TABLE IF EXISTS Backup_" + m_tableName + ";";
    commands.append(dropBackupQuery);

    SQLiteTransaction transaction(m_db, false);
    transaction.begin();
    size_t commandSize = commands.size();
    for (size_t i = 0; i < commandSize; ++i) {
        if (!m_db.executeCommand(commands[i])) {
            LOG_ERROR("Failed to alter cookie table when executing sql:%s", commands[i].utf8().data());
            LOG_ERROR("SQLite Error Message: %s", m_db.lastErrorMsg());
            transaction.rollback();

            // We should never get here, but if we do, rename the current cookie table for future restoration. This has the side effect of
            // clearing the current cookie table, but that's better than continually hitting this case and hence never being able to use the
            // cookie table.
            ASSERT_NOT_REACHED();
            String renameQuery = "ALTER TABLE " + m_tableName + " RENAME TO Backup2_" + m_tableName + ";";
            if (!m_db.executeCommand(renameQuery)) {
                LOG_ERROR("Failed to backup existing cookie table.");
                LOG_ERROR("SQLite Error Message: %s", m_db.lastErrorMsg());
            }
            return;
        }
    }
    transaction.commit();
    LOG(Network, "Successfully updated cookie table schema.");
}