Esempio n. 1
0
String cookies(const Document* /*document*/, const KURL& url)
{
    return cookieJar.get(url.string());
}
MutationObserverInterestGroup::MutationObserverInterestGroup(HashMap<WebKitMutationObserver*, MutationRecordDeliveryOptions>& observers, MutationRecordDeliveryOptions oldValueFlag)
    : m_oldValueFlag(oldValueFlag)
{
    ASSERT(!observers.isEmpty());
    m_observers.swap(observers);
}
Esempio n. 3
0
void CreateDialog::update_tree() {

	tree->clear();

	List<String> type_list;
	ObjectTypeDB::get_type_list(&type_list);

	HashMap<String,TreeItem*> types;

	TreeItem *root = tree->create_item();

	root->set_text(0,base);

	List<String>::Element *I=type_list.front();

	for(;I;I=I->next()) {


		String type=I->get();


		if (!ObjectTypeDB::can_instance(type))
			continue; // cant create what can't be instanced
		if (filter->get_text()=="")
			add_type(type,types,root);
		else {

			bool found=false;
			String type=I->get();
			while(type!="" && ObjectTypeDB::is_type(type,base) && type!=base) {
				if (type.findn(filter->get_text())!=-1) {

					found=true;
					break;
				}

				type=ObjectTypeDB::type_inherits_from(type);
			}


			if (found)
				add_type(I->get(),types,root);
		}

		if (EditorNode::get_editor_data().get_custom_types().has(type)) {
			//there are custom types based on this... cool.


			const Vector<EditorData::CustomType> &ct = EditorNode::get_editor_data().get_custom_types()[type];
			for(int i=0;i<ct.size();i++) {

				bool show = filter->get_text()=="" || ct[i].name.findn(filter->get_text())!=-1;

				if (!show)
					continue;
				if (!types.has(type))
					add_type(type,types,root);

				TreeItem *ti;
				if (types.has(type) )
					ti=types[type];
				else
					ti=tree->get_root();


				TreeItem *item = tree->create_item(ti);
				item->set_metadata(0,type);
				item->set_text(0,ct[i].name);
				if (ct[i].icon.is_valid()) {
					item->set_icon(0,ct[i].icon);

				}
			}

		}
	}


}
Esempio n. 4
0
bool PluginDatabase::refresh()
{
    bool pluginSetChanged = false;

    if (!m_plugins.isEmpty()) {
        PluginSet pluginsToUnload;
        getDeletedPlugins(pluginsToUnload);

        // Unload plugins
        PluginSet::const_iterator end = pluginsToUnload.end();
        for (PluginSet::const_iterator it = pluginsToUnload.begin(); it != end; ++it)
            remove(it->get());

        pluginSetChanged = !pluginsToUnload.isEmpty();
    }

    HashSet<String> paths;
    getPluginPathsInDirectories(paths);

    HashMap<String, time_t> pathsWithTimes;

    // We should only skip unchanged files if we didn't remove any plugins above. If we did remove
    // any plugins, we need to look at every plugin file so that, e.g., if the user has two versions
    // of RealPlayer installed and just removed the newer one, we'll pick up the older one.
    bool shouldSkipUnchangedFiles = !pluginSetChanged;

    HashSet<String>::const_iterator pathsEnd = paths.end();
    for (HashSet<String>::const_iterator it = paths.begin(); it != pathsEnd; ++it) {
        time_t lastModified;
        if (!getFileModificationTime(*it, lastModified))
            continue;

        pathsWithTimes.add(*it, lastModified);

        // If the path's timestamp hasn't changed since the last time we ran refresh(), we don't have to do anything.
        if (shouldSkipUnchangedFiles && m_pluginPathsWithTimes.get(*it) == lastModified)
            continue;

        if (RefPtr<PluginPackage> oldPackage = m_pluginsByPath.get(*it)) {
            ASSERT(!shouldSkipUnchangedFiles || oldPackage->lastModified() != lastModified);
            remove(oldPackage.get());
        }

        if (!m_client || m_client->shouldLoadPluginAtPath(*it)) {
            RefPtr<PluginPackage> package = PluginPackage::createPackage(*it, lastModified);
            if (package && (!m_client || m_client->shouldLoadPluginPackage(package.get())) && add(package.release()))
                pluginSetChanged = true;
        }
    }

    // Cache all the paths we found with their timestamps for next time.
    pathsWithTimes.swap(m_pluginPathsWithTimes);

    if (!pluginSetChanged)
        return false;

    m_registeredMIMETypes.clear();

    // Register plug-in MIME types
    PluginSet::const_iterator end = m_plugins.end();
    for (PluginSet::const_iterator it = m_plugins.begin(); it != end; ++it) {
        // Get MIME types
        MIMEToDescriptionsMap::const_iterator map_it = (*it)->mimeToDescriptions().begin();
        MIMEToDescriptionsMap::const_iterator map_end = (*it)->mimeToDescriptions().end();
        for (; map_it != map_end; ++map_it)
            m_registeredMIMETypes.add(map_it->first);
    }

    return true;
}
namespace WebCore {

static int s_maxTextureSize = 0;
static HashMap<int, CanvasTexture*> s_textures;
static android::Mutex s_texturesLock;

/********************************************
 * Called by both threads
 ********************************************/

PassRefPtr<CanvasTexture> CanvasTexture::getCanvasTexture(CanvasLayer* layer)
{
    android::Mutex::Autolock lock(s_texturesLock);
    RefPtr<CanvasTexture> texture = s_textures.get(layer->uniqueId());
    if (texture.get())
        return texture.release();
    return adoptRef(new CanvasTexture(layer->uniqueId()));
}

bool CanvasTexture::setHwAccelerated(bool hwAccelerated)
{
    android::Mutex::Autolock lock(m_surfaceLock);
    if (m_useHwAcceleration == hwAccelerated)
        return false;
    m_useHwAcceleration = hwAccelerated;
    if (!m_ANW.get())
        return false;
    destroySurfaceTextureLocked();
    return true;
}

/********************************************
 * Called by WebKit thread
 ********************************************/

void CanvasTexture::setSize(const IntSize& size)
{
    android::Mutex::Autolock lock(m_surfaceLock);
    if (m_size == size)
        return;
    m_size = size;
    if (m_ANW.get()) {
        if (useSurfaceTexture()) {
            int result = native_window_set_buffers_dimensions(m_ANW.get(),
                    m_size.width(), m_size.height());
            GLUtils::checkSurfaceTextureError("native_window_set_buffers_dimensions", result);
            if (result != NO_ERROR)
                m_useHwAcceleration = false; // On error, drop out of HWA
        }
        if (!useSurfaceTexture())
            destroySurfaceTextureLocked();
    }
}

SurfaceTextureClient* CanvasTexture::nativeWindow()
{
    android::Mutex::Autolock lock(m_surfaceLock);
    if (m_ANW.get())
        return m_ANW.get();
    if (!m_texture)
        return 0;
    if (!useSurfaceTexture())
        return 0;
    m_surfaceTexture = new android::SurfaceTexture(m_texture, false);
    m_ANW = new android::SurfaceTextureClient(m_surfaceTexture);
    int result = native_window_set_buffers_format(m_ANW.get(), HAL_PIXEL_FORMAT_RGBA_8888);
    GLUtils::checkSurfaceTextureError("native_window_set_buffers_format", result);
    if (result == NO_ERROR) {
        result = native_window_set_buffers_dimensions(m_ANW.get(),
                m_size.width(), m_size.height());
        GLUtils::checkSurfaceTextureError("native_window_set_buffers_dimensions", result);
    }
    if (result != NO_ERROR) {
        m_useHwAcceleration = false;
        destroySurfaceTextureLocked();
        return 0;
    }
    return m_ANW.get();
}

bool CanvasTexture::uploadImageBuffer(ImageBuffer* imageBuffer)
{
    m_hasValidTexture = false;
    SurfaceTextureClient* anw = nativeWindow();
    if (!anw)
        return false;
    // Size mismatch, early abort (will fall back to software)
    if (imageBuffer->size() != m_size)
        return false;
    GraphicsContext* gc = imageBuffer ? imageBuffer->context() : 0;
    if (!gc)
        return false;
    const SkBitmap& bitmap = android_gc2canvas(gc)->getDevice()->accessBitmap(false);
    if (!GLUtils::updateSharedSurfaceTextureWithBitmap(anw, bitmap))
        return false;
    m_hasValidTexture = true;
    return true;
}

/********************************************
 * Called by UI thread WITH GL context
 ********************************************/

CanvasTexture::~CanvasTexture()
{
    if (m_layerId) {
        s_texturesLock.lock();
        s_textures.remove(m_layerId);
        s_texturesLock.unlock();
    }
    if (m_texture)
        GLUtils::deleteTexture(&m_texture);
}

void CanvasTexture::requireTexture()
{
    android::Mutex::Autolock lock(m_surfaceLock);
    if (!m_texture)
        glGenTextures(1, &m_texture);
    if (!s_maxTextureSize)
        glGetIntegerv(GL_MAX_TEXTURE_SIZE, &s_maxTextureSize);
}

bool CanvasTexture::updateTexImage()
{
    android::Mutex::Autolock lock(m_surfaceLock);
    if (!m_surfaceTexture.get())
        return false;
    status_t result = m_surfaceTexture->updateTexImage();
    if (result != OK) {
        ALOGE("unexpected error: updateTexImage return %d", result);
        return false;
    }
    return true;
}

/********************************************
 * Called by both threads
 ********************************************/

void CanvasTexture::destroySurfaceTextureLocked()
{
    if (m_ANW.get()) {
        m_ANW.clear();
        m_surfaceTexture->abandon();
        m_surfaceTexture.clear();
    }
}

/********************************************
 * Called by WebKit thread
 ********************************************/

CanvasTexture::CanvasTexture(int layerId)
    : m_size()
    , m_layerId(layerId)
    , m_texture(0)
    , m_surfaceTexture(0)
    , m_ANW(0)
    , m_hasValidTexture(false)
    , m_useHwAcceleration(true)
{
    s_textures.add(m_layerId, this);
}

// TODO: Have a global limit as well as a way to react to low memory situations
bool CanvasTexture::useSurfaceTexture()
{
    if (!m_useHwAcceleration)
        return false;
    if (m_size.isEmpty())
        return false;
    return (m_size.width() < s_maxTextureSize) && (m_size.height() < s_maxTextureSize);
}

} // namespace WebCore
Esempio n. 6
0
void demoteValues(Procedure& proc, const IndexSet<Value>& values)
{
    HashMap<Value*, StackSlotValue*> map;
    HashMap<Value*, StackSlotValue*> phiMap;

    // Create stack slots.
    InsertionSet insertionSet(proc);
    for (Value* value : values.values(proc.values())) {
        StackSlotValue* stack = insertionSet.insert<StackSlotValue>(
            0, value->origin(), sizeofType(value->type()), StackSlotKind::Anonymous);
        map.add(value, stack);

        if (value->opcode() == Phi) {
            StackSlotValue* phiStack = insertionSet.insert<StackSlotValue>(
                0, value->origin(), sizeofType(value->type()), StackSlotKind::Anonymous);
            phiMap.add(value, phiStack);
        }
    }
    insertionSet.execute(proc[0]);

    if (verbose) {
        dataLog("Demoting values as follows:\n");
        dataLog("   map = ");
        CommaPrinter comma;
        for (auto& entry : map)
            dataLog(comma, *entry.key, "=>", *entry.value);
        dataLog("\n");
        dataLog("   phiMap = ");
        comma = CommaPrinter();
        for (auto& entry : phiMap)
            dataLog(comma, *entry.key, "=>", *entry.value);
        dataLog("\n");
    }

    // Change accesses to the values to accesses to the stack slots.
    for (BasicBlock* block : proc) {
        for (unsigned valueIndex = 0; valueIndex < block->size(); ++valueIndex) {
            Value* value = block->at(valueIndex);

            if (value->opcode() == Phi) {
                if (StackSlotValue* stack = phiMap.get(value)) {
                    value->replaceWithIdentity(
                        insertionSet.insert<MemoryValue>(
                            valueIndex, Load, value->type(), value->origin(), stack));
                }
            } else {
                for (Value*& child : value->children()) {
                    if (StackSlotValue* stack = map.get(child)) {
                        child = insertionSet.insert<MemoryValue>(
                            valueIndex, Load, child->type(), value->origin(), stack);
                    }
                }

                if (UpsilonValue* upsilon = value->as<UpsilonValue>()) {
                    if (StackSlotValue* stack = phiMap.get(upsilon->phi())) {
                        insertionSet.insert<MemoryValue>(
                            valueIndex, Store, upsilon->origin(), upsilon->child(0), stack);
                        value->replaceWithNop();
                    }
                }
            }

            if (StackSlotValue* stack = map.get(value)) {
                insertionSet.insert<MemoryValue>(
                    valueIndex + 1, Store, value->origin(), value, stack);
            }
        }
        insertionSet.execute(block);
    }
}
Esempio n. 7
0
 void setPayloadData(const String& field, int32_t numFieldInstancesToSkip, ByteArray data, int32_t offset, int32_t length) {
     PayloadDataPtr payload = newLucene<PayloadData>(numFieldInstancesToSkip, data, offset, length);
     fieldToData.put(field, payload);
 }
Esempio n. 8
0
void addAllowedClientCertificate(const String& host, const String& certificate, const String& key)
{
    clientCertificate clientInfo(certificate, key);
    allowedClientHosts.set(host.lower(), clientInfo);
}
Esempio n. 9
0
void IntlDateTimeFormat::initializeDateTimeFormat(ExecState& exec, JSValue locales, JSValue originalOptions)
{
    VM& vm = exec.vm();
    auto scope = DECLARE_THROW_SCOPE(vm);

    // 12.1.1 InitializeDateTimeFormat (dateTimeFormat, locales, options) (ECMA-402 2.0)
    // 1. If dateTimeFormat.[[initializedIntlObject]] is true, throw a TypeError exception.
    // 2. Set dateTimeFormat.[[initializedIntlObject]] to true.

    // 3. Let requestedLocales be CanonicalizeLocaleList(locales).
    Vector<String> requestedLocales = canonicalizeLocaleList(exec, locales);
    // 4. ReturnIfAbrupt(requestedLocales),
    RETURN_IF_EXCEPTION(scope, void());

    // 5. Let options be ToDateTimeOptions(options, "any", "date").
    JSObject* options = toDateTimeOptionsAnyDate(exec, originalOptions);
    // 6. ReturnIfAbrupt(options).
    RETURN_IF_EXCEPTION(scope, void());

    // 7. Let opt be a new Record.
    HashMap<String, String> localeOpt;

    // 8. Let matcher be GetOption(options, "localeMatcher", "string", «"lookup", "best fit"», "best fit").
    String localeMatcher = intlStringOption(exec, options, vm.propertyNames->localeMatcher, { "lookup", "best fit" }, "localeMatcher must be either \"lookup\" or \"best fit\"", "best fit");
    // 9. ReturnIfAbrupt(matcher).
    RETURN_IF_EXCEPTION(scope, void());
    // 10. Set opt.[[localeMatcher]] to matcher.
    localeOpt.add(vm.propertyNames->localeMatcher.string(), localeMatcher);

    // 11. Let localeData be the value of %DateTimeFormat%.[[localeData]].
    // 12. Let r be ResolveLocale( %DateTimeFormat%.[[availableLocales]], requestedLocales, opt, %DateTimeFormat%.[[relevantExtensionKeys]], localeData).
    const HashSet<String> availableLocales = exec.callee()->globalObject()->intlDateTimeFormatAvailableLocales();
    HashMap<String, String> resolved = resolveLocale(exec, availableLocales, requestedLocales, localeOpt, relevantExtensionKeys, WTF_ARRAY_LENGTH(relevantExtensionKeys), localeData);

    // 13. Set dateTimeFormat.[[locale]] to the value of r.[[locale]].
    m_locale = resolved.get(vm.propertyNames->locale.string());
    if (m_locale.isEmpty()) {
        throwTypeError(&exec, scope, ASCIILiteral("failed to initialize DateTimeFormat due to invalid locale"));
        return;
    }
    // 14. Set dateTimeFormat.[[calendar]] to the value of r.[[ca]].
    m_calendar = resolved.get(ASCIILiteral("ca"));
    // Switch to preferred aliases.
    if (m_calendar == "gregory")
        m_calendar = ASCIILiteral("gregorian");
    else if (m_calendar == "islamicc")
        m_calendar = ASCIILiteral("islamic-civil");
    else if (m_calendar == "ethioaa")
        m_calendar = ASCIILiteral("ethiopic-amete-alem");
    // 15. Set dateTimeFormat.[[numberingSystem]] to the value of r.[[nu]].
    m_numberingSystem = resolved.get(ASCIILiteral("nu"));
    // 16. Let dataLocale be the value of r.[[dataLocale]].
    String dataLocale = resolved.get(ASCIILiteral("dataLocale"));

    // 17. Let tz be Get(options, "timeZone").
    JSValue tzValue = options->get(&exec, vm.propertyNames->timeZone);
    // 18. ReturnIfAbrupt(tz).
    RETURN_IF_EXCEPTION(scope, void());

    // 19. If tz is not undefined, then
    String tz;
    if (!tzValue.isUndefined()) {
        // a. Let tz be ToString(tz).
        String originalTz = tzValue.toWTFString(&exec);
        // b. ReturnIfAbrupt(tz).
        RETURN_IF_EXCEPTION(scope, void());
        // c. If the result of IsValidTimeZoneName(tz) is false, then i. Throw a RangeError exception.
        // d. Let tz be CanonicalizeTimeZoneName(tz).
        tz = canonicalizeTimeZoneName(originalTz);
        if (tz.isNull()) {
            throwRangeError(&exec, scope, String::format("invalid time zone: %s", originalTz.utf8().data()));
            return;
        }
    } else {
        // 20. Else,
        // a. Let tz be DefaultTimeZone().
        tz = defaultTimeZone();
    }

    // 21. Set dateTimeFormat.[[timeZone]] to tz.
    m_timeZone = tz;

    // 22. Let opt be a new Record.
    // Rather than building a record, build the skeleton pattern.
    StringBuilder skeletonBuilder;

    // 23. For each row of Table 3, except the header row, do:
    // a. Let prop be the name given in the Property column of the row.
    // b. Let value be GetOption(options, prop, "string", «the strings given in the Values column of the row», undefined).
    // c. ReturnIfAbrupt(value).
    // d. Set opt.[[<prop>]] to value.
    auto narrowShortLong = { "narrow", "short", "long" };
    auto twoDigitNumeric = { "2-digit", "numeric" };
    auto twoDigitNumericNarrowShortLong = { "2-digit", "numeric", "narrow", "short", "long" };
    auto shortLong = { "short", "long" };

    String weekday = intlStringOption(exec, options, vm.propertyNames->weekday, narrowShortLong, "weekday must be \"narrow\", \"short\", or \"long\"", nullptr);
    RETURN_IF_EXCEPTION(scope, void());
    if (!weekday.isNull()) {
        if (weekday == "narrow")
            skeletonBuilder.appendLiteral("EEEEE");
        else if (weekday == "short")
            skeletonBuilder.appendLiteral("EEE");
        else if (weekday == "long")
            skeletonBuilder.appendLiteral("EEEE");
    }

    String era = intlStringOption(exec, options, vm.propertyNames->era, narrowShortLong, "era must be \"narrow\", \"short\", or \"long\"", nullptr);
    RETURN_IF_EXCEPTION(scope, void());
    if (!era.isNull()) {
        if (era == "narrow")
            skeletonBuilder.appendLiteral("GGGGG");
        else if (era == "short")
            skeletonBuilder.appendLiteral("GGG");
        else if (era == "long")
            skeletonBuilder.appendLiteral("GGGG");
    }

    String year = intlStringOption(exec, options, vm.propertyNames->year, twoDigitNumeric, "year must be \"2-digit\" or \"numeric\"", nullptr);
    RETURN_IF_EXCEPTION(scope, void());
    if (!year.isNull()) {
        if (year == "2-digit")
            skeletonBuilder.appendLiteral("yy");
        else if (year == "numeric")
            skeletonBuilder.append('y');
    }

    String month = intlStringOption(exec, options, vm.propertyNames->month, twoDigitNumericNarrowShortLong, "month must be \"2-digit\", \"numeric\", \"narrow\", \"short\", or \"long\"", nullptr);
    RETURN_IF_EXCEPTION(scope, void());
    if (!month.isNull()) {
        if (month == "2-digit")
            skeletonBuilder.appendLiteral("MM");
        else if (month == "numeric")
            skeletonBuilder.append('M');
        else if (month == "narrow")
            skeletonBuilder.appendLiteral("MMMMM");
        else if (month == "short")
            skeletonBuilder.appendLiteral("MMM");
        else if (month == "long")
            skeletonBuilder.appendLiteral("MMMM");
    }

    String day = intlStringOption(exec, options, vm.propertyNames->day, twoDigitNumeric, "day must be \"2-digit\" or \"numeric\"", nullptr);
    RETURN_IF_EXCEPTION(scope, void());
    if (!day.isNull()) {
        if (day == "2-digit")
            skeletonBuilder.appendLiteral("dd");
        else if (day == "numeric")
            skeletonBuilder.append('d');
    }

    String hour = intlStringOption(exec, options, vm.propertyNames->hour, twoDigitNumeric, "hour must be \"2-digit\" or \"numeric\"", nullptr);
    RETURN_IF_EXCEPTION(scope, void());

    // We need hour12 to make the hour skeleton pattern decision, so do this early.
    // 32. Let hr12 be GetOption(options, "hour12", "boolean", undefined, undefined).
    bool isHour12Undefined;
    bool hr12 = intlBooleanOption(exec, options, vm.propertyNames->hour12, isHour12Undefined);
    // 33. ReturnIfAbrupt(hr12).
    RETURN_IF_EXCEPTION(scope, void());

    if (!hour.isNull()) {
        if (isHour12Undefined) {
            if (hour == "2-digit")
                skeletonBuilder.appendLiteral("jj");
            else if (hour == "numeric")
                skeletonBuilder.append('j');
        } else if (hr12) {
            if (hour == "2-digit")
                skeletonBuilder.appendLiteral("hh");
            else if (hour == "numeric")
                skeletonBuilder.append('h');
        } else {
            if (hour == "2-digit")
                skeletonBuilder.appendLiteral("HH");
            else if (hour == "numeric")
                skeletonBuilder.append('H');
        }
    }

    String minute = intlStringOption(exec, options, vm.propertyNames->minute, twoDigitNumeric, "minute must be \"2-digit\" or \"numeric\"", nullptr);
    RETURN_IF_EXCEPTION(scope, void());
    if (!minute.isNull()) {
        if (minute == "2-digit")
            skeletonBuilder.appendLiteral("mm");
        else if (minute == "numeric")
            skeletonBuilder.append('m');
    }

    String second = intlStringOption(exec, options, vm.propertyNames->second, twoDigitNumeric, "second must be \"2-digit\" or \"numeric\"", nullptr);
    RETURN_IF_EXCEPTION(scope, void());
    if (!second.isNull()) {
        if (second == "2-digit")
            skeletonBuilder.appendLiteral("ss");
        else if (second == "numeric")
            skeletonBuilder.append('s');
    }

    String timeZoneName = intlStringOption(exec, options, vm.propertyNames->timeZoneName, shortLong, "timeZoneName must be \"short\" or \"long\"", nullptr);
    RETURN_IF_EXCEPTION(scope, void());
    if (!timeZoneName.isNull()) {
        if (timeZoneName == "short")
            skeletonBuilder.append('z');
        else if (timeZoneName == "long")
            skeletonBuilder.appendLiteral("zzzz");
    }

    // 24. Let dataLocaleData be Get(localeData, dataLocale).
    // 25. Let formats be Get(dataLocaleData, "formats").
    // 26. Let matcher be GetOption(options, "formatMatcher", "string", «"basic", "best fit"», "best fit").
    intlStringOption(exec, options, vm.propertyNames->formatMatcher, { "basic", "best fit" }, "formatMatcher must be either \"basic\" or \"best fit\"", "best fit");
    // 27. ReturnIfAbrupt(matcher).
    RETURN_IF_EXCEPTION(scope, void());

    // Always use ICU date format generator, rather than our own pattern list and matcher.
    // Covers steps 28-36.
    UErrorCode status = U_ZERO_ERROR;
    UDateTimePatternGenerator* generator = udatpg_open(dataLocale.utf8().data(), &status);
    if (U_FAILURE(status)) {
        throwTypeError(&exec, scope, ASCIILiteral("failed to initialize DateTimeFormat"));
        return;
    }

    String skeleton = skeletonBuilder.toString();
    StringView skeletonView(skeleton);
    Vector<UChar, 32> patternBuffer(32);
    status = U_ZERO_ERROR;
    auto patternLength = udatpg_getBestPattern(generator, skeletonView.upconvertedCharacters(), skeletonView.length(), patternBuffer.data(), patternBuffer.size(), &status);
    if (status == U_BUFFER_OVERFLOW_ERROR) {
        status = U_ZERO_ERROR;
        patternBuffer.grow(patternLength);
        udatpg_getBestPattern(generator, skeletonView.upconvertedCharacters(), skeletonView.length(), patternBuffer.data(), patternLength, &status);
    }
    udatpg_close(generator);
    if (U_FAILURE(status)) {
        throwTypeError(&exec, scope, ASCIILiteral("failed to initialize DateTimeFormat"));
        return;
    }

    StringView pattern(patternBuffer.data(), patternLength);
    setFormatsFromPattern(pattern);

    status = U_ZERO_ERROR;
    StringView timeZoneView(m_timeZone);
    m_dateFormat = std::unique_ptr<UDateFormat, UDateFormatDeleter>(udat_open(UDAT_PATTERN, UDAT_PATTERN, m_locale.utf8().data(), timeZoneView.upconvertedCharacters(), timeZoneView.length(), pattern.upconvertedCharacters(), pattern.length(), &status));
    if (U_FAILURE(status)) {
        throwTypeError(&exec, scope, ASCIILiteral("failed to initialize DateTimeFormat"));
        return;
    }

    // 37. Set dateTimeFormat.[[boundFormat]] to undefined.
    // Already undefined.

    // 38. Set dateTimeFormat.[[initializedDateTimeFormat]] to true.
    m_initializedDateTimeFormat = true;

    // 39. Return dateTimeFormat.
}
Esempio n. 10
0
namespace WebCore {

typedef std::tuple<WTF::String, WTF::String> clientCertificate;
static HashMap<String, ListHashSet<String>> allowedHosts;
static HashMap<String, clientCertificate> allowedClientHosts;

void allowsAnyHTTPSCertificateHosts(const String& host)
{
    ListHashSet<String> certificates;
    allowedHosts.set(host, certificates);
}

void addAllowedClientCertificate(const String& host, const String& certificate, const String& key)
{
    clientCertificate clientInfo(certificate, key);
    allowedClientHosts.set(host.lower(), clientInfo);
}

void setSSLClientCertificate(ResourceHandle* handle)
{
    String host = handle->firstRequest().url().host();
    HashMap<String, clientCertificate>::iterator it = allowedClientHosts.find(host.lower());
    if (it == allowedClientHosts.end())
        return;

    ResourceHandleInternal* d = handle->getInternal();
    clientCertificate clientInfo = it->value;
    curl_easy_setopt(d->m_handle, CURLOPT_SSLCERT, std::get<0>(clientInfo).utf8().data());
    curl_easy_setopt(d->m_handle, CURLOPT_SSLCERTTYPE, "P12");
    curl_easy_setopt(d->m_handle, CURLOPT_SSLCERTPASSWD, std::get<1>(clientInfo).utf8().data());
}

bool sslIgnoreHTTPSCertificate(const String& host, const ListHashSet<String>& certificates)
{
    HashMap<String, ListHashSet<String>>::iterator it = allowedHosts.find(host);
    if (it != allowedHosts.end()) {
        if ((it->value).isEmpty()) {
            it->value = certificates;
            return true;
        }
        if (certificates.size() != it->value.size())
            return false;
        ListHashSet<String>::const_iterator certsIter = certificates.begin();
        ListHashSet<String>::iterator valueIter = (it->value).begin();
        for (; valueIter != (it->value).end(); ++valueIter, ++certsIter) {
            if (*certsIter != *valueIter)
                return false;
        }
        return true;
    }
    return false;
}

unsigned sslCertificateFlag(const unsigned& sslError)
{
    switch (sslError) {
    case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT : // the issuer certificate could not be found: this occurs if the issuer certificate of an untrusted certificate cannot be found.
    case X509_V_ERR_UNABLE_TO_GET_CRL : // the CRL of a certificate could not be found.
    case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY : // the issuer certificate of a locally looked up certificate could not be found. This normally means the list of trusted certificates is not complete.
        return SSL_CERTIFICATE_UNKNOWN_CA;
    case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE : // the certificate signature could not be decrypted. This means that the actual signature value could not be determined rather than it not matching the expected value, this is only meaningful for RSA keys.
    case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE : // the CRL signature could not be decrypted: this means that the actual signature value could not be determined rather than it not matching the expected value. Unused.
    case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY : // the public key in the certificate SubjectPublicKeyInfo could not be read.
    case X509_V_ERR_CERT_SIGNATURE_FAILURE : // the signature of the certificate is invalid.
    case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT : // the passed certificate is self signed and the same certificate cannot be found in the list of trusted certificates.
    case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN : // the certificate chain could be built up using the untrusted certificates but the root could not be found locally.
    case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE : // no signatures could be verified because the chain contains only one certificate and it is not self signed.
    case X509_V_ERR_INVALID_PURPOSE : // the supplied certificate cannot be used for the specified purpose.
    case X509_V_ERR_CERT_UNTRUSTED : // the root CA is not marked as trusted for the specified purpose.
    case X509_V_ERR_CERT_REJECTED : // the root CA is marked to reject the specified purpose.
    case X509_V_ERR_NO_EXPLICIT_POLICY : // the verification flags were set to require and explicit policy but none was present.
    case X509_V_ERR_DIFFERENT_CRL_SCOPE : // the only CRLs that could be found did not match the scope of the certificate.
        return SSL_CERTIFICATE_INSECURE;
    case X509_V_ERR_CERT_NOT_YET_VALID : // the certificate is not yet valid: the notBefore date is after the current time.
    case X509_V_ERR_CRL_NOT_YET_VALID : // the CRL is not yet valid.
        return SSL_CERTIFICATE_NOT_ACTIVATED;
    case X509_V_ERR_CERT_HAS_EXPIRED : // the certificate has expired: that is the notAfter date is before the current time.
    case X509_V_ERR_CRL_HAS_EXPIRED : // the CRL has expired.
        return SSL_CERTIFICATE_EXPIRED;
    case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD : // the certificate notBefore field contains an invalid time.
    case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD : // the certificate notAfter field contains an invalid time.
    case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD : // the CRL lastUpdate field contains an invalid time.
    case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD : // the CRL nextUpdate field contains an invalid time.
    case X509_V_ERR_OUT_OF_MEM : // an error occurred trying to allocate memory. This should never happen.
    case X509_V_ERR_CERT_CHAIN_TOO_LONG : // the certificate chain length is greater than the supplied maximum depth. Unused.
    case X509_V_ERR_PATH_LENGTH_EXCEEDED : // the basicConstraints pathlength parameter has been exceeded.
    case X509_V_ERR_INVALID_EXTENSION : // a certificate extension had an invalid value (for example an incorrect encoding) or some value inconsistent with other extensions.
    case X509_V_ERR_INVALID_POLICY_EXTENSION : // a certificate policies extension had an invalid value (for example an incorrect encoding) or some value inconsistent with other extensions. This error only occurs if policy processing is enabled.
    case X509_V_ERR_UNSUPPORTED_EXTENSION_FEATURE : // some feature of a certificate extension is not supported. Unused.
    case X509_V_ERR_PERMITTED_VIOLATION : // a name constraint violation occured in the permitted subtrees.
    case X509_V_ERR_EXCLUDED_VIOLATION : // a name constraint violation occured in the excluded subtrees.
    case X509_V_ERR_SUBTREE_MINMAX : // a certificate name constraints extension included a minimum or maximum field: this is not supported.
    case X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE : // an unsupported name constraint type was encountered. OpenSSL currently only supports directory name, DNS name, email and URI types.
    case X509_V_ERR_UNSUPPORTED_CONSTRAINT_SYNTAX : // the format of the name constraint is not recognised: for example an email address format of a form not mentioned in RFC3280. This could be caused by a garbage extension or some new feature not currently supported.
    case X509_V_ERR_CRL_PATH_VALIDATION_ERROR : // an error occured when attempting to verify the CRL path. This error can only happen if extended CRL checking is enabled.
    case X509_V_ERR_APPLICATION_VERIFICATION : // an application specific error. This will never be returned unless explicitly set by an application.
        return SSL_CERTIFICATE_GENERIC_ERROR;
    case X509_V_ERR_CERT_REVOKED : // the certificate has been revoked.
        return SSL_CERTIFICATE_REVOKED;
    case X509_V_ERR_INVALID_CA : // a CA certificate is invalid. Either it is not a CA or its extensions are not consistent with the supplied purpose.
    case X509_V_ERR_SUBJECT_ISSUER_MISMATCH : // the current candidate issuer certificate was rejected because its subject name did not match the issuer name of the current certificate. This is only set if issuer check debugging is enabled it is used for status notification and is not in itself an error.
    case X509_V_ERR_AKID_SKID_MISMATCH : // the current candidate issuer certificate was rejected because its subject key identifier was present and did not match the authority key identifier current certificate. This is only set if issuer check debugging is enabled it is used for status notification and is not in itself an error.
    case X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH : // the current candidate issuer certificate was rejected because its issuer name and serial number was present and did not match the authority key identifier of the current certificate. This is only set if issuer check debugging is enabled it is used for status notification and is not in itself an error.
    case X509_V_ERR_KEYUSAGE_NO_CERTSIGN : // the current candidate issuer certificate was rejected because its keyUsage extension does not permit certificate signing. This is only set if issuer check debugging is enabled it is used for status notification and is not in itself an error.
        return SSL_CERTIFICATE_BAD_IDENTITY;
    default :
        return SSL_CERTIFICATE_GENERIC_ERROR;
    }
}

#if !PLATFORM(WIN)
// success of certificates extraction
bool pemData(X509_STORE_CTX* ctx, ListHashSet<String>& certificates)
{
    bool ok = true;
    STACK_OF(X509)* certs = X509_STORE_CTX_get1_chain(ctx);
    for (int i = 0; i < sk_X509_num(certs); i++) {
        X509* uCert = sk_X509_value(certs, i);
        BIO* bio = BIO_new(BIO_s_mem());
        int res = PEM_write_bio_X509(bio, uCert);
        if (!res) {
            ok = false;
            BIO_free(bio);
            break;
        }

        unsigned char* certificateData;
        long length = BIO_get_mem_data(bio, &certificateData);
        if (length < 0) {
            ok = false;
            BIO_free(bio);
            break;
        }

        certificateData[length] = '\0';
        String certificate = certificateData;
        certificates.add(certificate);
        BIO_free(bio);
    }
        sk_X509_pop_free(certs, X509_free);
        return ok;
}
#endif

static int certVerifyCallback(int ok, X509_STORE_CTX* ctx)
{
    // whether the verification of the certificate in question was passed (preverify_ok=1) or not (preverify_ok=0)

    unsigned err = X509_STORE_CTX_get_error(ctx);
    if (!err)
        return 1;

    SSL* ssl = reinterpret_cast<SSL*>(X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
    SSL_CTX* sslctx = SSL_get_SSL_CTX(ssl);
    ResourceHandle* job = reinterpret_cast<ResourceHandle*>(SSL_CTX_get_app_data(sslctx));
    String host = job->firstRequest().url().host();
    ResourceHandleInternal* d = job->getInternal();

    d->m_sslErrors = sslCertificateFlag(err);

#if PLATFORM(WIN)
    HashMap<String, ListHashSet<String>>::iterator it = allowedHosts.find(host);
    ok = (it != allowedHosts.end());
#else
    ListHashSet<String> certificates;
    if (!pemData(ctx, certificates))
        return 0;
    ok = sslIgnoreHTTPSCertificate(host.lower(), certificates);
#endif

    if (ok) {
        // if the host and the certificate are stored for the current handle that means is enabled,
        // so don't need to curl verifies the authenticity of the peer's certificate
        curl_easy_setopt(d->m_handle, CURLOPT_SSL_VERIFYPEER, false);
    }
    return ok;
}

static CURLcode sslctxfun(CURL* curl, void* sslctx, void* parm)
{
    SSL_CTX_set_app_data(reinterpret_cast<SSL_CTX*>(sslctx), parm);
    SSL_CTX_set_verify(reinterpret_cast<SSL_CTX*>(sslctx), SSL_VERIFY_PEER, certVerifyCallback);
    return CURLE_OK;
}

void setSSLVerifyOptions(ResourceHandle* handle)
{
    ResourceHandleInternal* d = handle->getInternal();
    curl_easy_setopt(d->m_handle, CURLOPT_SSL_CTX_DATA, handle);
    curl_easy_setopt(d->m_handle, CURLOPT_SSL_CTX_FUNCTION, sslctxfun);
}

}
Esempio n. 11
0
void allowsAnyHTTPSCertificateHosts(const String& host)
{
    ListHashSet<String> certificates;
    allowedHosts.set(host, certificates);
}
Esempio n. 12
0
void
MainForm::OnParsingCompleted(ArrayList &feedData) {
	AppResource *pAppResource = Application::GetInstance()->GetAppResource();
	if (feedData.GetCount() == 0) {
		// no service this day
		String emptyText;
		pAppResource->GetString("IDS_NOSERVICE", emptyText);
		__pListFood->SetTextOfEmptyList(emptyText);
	} else {
		IEnumerator *pEnum = feedData.GetEnumeratorN();
		HashMap *pItem = null;
		int mensaIndex = -1;
		String *currentMensa = null;
		String currencySymbol;
		pAppResource->GetString("IDS_CURRENCY", currencySymbol);
		String soldOut;
		pAppResource->GetString("IDS_SOLDOUT", soldOut);

		// iterate over items (meals) in feed
		while (pEnum->MoveNext() == E_SUCCESS) {
			pItem = (HashMap *)pEnum->GetCurrent();

			// check if mensa is already in the list (we assume the feed to be ordered)
			if (!currentMensa || !(static_cast<String *>(pItem->GetValue(*(new String("author")))))->Equals(*currentMensa, false)) {
				currentMensa = static_cast<String *>(pItem->GetValue(*(new String("author"))));
				mensaIndex++;
				// Create a main item of the ExpandableList
				CustomListItem* pMainItem = new CustomListItem();
				pMainItem->Construct(100);
				pMainItem->SetItemFormat(*__pMainItemFormat);
				pMainItem->SetElement(TEXT_ID, *(new String(*currentMensa)));
				// Add the item to the ExpandableList
				__pListFood->AddItem(*pMainItem, mensaIndex);
			}

			String *title = static_cast<String *>(pItem->GetValue(*(new String("title"))));
			title->Trim();
			String priceStudents;
			String priceStaff;
			int stringLength = title->GetLength();

			// Create a sub item of the ExpandableList
			CustomListItem *pSubItem = new CustomListItem();
			pSubItem->Construct(100);
			pSubItem->SetItemFormat(*__pSubItemFormat);

			// get prices
			if (title->EndsWith(L" EUR)")) {
				// parse price
				title->SubString(stringLength - 20, 5, priceStudents);
				priceStudents.Append(currencySymbol);
				title->SubString(stringLength - 9, 5, priceStaff);
				priceStaff.Append(currencySymbol);
				title->Remove(stringLength - 22, 22);

				pSubItem->SetElement(PRICESTUDENT_ID, priceStudents);
				pSubItem->SetElement(PRICESTAFF_ID, priceStaff);
			} else if (title->EndsWith(L"(ausverkauft)")) {
				// sold out
				title->Remove(stringLength - 14, 14);
				pSubItem->SetElement(REMARK_ID, soldOut);
			}

			pSubItem->SetElement(TEXT_ID, *title);

			// Add sub item to the ExpandableList
			__pListFood->AddSubItem(mensaIndex, *pSubItem);
		}

		// clean up
		delete pEnum;
	}

	__pListFood->RequestRedraw();
	__pListFood->ScrollToTop();

	StopLoadingAnimation();
}
Esempio n. 13
0
		static const char alphanum[] =
			"0123456789"
			"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
			"abcdefghijklmnopqrstuvwxyz";

		for (int i = 0; i < len; ++i) {
			s[i] = alphanum[rand() % (sizeof(alphanum) - 1)];
		}

		s[len] = 0;
	}
}

TEST_CASE("HashMap insert/remove testing", "[HashMap]")
{
	HashMap<int> map;

	map.insert("jorma", 2000);
	map.insert("jarmo", 2);
	map.insert("pentti", 666);
	map.insert("hahahaha", -24);
	map.insert("moi", 1);

	REQUIRE(map.getSize() == 5);

	char *str = (char*)malloc(15);

	for (unsigned i = 0; i < 3500; ++i)
	{
		helper::gen_random(str, 10);
		str[10] = '\n';
void DOMWindowExtensionBasic::updateExtensionStateRecord(WKBundleDOMWindowExtensionRef extension, ExtensionState state)
{
    int index = m_extensionToRecordMap.get(extension);
    m_extensionRecords[index].state = state;
}
Esempio n. 15
0
static bool decodeDataObject(ArgumentDecoder& decoder, RefPtr<DataObjectGtk>& dataObject)
{
    RefPtr<DataObjectGtk> data = DataObjectGtk::create();

    bool hasText;
    if (!decoder.decode(hasText))
        return false;
    if (hasText) {
        String text;
        if (!decoder.decode(text))
            return false;
        data->setText(text);
    }

    bool hasMarkup;
    if (!decoder.decode(hasMarkup))
        return false;
    if (hasMarkup) {
        String markup;
        if (!decoder.decode(markup))
            return false;
        data->setMarkup(markup);
    }

    bool hasURL;
    if (!decoder.decode(hasURL))
        return false;
    if (hasURL) {
        String url;
        if (!decoder.decode(url))
            return false;
        data->setURL(URL(URL(), url), String());
    }

    bool hasURIList;
    if (!decoder.decode(hasURIList))
        return false;
    if (hasURIList) {
        String uriList;
        if (!decoder.decode(uriList))
            return false;
        data->setURIList(uriList);
    }

    bool hasImage;
    if (!decoder.decode(hasImage))
        return false;
    if (hasImage) {
        GRefPtr<GdkPixbuf> image;
        if (!decodeImage(decoder, image))
            return false;
        data->setImage(image.get());
    }

    bool hasUnknownTypeData;
    if (!decoder.decode(hasUnknownTypeData))
        return false;
    if (hasUnknownTypeData) {
        HashMap<String, String> unknownTypes;
        if (!decoder.decode(unknownTypes))
            return false;

        auto end = unknownTypes.end();
        for (auto it = unknownTypes.begin(); it != end; ++it)
            data->setUnknownTypeData(it->key, it->value);
    }

    dataObject = data;

    return true;
}
/*! \brief  Get simple DOI identifier from full DOI content ID string.

    \param  contentID       input, full DOI contentID string.
    \param  doi             output, simple DOI identifier.

    \returns  Boolean indicating success or failure.
*/
bool OsmsOpenIPMPMessenger::GetDOIFromContentID(const std::string& contentID,
    std::string& doiID) {
  XMLDocument pIPMP_ContentId;
  if (pIPMP_ContentId.decode(contentID.data(), "IPMP_ContentIdentity") == false) {
    return false;
  }
  HashMap* identifier = pIPMP_ContentId.getDocList("Identifier");
  if (identifier == 0) {
    return false;
  }
  if (identifier->size() == 0) {
    identifier->clear();
    delete identifier;
    return false;
  }
  XMLDocument* node = (XMLDocument*)identifier->first();
  if (node == 0) {
    for (int j = 1; j < identifier->size(); j++) {
      node = (XMLDocument*)identifier->next();
      if (node != 0) delete node;
    }
    identifier->clear();
    delete identifier;
    return false;
  }
  char* identifierType = node->getString("IdentifierType");
  char* identifierValue = node->getString("IdentifierValue");
  if ((identifierType == 0) || (identifierValue == 0)) {
    delete node;
    for (int j = 1; j < identifier->size(); j++) {
      node = (XMLDocument*)identifier->next();
      if (node != 0) delete node;
    }
    identifier->clear();
    delete identifier;
    return false;
  }
  if (strcmp(identifierType, "DOI") == 0) {
    doiID = identifierValue;
    delete[] identifierType;
    delete[] identifierValue;
    delete node;
    for (int j = 1; j < identifier->size(); j++) {
      node = (XMLDocument*)identifier->next();
      if (node != 0) delete node;
    }
    identifier->clear();
    delete identifier;
    return true;
  }
  delete[] identifierType;
  delete[] identifierValue;
  delete node;

  for (int i = 1; i < identifier->size(); i++) {
    node = (XMLDocument*)identifier->next();
    if (node == 0) {
      for (int j = (i + 1); j < identifier->size(); j++) {
        node = (XMLDocument*)identifier->next();
        if (node != 0) delete node;
      }
      identifier->clear();
      delete identifier;
      return false;
    }
    char* identifierType = node->getString("IdentifierType");
    char* identifierValue = node->getString("IdentifierValue");
    if ((identifierType == 0) || (identifierValue == 0)) {
      delete node;
      for (int j = (i + 1); j < identifier->size(); j++) {
        node = (XMLDocument*)identifier->next();
        if (node != 0) delete node;
      }
      identifier->clear();
      delete identifier;
      return false;
    }
    if (strcmp(identifierType, "DOI") == 0) {
      doiID = identifierValue;
      delete[] identifierType;
      delete[] identifierValue;
      delete node;
      for (int j = (i + 1); j < identifier->size(); j++) {
        node = (XMLDocument*)identifier->next();
        if (node != 0) delete node;
      }
      identifier->clear();
      delete identifier;
      return true;
    }
    delete[] identifierType;
    delete[] identifierValue;
    delete node;
  }
  identifier->clear();
  delete identifier;
  return false;
}
Esempio n. 17
0
bool fixSSA(Procedure& proc)
{
    PhaseScope phaseScope(proc, "fixSSA");
    
    // Collect the stack "variables". If there aren't any, then we don't have anything to do.
    // That's a fairly common case.
    HashMap<StackSlotValue*, Type> stackVariable;
    for (Value* value : proc.values()) {
        if (StackSlotValue* stack = value->as<StackSlotValue>()) {
            if (stack->kind() == StackSlotKind::Anonymous)
                stackVariable.add(stack, Void);
        }
    }

    if (stackVariable.isEmpty())
        return false;

    // Make sure that we know how to optimize all of these. We only know how to handle Load and
    // Store on anonymous variables.
    for (Value* value : proc.values()) {
        auto reject = [&] (Value* value) {
            if (StackSlotValue* stack = value->as<StackSlotValue>())
                stackVariable.remove(stack);
        };
        
        auto handleAccess = [&] (Value* access, Type type) {
            StackSlotValue* stack = access->lastChild()->as<StackSlotValue>();
            if (!stack)
                return;
            
            if (value->as<MemoryValue>()->offset()) {
                stackVariable.remove(stack);
                return;
            }

            auto result = stackVariable.find(stack);
            if (result == stackVariable.end())
                return;
            if (result->value == Void) {
                result->value = type;
                return;
            }
            if (result->value == type)
                return;
            stackVariable.remove(result);
        };
        
        switch (value->opcode()) {
        case Load:
            // We're OK with loads from stack variables at an offset of zero.
            handleAccess(value, value->type());
            break;
        case Store:
            // We're OK with stores to stack variables, but not storing stack variables.
            reject(value->child(0));
            handleAccess(value, value->child(0)->type());
            break;
        default:
            for (Value* child : value->children())
                reject(child);
            break;
        }
    }

    Vector<StackSlotValue*> deadValues;
    for (auto& entry : stackVariable) {
        if (entry.value == Void)
            deadValues.append(entry.key);
    }

    for (StackSlotValue* deadValue : deadValues) {
        deadValue->replaceWithNop();
        stackVariable.remove(deadValue);
    }

    if (stackVariable.isEmpty())
        return false;

    // We know that we have variables to optimize, so do that now.
    breakCriticalEdges(proc);

    SSACalculator ssa(proc);

    // Create a SSACalculator::Variable for every stack variable.
    Vector<StackSlotValue*> variableToStack;
    HashMap<StackSlotValue*, SSACalculator::Variable*> stackToVariable;

    for (auto& entry : stackVariable) {
        StackSlotValue* stack = entry.key;
        SSACalculator::Variable* variable = ssa.newVariable();
        RELEASE_ASSERT(variable->index() == variableToStack.size());
        variableToStack.append(stack);
        stackToVariable.add(stack, variable);
    }

    // Create Defs for all of the stores to the stack variable.
    for (BasicBlock* block : proc) {
        for (Value* value : *block) {
            if (value->opcode() != Store)
                continue;

            StackSlotValue* stack = value->child(1)->as<StackSlotValue>();
            if (!stack)
                continue;

            if (SSACalculator::Variable* variable = stackToVariable.get(stack))
                ssa.newDef(variable, block, value->child(0));
        }
    }

    // Decide where Phis are to be inserted. This creates them but does not insert them.
    ssa.computePhis(
        [&] (SSACalculator::Variable* variable, BasicBlock* block) -> Value* {
            StackSlotValue* stack = variableToStack[variable->index()];
            Value* phi = proc.add<Value>(Phi, stackVariable.get(stack), stack->origin());
            if (verbose) {
                dataLog(
                    "Adding Phi for ", pointerDump(stack), " at ", *block, ": ",
                    deepDump(proc, phi), "\n");
            }
            return phi;
        });

    // Now perform the conversion.
    InsertionSet insertionSet(proc);
    HashMap<StackSlotValue*, Value*> mapping;
    for (BasicBlock* block : proc.blocksInPreOrder()) {
        mapping.clear();

        for (auto& entry : stackToVariable) {
            StackSlotValue* stack = entry.key;
            SSACalculator::Variable* variable = entry.value;

            SSACalculator::Def* def = ssa.reachingDefAtHead(block, variable);
            if (def)
                mapping.set(stack, def->value());
        }

        for (SSACalculator::Def* phiDef : ssa.phisForBlock(block)) {
            StackSlotValue* stack = variableToStack[phiDef->variable()->index()];

            insertionSet.insertValue(0, phiDef->value());
            mapping.set(stack, phiDef->value());
        }

        for (unsigned valueIndex = 0; valueIndex < block->size(); ++valueIndex) {
            Value* value = block->at(valueIndex);
            value->performSubstitution();

            switch (value->opcode()) {
            case Load: {
                if (StackSlotValue* stack = value->child(0)->as<StackSlotValue>()) {
                    if (Value* replacement = mapping.get(stack))
                        value->replaceWithIdentity(replacement);
                }
                break;
            }
                
            case Store: {
                if (StackSlotValue* stack = value->child(1)->as<StackSlotValue>()) {
                    if (stackToVariable.contains(stack)) {
                        mapping.set(stack, value->child(0));
                        value->replaceWithNop();
                    }
                }
                break;
            }

            default:
                break;
            }
        }

        unsigned upsilonInsertionPoint = block->size() - 1;
        Origin upsilonOrigin = block->last()->origin();
        for (BasicBlock* successorBlock : block->successorBlocks()) {
            for (SSACalculator::Def* phiDef : ssa.phisForBlock(successorBlock)) {
                Value* phi = phiDef->value();
                SSACalculator::Variable* variable = phiDef->variable();
                StackSlotValue* stack = variableToStack[variable->index()];

                Value* mappedValue = mapping.get(stack);
                if (verbose) {
                    dataLog(
                        "Mapped value for ", *stack, " with successor Phi ", *phi, " at end of ",
                        *block, ": ", pointerDump(mappedValue), "\n");
                }
                
                if (!mappedValue)
                    mappedValue = insertionSet.insertBottom(upsilonInsertionPoint, phi);
                
                insertionSet.insert<UpsilonValue>(
                    upsilonInsertionPoint, upsilonOrigin, mappedValue, phi);
            }
        }

        insertionSet.execute(block);
    }

    // Finally, kill the stack slots.
    for (StackSlotValue* stack : variableToStack)
        stack->replaceWithNop();

    if (verbose) {
        dataLog("B3 after SSA conversion:\n");
        dataLog(proc);
    }

    return true;
}
gpointer createHTMLElementWrapper(PassRefPtr<WebCore::HTMLElement> element)
{
    static HashMap<WTF::AtomicStringImpl*, CreateHTMLElementWrapperFunction> map;
    if (map.isEmpty()) {
       map.set(aTag.localName().impl(), createAnchorWrapper);
       map.set(appletTag.localName().impl(), createAppletWrapper);
#if ENABLE(VIDEO)
       map.set(audioTag.localName().impl(), createAudioWrapper);
       map.set(videoTag.localName().impl(), createVideoWrapper);
#endif
       map.set(areaTag.localName().impl(), createAreaWrapper);
       map.set(baseTag.localName().impl(), createBaseWrapper);
       map.set(basefontTag.localName().impl(), createBaseFontWrapper);
       map.set(blockquoteTag.localName().impl(), createQuoteWrapper);
       map.set(bodyTag.localName().impl(), createBodyWrapper);
       map.set(brTag.localName().impl(), createBRWrapper);
       map.set(buttonTag.localName().impl(), createButtonWrapper);
       map.set(canvasTag.localName().impl(), createCanvasWrapper);
       map.set(captionTag.localName().impl(), createTableCaptionWrapper);
       map.set(colTag.localName().impl(), createTableColWrapper);
       map.set(delTag.localName().impl(), createModWrapper);
       map.set(dirTag.localName().impl(), createDirectoryWrapper);
       map.set(divTag.localName().impl(), createDivWrapper);
       map.set(dlTag.localName().impl(), createDListWrapper);
       map.set(embedTag.localName().impl(), createEmbedWrapper);
       map.set(fieldsetTag.localName().impl(), createFieldSetWrapper);
       map.set(fontTag.localName().impl(), createFontWrapper);
       map.set(formTag.localName().impl(), createFormWrapper);
       map.set(frameTag.localName().impl(), createFrameWrapper);
       map.set(framesetTag.localName().impl(), createFrameSetWrapper);
       map.set(h1Tag.localName().impl(), createHeadingWrapper);
       map.set(headTag.localName().impl(), createHeadWrapper);
       map.set(hrTag.localName().impl(), createHRWrapper);
       map.set(htmlTag.localName().impl(), createHtmlWrapper);
       map.set(iframeTag.localName().impl(), createIFrameWrapper);
       map.set(imgTag.localName().impl(), createImageWrapper);
       map.set(inputTag.localName().impl(), createInputWrapper);
       map.set(isindexTag.localName().impl(), createIsIndexWrapper);
       map.set(labelTag.localName().impl(), createLabelWrapper);
       map.set(legendTag.localName().impl(), createLegendWrapper);
       map.set(liTag.localName().impl(), createLIWrapper);
       map.set(linkTag.localName().impl(), createLinkWrapper);
       map.set(mapTag.localName().impl(), createMapWrapper);
       map.set(marqueeTag.localName().impl(), createMarqueeWrapper);
       map.set(menuTag.localName().impl(), createMenuWrapper);
       map.set(metaTag.localName().impl(), createMetaWrapper);
       map.set(objectTag.localName().impl(), createObjectWrapper);
       map.set(olTag.localName().impl(), createOListWrapper);
       map.set(optgroupTag.localName().impl(), createOptGroupWrapper);
       map.set(optionTag.localName().impl(), createOptionWrapper);
       map.set(pTag.localName().impl(), createParagraphWrapper);
       map.set(paramTag.localName().impl(), createParamWrapper);
       map.set(preTag.localName().impl(), createPreWrapper);
       map.set(qTag.localName().impl(), createQuoteWrapper);
       map.set(scriptTag.localName().impl(), createScriptWrapper);
       map.set(selectTag.localName().impl(), createSelectWrapper);
       map.set(styleTag.localName().impl(), createStyleWrapper);
       map.set(tableTag.localName().impl(), createTableWrapper);
       map.set(tbodyTag.localName().impl(), createTableSectionWrapper);
       map.set(tdTag.localName().impl(), createTableCellWrapper);
       map.set(textareaTag.localName().impl(), createTextAreaWrapper);
       map.set(titleTag.localName().impl(), createTitleWrapper);
       map.set(trTag.localName().impl(), createTableRowWrapper);
       map.set(ulTag.localName().impl(), createUListWrapper);
       map.set(colgroupTag.localName().impl(), createTableColWrapper);
       map.set(h2Tag.localName().impl(), createHeadingWrapper);
       map.set(h3Tag.localName().impl(), createHeadingWrapper);
       map.set(h4Tag.localName().impl(), createHeadingWrapper);
       map.set(h5Tag.localName().impl(), createHeadingWrapper);
       map.set(h6Tag.localName().impl(), createHeadingWrapper);
       map.set(imageTag.localName().impl(), createImageWrapper);
       map.set(insTag.localName().impl(), createModWrapper);
       map.set(keygenTag.localName().impl(), createKeygenWrapper);
       map.set(listingTag.localName().impl(), createPreWrapper);
       map.set(tfootTag.localName().impl(), createTableSectionWrapper);
       map.set(thTag.localName().impl(), createTableCellWrapper);
       map.set(theadTag.localName().impl(), createTableSectionWrapper);
       map.set(xmpTag.localName().impl(), createPreWrapper);
    }

    CreateHTMLElementWrapperFunction createWrapperFunction =
        map.get(element->localName().impl());
    if (createWrapperFunction)
        return createWrapperFunction(element);
    return wrapHTMLElement(element.get());
}
Esempio n. 19
0
 void setPayloadData(const String& field, ByteArray data, int32_t offset, int32_t length) {
     fieldToData.put(field, newLucene<PayloadData>(0, data, offset, length));
 }
Esempio n. 20
0
HashMap * IMAPNamespace::serializable()
{
    HashMap * result = Object::serializable();
    result->setObjectForKey(MCSTR("items"), mItems->serializable());
    return result;
}
Esempio n. 21
0
static void resolveKeyframes(StyleResolver* resolver, Element* element, const RenderStyle& style, const AtomicString& name, TimingFunction* defaultTimingFunction,
    Vector<std::pair<KeyframeAnimationEffect::KeyframeVector, RefPtr<TimingFunction> > >& keyframesAndTimingFunctions)
{
    ASSERT(RuntimeEnabledFeatures::webAnimationsCSSEnabled());
    const StyleRuleKeyframes* keyframesRule = CSSAnimations::matchScopedKeyframesRule(resolver, element, name.impl());
    if (!keyframesRule)
        return;

    const Vector<RefPtr<StyleKeyframe> >& styleKeyframes = keyframesRule->keyframes();
    if (styleKeyframes.isEmpty())
        return;

    // Construct and populate the style for each keyframe
    PropertySet specifiedProperties;
    KeyframeAnimationEffect::KeyframeVector keyframes;
    HashMap<double, RefPtr<TimingFunction> > perKeyframeTimingFunctions;
    for (size_t i = 0; i < styleKeyframes.size(); ++i) {
        const StyleKeyframe* styleKeyframe = styleKeyframes[i].get();
        RefPtr<RenderStyle> keyframeStyle = resolver->styleForKeyframe(element, style, styleKeyframe, name);
        RefPtr<Keyframe> keyframe = Keyframe::create();
        const Vector<double>& offsets = styleKeyframe->keys();
        ASSERT(!offsets.isEmpty());
        keyframe->setOffset(offsets[0]);
        TimingFunction* timingFunction = defaultTimingFunction;
        const StylePropertySet* properties = styleKeyframe->properties();
        for (unsigned j = 0; j < properties->propertyCount(); j++) {
            CSSPropertyID property = properties->propertyAt(j).id();
            specifiedProperties.add(property);
            if (property == CSSPropertyWebkitAnimationTimingFunction || property == CSSPropertyAnimationTimingFunction)
                timingFunction = KeyframeValue::timingFunction(*keyframeStyle);
            else if (CSSAnimations::isAnimatableProperty(property))
                keyframe->setPropertyValue(property, CSSAnimatableValueFactory::create(property, *keyframeStyle).get());
        }
        keyframes.append(keyframe);
        // The last keyframe specified at a given offset is used.
        perKeyframeTimingFunctions.set(offsets[0], timingFunction);
        for (size_t j = 1; j < offsets.size(); ++j) {
            keyframes.append(keyframe->cloneWithOffset(offsets[j]));
            perKeyframeTimingFunctions.set(offsets[j], timingFunction);
        }
    }
    ASSERT(!keyframes.isEmpty());

    if (!perKeyframeTimingFunctions.contains(0))
        perKeyframeTimingFunctions.set(0, defaultTimingFunction);

    for (PropertySet::const_iterator iter = specifiedProperties.begin(); iter != specifiedProperties.end(); ++iter) {
        const CSSPropertyID property = *iter;
        ASSERT(property != CSSPropertyInvalid);
        blink::Platform::current()->histogramSparse("WebCore.Animation.CSSProperties", UseCounter::mapCSSPropertyIdToCSSSampleIdForHistogram(property));
    }

    // Remove duplicate keyframes. In CSS the last keyframe at a given offset takes priority.
    std::stable_sort(keyframes.begin(), keyframes.end(), Keyframe::compareOffsets);
    size_t targetIndex = 0;
    for (size_t i = 1; i < keyframes.size(); i++) {
        if (keyframes[i]->offset() != keyframes[targetIndex]->offset())
            targetIndex++;
        if (targetIndex != i)
            keyframes[targetIndex] = keyframes[i];
    }
    keyframes.shrink(targetIndex + 1);

    // Add 0% and 100% keyframes if absent.
    RefPtr<Keyframe> startKeyframe = keyframes[0];
    if (startKeyframe->offset()) {
        startKeyframe = Keyframe::create();
        startKeyframe->setOffset(0);
        keyframes.prepend(startKeyframe);
    }
    RefPtr<Keyframe> endKeyframe = keyframes[keyframes.size() - 1];
    if (endKeyframe->offset() != 1) {
        endKeyframe = Keyframe::create();
        endKeyframe->setOffset(1);
        keyframes.append(endKeyframe);
    }
    ASSERT(keyframes.size() >= 2);
    ASSERT(!keyframes.first()->offset());
    ASSERT(keyframes.last()->offset() == 1);

    // Snapshot current property values for 0% and 100% if missing.
    PropertySet allProperties;
    size_t numKeyframes = keyframes.size();
    for (size_t i = 0; i < numKeyframes; i++) {
        const PropertySet& keyframeProperties = keyframes[i]->properties();
        for (PropertySet::const_iterator iter = keyframeProperties.begin(); iter != keyframeProperties.end(); ++iter)
            allProperties.add(*iter);
    }
    const PropertySet& startKeyframeProperties = startKeyframe->properties();
    const PropertySet& endKeyframeProperties = endKeyframe->properties();
    bool missingStartValues = startKeyframeProperties.size() < allProperties.size();
    bool missingEndValues = endKeyframeProperties.size() < allProperties.size();
    if (missingStartValues || missingEndValues) {
        for (PropertySet::const_iterator iter = allProperties.begin(); iter != allProperties.end(); ++iter) {
            const CSSPropertyID property = *iter;
            bool startNeedsValue = missingStartValues && !startKeyframeProperties.contains(property);
            bool endNeedsValue = missingEndValues && !endKeyframeProperties.contains(property);
            if (!startNeedsValue && !endNeedsValue)
                continue;
            RefPtr<AnimatableValue> snapshotValue = CSSAnimatableValueFactory::create(property, style);
            if (startNeedsValue)
                startKeyframe->setPropertyValue(property, snapshotValue.get());
            if (endNeedsValue)
                endKeyframe->setPropertyValue(property, snapshotValue.get());
        }
    }
    ASSERT(startKeyframe->properties().size() == allProperties.size());
    ASSERT(endKeyframe->properties().size() == allProperties.size());

    // Determine how many keyframes specify each property. Note that this must
    // be done after we've filled in end keyframes.
    typedef HashCountedSet<CSSPropertyID> PropertyCountedSet;
    PropertyCountedSet propertyCounts;
    for (size_t i = 0; i < numKeyframes; ++i) {
        const PropertySet& properties = keyframes[i]->properties();
        for (PropertySet::const_iterator iter = properties.begin(); iter != properties.end(); ++iter)
            propertyCounts.add(*iter);
    }

    // Split keyframes into groups, where each group contains only keyframes
    // which specify all properties used in that group. Each group is animated
    // in a separate animation, to allow per-keyframe timing functions to be
    // applied correctly.
    for (PropertyCountedSet::const_iterator iter = propertyCounts.begin(); iter != propertyCounts.end(); ++iter) {
        const CSSPropertyID property = iter->key;
        const size_t count = iter->value;
        ASSERT(count <= numKeyframes);
        if (count == numKeyframes)
            continue;
        KeyframeAnimationEffect::KeyframeVector splitOutKeyframes;
        for (size_t i = 0; i < numKeyframes; i++) {
            Keyframe* keyframe = keyframes[i].get();
            if (!keyframe->properties().contains(property)) {
                ASSERT(i && i != numKeyframes - 1);
                continue;
            }
            RefPtr<Keyframe> clonedKeyframe = Keyframe::create();
            clonedKeyframe->setOffset(keyframe->offset());
            clonedKeyframe->setComposite(keyframe->composite());
            clonedKeyframe->setPropertyValue(property, keyframe->propertyValue(property));
            splitOutKeyframes.append(clonedKeyframe);
            // Note that it's OK if this keyframe ends up having no
            // properties. This can only happen when none of the properties
            // are specified in all keyframes, in which case we won't animate
            // anything with these keyframes.
            keyframe->clearPropertyValue(property);
        }
        ASSERT(!splitOutKeyframes.first()->offset());
        ASSERT(splitOutKeyframes.last()->offset() == 1);
#ifndef NDEBUG
        for (size_t j = 0; j < splitOutKeyframes.size(); ++j)
            ASSERT(splitOutKeyframes[j]->properties().size() == 1);
#endif
        keyframesAndTimingFunctions.append(std::make_pair(splitOutKeyframes, generateTimingFunction(splitOutKeyframes, perKeyframeTimingFunctions)));
    }

    unsigned numPropertiesSpecifiedInAllKeyframes = keyframes.first()->properties().size();
#ifndef NDEBUG
    for (size_t i = 1; i < numKeyframes; ++i)
        ASSERT(keyframes[i]->properties().size() == numPropertiesSpecifiedInAllKeyframes);
#endif

    // If the animation specifies any keyframes, we always provide at least one
    // vector of resolved keyframes, even if no properties are animated.
    if (numPropertiesSpecifiedInAllKeyframes || keyframesAndTimingFunctions.isEmpty())
        keyframesAndTimingFunctions.append(std::make_pair(keyframes, generateTimingFunction(keyframes, perKeyframeTimingFunctions)));
}
Esempio n. 22
0
FontData* CSSFontSelector::getFontData(const FontDescription& fontDescription, const AtomicString& familyName)
{
    if (m_fontFaces.isEmpty()) {
        if (familyName.startsWith("-webkit-"))
            return fontDataForGenericFamily(m_document, fontDescription, familyName);
        return 0;
    }

    String family = familyName.string();

    Vector<RefPtr<CSSFontFace> >* familyFontFaces = m_fontFaces.get(family);
    // If no face was found, then return 0 and let the OS come up with its best match for the name.
    if (!familyFontFaces || familyFontFaces->isEmpty()) {
        // If we were handed a generic family, but there was no match, go ahead and return the correct font based off our
        // settings.
        return fontDataForGenericFamily(m_document, fontDescription, familyName);
    }

    HashMap<unsigned, RefPtr<CSSSegmentedFontFace> >* segmentedFontFaceCache = m_fonts.get(family);
    if (!segmentedFontFaceCache) {
        segmentedFontFaceCache = new HashMap<unsigned, RefPtr<CSSSegmentedFontFace> >;
        m_fonts.set(family, segmentedFontFaceCache);
    }

    FontTraitsMask traitsMask = fontDescription.traitsMask();

    RefPtr<CSSSegmentedFontFace> face = segmentedFontFaceCache->get(traitsMask);

    if (!face) {
        face = CSSSegmentedFontFace::create(this);
        segmentedFontFaceCache->set(traitsMask, face);
        // Collect all matching faces and sort them in order of preference.
        Vector<CSSFontFace*, 32> candidateFontFaces;
        for (int i = familyFontFaces->size() - 1; i >= 0; --i) {
            CSSFontFace* candidate = familyFontFaces->at(i).get();
            unsigned candidateTraitsMask = candidate->traitsMask();
            if ((traitsMask & FontStyleNormalMask) && !(candidateTraitsMask & FontStyleNormalMask))
                continue;
            if ((traitsMask & FontVariantNormalMask) && !(candidateTraitsMask & FontVariantNormalMask))
                continue;
#if ENABLE(SVG_FONTS)
            // For SVG Fonts that specify that they only support the "normal" variant, we will assume they are incapable
            // of small-caps synthesis and just ignore the font face as a candidate.
            if (candidate->hasSVGFontFaceSource() && (traitsMask & FontVariantSmallCapsMask) && !(candidateTraitsMask & FontVariantSmallCapsMask))
                continue;
#endif
            candidateFontFaces.append(candidate);
        }

        if (Vector<RefPtr<CSSFontFace> >* familyLocallyInstalledFontFaces = m_locallyInstalledFontFaces.get(family)) {
            unsigned numLocallyInstalledFontFaces = familyLocallyInstalledFontFaces->size();
            for (unsigned i = 0; i < numLocallyInstalledFontFaces; ++i) {
                CSSFontFace* candidate = familyLocallyInstalledFontFaces->at(i).get();
                unsigned candidateTraitsMask = candidate->traitsMask();
                if ((traitsMask & FontStyleNormalMask) && !(candidateTraitsMask & FontStyleNormalMask))
                    continue;
                if ((traitsMask & FontVariantNormalMask) && !(candidateTraitsMask & FontVariantNormalMask))
                    continue;
                candidateFontFaces.append(candidate);
            }
        }

        desiredTraitsMaskForComparison = traitsMask;
        std::stable_sort(candidateFontFaces.begin(), candidateFontFaces.end(), compareFontFaces);
        unsigned numCandidates = candidateFontFaces.size();
        for (unsigned i = 0; i < numCandidates; ++i)
            face->appendFontFace(candidateFontFaces[i]);
    }

    // We have a face.  Ask it for a font data.  If it cannot produce one, it will fail, and the OS will take over.
    return face->getFontData(fontDescription);
}
static void addToDictionaryFromHashMap(MutableDictionary* dictionary, const HashMap<String, uint64_t>& map)
{
    HashMap<String, uint64_t>::const_iterator end = map.end();
    for (HashMap<String, uint64_t>::const_iterator it = map.begin(); it != end; ++it)
        dictionary->set(it->key, RefPtr<WebUInt64>(WebUInt64::create(it->value)).get());
}
Esempio n. 24
0
    void validate()
    {
        // NB. This code is not written for performance, since it is not intended to run
        // in release builds.
        
        // Validate that all local variables at the head of the root block are dead.
        BasicBlock* root = m_graph.m_blocks[0].get();
        for (unsigned i = 0; i < root->variablesAtHead.numberOfLocals(); ++i)
            V_EQUAL((static_cast<VirtualRegister>(i), 0), static_cast<Node*>(0), root->variablesAtHead.local(i));
        
        // Validate ref counts and uses.
        HashMap<Node*, unsigned> myRefCounts;
        for (BlockIndex blockIndex = 0; blockIndex < m_graph.m_blocks.size(); ++blockIndex) {
            BasicBlock* block = m_graph.m_blocks[blockIndex].get();
            if (!block || !block->isReachable)
                continue;
            for (size_t i = 0; i < block->numNodes(); ++i)
                myRefCounts.add(block->node(i), 0);
        }
        HashSet<Node*> acceptableNodes;
        for (BlockIndex blockIndex = 0; blockIndex < m_graph.m_blocks.size(); ++blockIndex) {
            BasicBlock* block = m_graph.m_blocks[blockIndex].get();
            if (!block || !block->isReachable)
                continue;
            for (size_t i = 0; i < block->numNodes(); ++i) {
                Node* node = block->node(i);
                acceptableNodes.add(node);
                if (!node->shouldGenerate())
                    continue;
                for (unsigned j = 0; j < m_graph.numChildren(node); ++j) {
                    // Phi children in LoadStore form are invalid.
                    if (m_graph.m_form == LoadStore && block->isPhiIndex(i))
                        continue;
                    
                    Edge edge = m_graph.child(node, j);
                    if (!edge)
                        continue;
                    
                    myRefCounts.find(edge.node())->value++;
                    
                    // Unless I'm a Flush, Phantom, GetLocal, or Phi, my children should hasResult().
                    switch (node->op()) {
                    case Flush:
                    case GetLocal:
                        VALIDATE((node, edge), edge->hasVariableAccessData());
                        VALIDATE((node, edge), edge->variableAccessData() == node->variableAccessData());
                        break;
                    case PhantomLocal:
                        VALIDATE((node, edge), edge->hasVariableAccessData());
                        VALIDATE((node, edge), edge->variableAccessData() == node->variableAccessData());
                        VALIDATE((node, edge), edge->op() != SetLocal);
                        break;
                    case Phi:
                        VALIDATE((node, edge), edge->hasVariableAccessData());
                        if (m_graph.m_unificationState == LocallyUnified)
                            break;
                        VALIDATE((node, edge), edge->variableAccessData() == node->variableAccessData());
                        break;
                    case Phantom:
                        switch (m_graph.m_form) {
                        case LoadStore:
                            if (j) {
                                VALIDATE((node, edge), edge->hasResult());
                                break;
                            }
                            switch (edge->op()) {
                            case Phi:
                            case SetArgument:
                            case SetLocal:
                                break;
                            default:
                                VALIDATE((node, edge), edge->hasResult());
                                break;
                            }
                            break;
                        case ThreadedCPS:
                            VALIDATE((node, edge), edge->hasResult());
                            break;
                        }
                        break;
                    default:
                        VALIDATE((node, edge), edge->hasResult());
                        break;
                    }
                }
            }
        }
        for (BlockIndex blockIndex = 0; blockIndex < m_graph.m_blocks.size(); ++blockIndex) {
            BasicBlock* block = m_graph.m_blocks[blockIndex].get();
            if (!block || !block->isReachable)
                continue;
            
            HashSet<Node*> phisInThisBlock;
            HashSet<Node*> nodesInThisBlock;
            
            for (size_t i = 0; i < block->numNodes(); ++i) {
                Node* node = block->node(i);
                nodesInThisBlock.add(node);
                if (block->isPhiIndex(i))
                    phisInThisBlock.add(node);
                if (m_graph.m_refCountState == ExactRefCount)
                    V_EQUAL((node), myRefCounts.get(node), node->adjustedRefCount());
                else
                    V_EQUAL((node), node->refCount(), 1);
                for (unsigned j = 0; j < m_graph.numChildren(node); ++j) {
                    Edge edge = m_graph.child(node, j);
                    if (!edge)
                        continue;
                    VALIDATE((node, edge), acceptableNodes.contains(edge.node()));
                }
            }
            
            for (size_t i = 0; i < block->phis.size(); ++i) {
                Node* node = block->phis[i];
                ASSERT(phisInThisBlock.contains(node));
                VALIDATE((node), node->op() == Phi);
                VirtualRegister local = node->local();
                for (unsigned j = 0; j < m_graph.numChildren(node); ++j) {
                    // Phi children in LoadStore form are invalid.
                    if (m_graph.m_form == LoadStore && block->isPhiIndex(i))
                        continue;
                    
                    Edge edge = m_graph.child(node, j);
                    if (!edge)
                        continue;
                    
                    VALIDATE(
                        (node, edge),
                        edge->op() == SetLocal
                        || edge->op() == SetArgument
                        || edge->op() == Flush
                        || edge->op() == Phi
                        || edge->op() == ZombieHint
                        || edge->op() == MovHint
                        || edge->op() == MovHintAndCheck);
                    
                    if (phisInThisBlock.contains(edge.node()))
                        continue;
                    
                    if (nodesInThisBlock.contains(edge.node())) {
                        VALIDATE(
                            (node, edge),
                            edge->op() == SetLocal
                            || edge->op() == ZombieHint
                            || edge->op() == MovHint
                            || edge->op() == MovHintAndCheck
                            || edge->op() == SetArgument
                            || edge->op() == Flush);
                        
                        continue;
                    }
                    
                    // There must exist a predecessor block that has this node index in
                    // its tail variables.
                    bool found = false;
                    for (unsigned k = 0; k < block->m_predecessors.size(); ++k) {
                        BasicBlock* prevBlock = m_graph.m_blocks[block->m_predecessors[k]].get();
                        VALIDATE((Block, block->m_predecessors[k]), prevBlock);
                        VALIDATE((Block, block->m_predecessors[k]), prevBlock->isReachable);
                        Node* prevNode = prevBlock->variablesAtTail.operand(local);
                        // If we have a Phi that is not referring to *this* block then all predecessors
                        // must have that local available.
                        VALIDATE((local, blockIndex, Block, block->m_predecessors[k]), prevNode);
                        switch (prevNode->op()) {
                        case GetLocal:
                        case Flush:
                        case PhantomLocal:
                            prevNode = prevNode->child1().node();
                            break;
                        default:
                            break;
                        }
                        if (node->shouldGenerate()) {
                            VALIDATE((local, block->m_predecessors[k], prevNode),
                                     prevNode->shouldGenerate());
                        }
                        VALIDATE(
                            (local, block->m_predecessors[k], prevNode),
                            prevNode->op() == SetLocal
                            || prevNode->op() == MovHint
                            || prevNode->op() == MovHintAndCheck
                            || prevNode->op() == ZombieHint
                            || prevNode->op() == SetArgument
                            || prevNode->op() == Phi);
                        if (prevNode == edge.node()) {
                            found = true;
                            break;
                        }
                        // At this point it cannot refer into this block.
                        VALIDATE((local, block->m_predecessors[k], prevNode), !prevBlock->isInBlock(edge.node()));
                    }
                    
                    VALIDATE((node, edge), found);
                }
            }
            
            Operands<size_t> getLocalPositions(
                block->variablesAtHead.numberOfArguments(),
                block->variablesAtHead.numberOfLocals());
            Operands<size_t> setLocalPositions(
                block->variablesAtHead.numberOfArguments(),
                block->variablesAtHead.numberOfLocals());
            
            for (size_t i = 0; i < block->variablesAtHead.numberOfArguments(); ++i) {
                VALIDATE((static_cast<VirtualRegister>(argumentToOperand(i)), blockIndex), !block->variablesAtHead.argument(i) || block->variablesAtHead.argument(i)->hasVariableAccessData());
                if (m_graph.m_form == ThreadedCPS)
                    VALIDATE((static_cast<VirtualRegister>(argumentToOperand(i)), blockIndex), !block->variablesAtTail.argument(i) || block->variablesAtTail.argument(i)->hasVariableAccessData());
                
                getLocalPositions.argument(i) = notSet;
                setLocalPositions.argument(i) = notSet;
            }
            for (size_t i = 0; i < block->variablesAtHead.numberOfLocals(); ++i) {
                VALIDATE((static_cast<VirtualRegister>(i), blockIndex), !block->variablesAtHead.local(i) || block->variablesAtHead.local(i)->hasVariableAccessData());
                if (m_graph.m_form == ThreadedCPS)
                    VALIDATE((static_cast<VirtualRegister>(i), blockIndex), !block->variablesAtTail.local(i) || block->variablesAtTail.local(i)->hasVariableAccessData());

                getLocalPositions.local(i) = notSet;
                setLocalPositions.local(i) = notSet;
            }
            
            for (size_t i = 0; i < block->size(); ++i) {
                Node* node = block->at(i);
                ASSERT(nodesInThisBlock.contains(node));
                VALIDATE((node), node->op() != Phi);
                for (unsigned j = 0; j < m_graph.numChildren(node); ++j) {
                    Edge edge = m_graph.child(node, j);
                    if (!edge)
                        continue;
                    VALIDATE((node, edge), nodesInThisBlock.contains(edge.node()));
                    switch (node->op()) {
                    case PhantomLocal:
                    case GetLocal:
                    case Flush:
                        break;
                    case Phantom:
                        if (m_graph.m_form == LoadStore && !j)
                            break;
                    default:
                        VALIDATE((node, edge), !phisInThisBlock.contains(edge.node()));
                        break;
                    }
                }
                
                if (!node->shouldGenerate())
                    continue;
                switch (node->op()) {
                case GetLocal:
                    if (node->variableAccessData()->isCaptured())
                        break;
                    // Ignore GetLocal's that we know to be dead, but that the graph
                    // doesn't yet know to be dead.
                    if (!myRefCounts.get(node))
                        break;
                    if (m_graph.m_form == ThreadedCPS)
                        VALIDATE((node, blockIndex), getLocalPositions.operand(node->local()) == notSet);
                    getLocalPositions.operand(node->local()) = i;
                    break;
                case SetLocal:
                    if (node->variableAccessData()->isCaptured())
                        break;
                    // Only record the first SetLocal. There may be multiple SetLocals
                    // because of flushing.
                    if (setLocalPositions.operand(node->local()) != notSet)
                        break;
                    setLocalPositions.operand(node->local()) = i;
                    break;
                default:
                    break;
                }
            }
            
            if (m_graph.m_form == LoadStore)
                continue;
            
            for (size_t i = 0; i < block->variablesAtHead.numberOfArguments(); ++i) {
                checkOperand(
                    blockIndex, getLocalPositions, setLocalPositions, argumentToOperand(i));
            }
            for (size_t i = 0; i < block->variablesAtHead.numberOfLocals(); ++i) {
                checkOperand(
                    blockIndex, getLocalPositions, setLocalPositions, i);
            }
        }
    }
Esempio n. 25
0
String MIMETypeRegistry::getMIMETypeForExtension(const String &ext)
{
    if (ext.isEmpty())
        return String();

    static HashMap<String, String> mimetypeMap;
    if (mimetypeMap.isEmpty()) {
        //fill with initial values
        mimetypeMap.add("txt", "text/plain");
        mimetypeMap.add("pdf", "application/pdf");
        mimetypeMap.add("ps", "application/postscript");
        mimetypeMap.add("html", "text/html");
        mimetypeMap.add("htm", "text/html");
        mimetypeMap.add("xml", "text/xml");
        mimetypeMap.add("xsl", "text/xsl");
        mimetypeMap.add("js", "application/x-javascript");
        mimetypeMap.add("xhtml", "application/xhtml+xml");
        mimetypeMap.add("rss", "application/rss+xml");
        mimetypeMap.add("webarchive", "application/x-webarchive");
        mimetypeMap.add("svg", "image/svg+xml");
        mimetypeMap.add("svgz", "image/svg+xml");
        mimetypeMap.add("jpg", "image/jpeg");
        mimetypeMap.add("jpeg", "image/jpeg");
        mimetypeMap.add("png", "image/png");
        mimetypeMap.add("tif", "image/tiff");
        mimetypeMap.add("tiff", "image/tiff");
        mimetypeMap.add("ico", "image/ico");
        mimetypeMap.add("cur", "image/ico");
        mimetypeMap.add("bmp", "image/bmp");
    }
    String result = mimetypeMap.get(ext);
    if (result.isEmpty()) {
        result = mimeTypeForExtension(ext);
        if (!result.isEmpty())
            mimetypeMap.add(ext, result);
    }
    return result;
}
Esempio n. 26
0
void SamplingTool::dump(ExecState* exec)
{
    // Tidies up SunSpider output by removing short scripts - such a small number of samples would likely not be useful anyhow.
    if (m_sampleCount < 10)
        return;
    
    // (1) Build and sort 'opcodeSampleInfo' array.

    OpcodeSampleInfo opcodeSampleInfo[numOpcodeIDs];
    for (int i = 0; i < numOpcodeIDs; ++i) {
        opcodeSampleInfo[i].opcode = static_cast<OpcodeID>(i);
        opcodeSampleInfo[i].count = m_opcodeSamples[i];
        opcodeSampleInfo[i].countInCTIFunctions = m_opcodeSamplesInCTIFunctions[i];
    }

    qsort(opcodeSampleInfo, numOpcodeIDs, sizeof(OpcodeSampleInfo), compareOpcodeIndicesSampling);

    // (2) Print Opcode sampling results.

    printf("\nBytecode samples [*]\n");
    printf("                             sample   %% of       %% of     |   cti     cti %%\n");
    printf("opcode                       count     VM        total    |  count   of self\n");
    printf("-------------------------------------------------------   |  ----------------\n");

    for (int i = 0; i < numOpcodeIDs; ++i) {
        long long count = opcodeSampleInfo[i].count;
        if (!count)
            continue;

        OpcodeID opcodeID = opcodeSampleInfo[i].opcode;
        
        const char* opcodeName = opcodeNames[opcodeID];
        const char* opcodePadding = padOpcodeName(opcodeID, 28);
        double percentOfVM = (static_cast<double>(count) * 100) / m_opcodeSampleCount;
        double percentOfTotal = (static_cast<double>(count) * 100) / m_sampleCount;
        long long countInCTIFunctions = opcodeSampleInfo[i].countInCTIFunctions;
        double percentInCTIFunctions = (static_cast<double>(countInCTIFunctions) * 100) / count;
        fprintf(stdout, "%s:%s%-6lld %.3f%%\t%.3f%%\t  |   %-6lld %.3f%%\n", opcodeName, opcodePadding, count, percentOfVM, percentOfTotal, countInCTIFunctions, percentInCTIFunctions);
    }
    
    printf("\n[*] Samples inside host code are not charged to any Bytecode.\n\n");
    printf("\tSamples inside VM:\t\t%lld / %lld (%.3f%%)\n", m_opcodeSampleCount, m_sampleCount, (static_cast<double>(m_opcodeSampleCount) * 100) / m_sampleCount);
    printf("\tSamples inside host code:\t%lld / %lld (%.3f%%)\n\n", m_sampleCount - m_opcodeSampleCount, m_sampleCount, (static_cast<double>(m_sampleCount - m_opcodeSampleCount) * 100) / m_sampleCount);
    printf("\tsample count:\tsamples inside this opcode\n");
    printf("\t%% of VM:\tsample count / all opcode samples\n");
    printf("\t%% of total:\tsample count / all samples\n");
    printf("\t--------------\n");
    printf("\tcti count:\tsamples inside a CTI function called by this opcode\n");
    printf("\tcti %% of self:\tcti count / sample count\n");
    
#if ENABLE(CODEBLOCK_SAMPLING)

    // (3) Build and sort 'codeBlockSamples' array.

    int scopeCount = m_scopeSampleMap->size();
    Vector<ScriptSampleRecord*> codeBlockSamples(scopeCount);
    ScriptSampleRecordMap::iterator iter = m_scopeSampleMap->begin();
    for (int i = 0; i < scopeCount; ++i, ++iter)
        codeBlockSamples[i] = iter->second;

    qsort(codeBlockSamples.begin(), scopeCount, sizeof(ScriptSampleRecord*), compareScriptSampleRecords);

    // (4) Print data from 'codeBlockSamples' array.

    printf("\nCodeBlock samples\n\n"); 

    for (int i = 0; i < scopeCount; ++i) {
        ScriptSampleRecord* record = codeBlockSamples[i];
        CodeBlock* codeBlock = record->m_codeBlock;

        double blockPercent = (record->m_sampleCount * 100.0) / m_sampleCount;

        if (blockPercent >= 1) {
            //Instruction* code = codeBlock->instructions().begin();
            printf("#%d: %s:%d: %d / %lld (%.3f%%)\n", i + 1, record->m_executable->sourceURL().ascii(), codeBlock->lineNumberForBytecodeOffset(exec, 0), record->m_sampleCount, m_sampleCount, blockPercent);
            if (i < 10) {
                HashMap<unsigned,unsigned> lineCounts;
                codeBlock->dump(exec);

                printf("    Opcode and line number samples [*]\n\n");
                for (unsigned op = 0; op < record->m_size; ++op) {
                    int count = record->m_samples[op];
                    if (count) {
                        printf("    [% 4d] has sample count: % 4d\n", op, count);
                        unsigned line = codeBlock->lineNumberForBytecodeOffset(exec, op);
                        lineCounts.set(line, (lineCounts.contains(line) ? lineCounts.get(line) : 0) + count);
                    }
                }
                printf("\n");

                int linesCount = lineCounts.size();
                Vector<LineCountInfo> lineCountInfo(linesCount);
                int lineno = 0;
                for (HashMap<unsigned,unsigned>::iterator iter = lineCounts.begin(); iter != lineCounts.end(); ++iter, ++lineno) {
                    lineCountInfo[lineno].line = iter->first;
                    lineCountInfo[lineno].count = iter->second;
                }

                qsort(lineCountInfo.begin(), linesCount, sizeof(LineCountInfo), compareLineCountInfoSampling);

                for (lineno = 0; lineno < linesCount; ++lineno) {
                    printf("    Line #%d has sample count %d.\n", lineCountInfo[lineno].line, lineCountInfo[lineno].count);
                }
                printf("\n");
                printf("    [*] Samples inside host code are charged to the calling Bytecode.\n");
                printf("        Samples on a call / return boundary are not charged to a specific opcode or line.\n\n");
                printf("            Samples on a call / return boundary: %d / %d (%.3f%%)\n\n", record->m_sampleCount - record->m_opcodeSampleCount, record->m_sampleCount, (static_cast<double>(record->m_sampleCount - record->m_opcodeSampleCount) * 100) / record->m_sampleCount);
            }
        }
    }
#else
    UNUSED_PARAM(exec);
#endif
}
Esempio n. 27
0
void CreateDialog::_update_search() {


	search_options->clear();

	/*
	TreeItem *root = search_options->create_item();
	_parse_fs(EditorFileSystem::get_singleton()->get_filesystem());
*/

	List<StringName> type_list;
	ObjectTypeDB::get_type_list(&type_list);

	HashMap<String,TreeItem*> types;

	TreeItem *root = search_options->create_item();

	root->set_text(0,base_type);
	if (has_icon(base_type,"EditorIcons")) {
		root->set_icon(0,get_icon(base_type,"EditorIcons"));
	}

	List<StringName>::Element *I=type_list.front();
	TreeItem *to_select=NULL;

	for(;I;I=I->next()) {



		String type=I->get();

		if (base_type=="Node" && type.begins_with("Editor"))
			continue; // do not show editor nodes

		if (!ObjectTypeDB::can_instance(type))
			continue; // cant create what can't be instanced

		if (search_box->get_text()=="") {
			add_type(type,types,root,&to_select);
		} else {

			bool found=false;
			String type=I->get();
			while(type!="" && ObjectTypeDB::is_type(type,base_type) && type!=base_type) {
				if (search_box->get_text().is_subsequence_ofi(type)) {

					found=true;
					break;
				}

				type=ObjectTypeDB::type_inherits_from(type);
			}


			if (found)
				add_type(I->get(),types,root,&to_select);
		}

		if (EditorNode::get_editor_data().get_custom_types().has(type) && ObjectTypeDB::is_type(type, base_type)) {
			//there are custom types based on this... cool.
			//print_line("there are custom types");


			const Vector<EditorData::CustomType> &ct = EditorNode::get_editor_data().get_custom_types()[type];
			for(int i=0;i<ct.size();i++) {

				bool show = search_box->get_text().is_subsequence_ofi(ct[i].name);

				if (!show)
					continue;

				if (!types.has(type))
					add_type(type,types,root,&to_select);

				TreeItem *ti;
				if (types.has(type) )
					ti=types[type];
				else
					ti=search_options->get_root();


				TreeItem *item = search_options->create_item(ti);
				item->set_metadata(0,type);
				item->set_text(0,ct[i].name);
				if (ct[i].icon.is_valid()) {
					item->set_icon(0,ct[i].icon);

				}

				if (!to_select) {
					to_select=item;
				}

			}

		}
	}

	if (to_select)
		to_select->select(0);

	get_ok()->set_disabled(root->get_children()==NULL);

}
Esempio n. 28
0
void StorageAreaSync::sync(bool clearItems, const HashMap<String, String>& items)
{
    ASSERT(!isMainThread());

    if (items.isEmpty() && !clearItems && !m_syncCloseDatabase)
        return;
    if (m_databaseOpenFailed)
        return;

    if (!m_database.isOpen() && m_syncCloseDatabase) {
        m_syncCloseDatabase = false;
        return;
    }

    if (!m_database.isOpen())
        openDatabase(CreateIfNonExistent);
    if (!m_database.isOpen())
        return;

    // Closing this db because it is about to be deleted by StorageTracker.
    // The delete will be cancelled if StorageAreaSync needs to reopen the db
    // to write new items created after the request to delete the db.
    if (m_syncCloseDatabase) {
        m_syncCloseDatabase = false;
        m_database.close();
        return;
    }
    
    // If the clear flag is set, then we clear all items out before we write any new ones in.
    if (clearItems) {
        SQLiteStatement clear(m_database, "DELETE FROM ItemTable");
        if (clear.prepare() != SQLResultOk) {
            LOG_ERROR("Failed to prepare clear statement - cannot write to local storage database");
            return;
        }

        int result = clear.step();
        if (result != SQLResultDone) {
            LOG_ERROR("Failed to clear all items in the local storage database - %i", result);
            return;
        }
    }

    SQLiteStatement insert(m_database, "INSERT INTO ItemTable VALUES (?, ?)");
    if (insert.prepare() != SQLResultOk) {
        LOG_ERROR("Failed to prepare insert statement - cannot write to local storage database");
        return;
    }

    SQLiteStatement remove(m_database, "DELETE FROM ItemTable WHERE key=?");
    if (remove.prepare() != SQLResultOk) {
        LOG_ERROR("Failed to prepare delete statement - cannot write to local storage database");
        return;
    }

    HashMap<String, String>::const_iterator end = items.end();

    SQLiteTransaction transaction(m_database);
    transaction.begin();
    for (HashMap<String, String>::const_iterator it = items.begin(); it != end; ++it) {
        // Based on the null-ness of the second argument, decide whether this is an insert or a delete.
        SQLiteStatement& query = it->value.isNull() ? remove : insert;

        query.bindText(1, it->key);

        // If the second argument is non-null, we're doing an insert, so bind it as the value.
        if (!it->value.isNull())
            query.bindBlob(2, it->value);

        int result = query.step();
        if (result != SQLResultDone) {
            LOG_ERROR("Failed to update item in the local storage database - %i", result);
            break;
        }

        query.reset();
    }
    transaction.commit();
}
Esempio n. 29
0
void CreateDialog::add_type(const String& p_type,HashMap<String,TreeItem*>& p_types,TreeItem *p_root,TreeItem **to_select) {

	if (p_types.has(p_type))
		return;
	if (!ObjectTypeDB::is_type(p_type,base_type) || p_type==base_type)
		return;

	String inherits=ObjectTypeDB::type_inherits_from(p_type);

	TreeItem *parent=p_root;


	if (inherits.length()) {

		if (!p_types.has(inherits)) {

			add_type(inherits,p_types,p_root,to_select);
		}

		if (p_types.has(inherits) )
			parent=p_types[inherits];
	}

	TreeItem *item = search_options->create_item(parent);
	item->set_text(0,p_type);
	if (!ObjectTypeDB::can_instance(p_type)) {
		item->set_custom_color(0, Color(0.5,0.5,0.5) );
		item->set_selectable(0,false);
	} else {

		if (!*to_select && (search_box->get_text().is_subsequence_ofi(p_type))) {
			*to_select=item;
		}

	}

	if (bool(EditorSettings::get_singleton()->get("scenetree_editor/start_create_dialog_fully_expanded"))) {
		item->set_collapsed(false);
	} else {
		// don't collapse search results
		bool collapse = (search_box->get_text() == "");
		// don't collapse the root node
		collapse &= (item != p_root);
		// don't collapse abstract nodes on the first tree level
		collapse &= ((parent != p_root) || (ObjectTypeDB::can_instance(p_type)));
		item->set_collapsed(collapse);
	}

	const String& description = EditorHelp::get_doc_data()->class_list[p_type].brief_description;
	item->set_tooltip(0,description);


	if (has_icon(p_type,"EditorIcons")) {

		item->set_icon(0, get_icon(p_type,"EditorIcons"));
	}



	p_types[p_type]=item;
}
Esempio n. 30
0
void setCookies(Document* /*document*/, const KURL& url, const KURL& /*policyURL*/, const String& value)
{
    cookieJar.set(url.string(), value);
}