label
int64
0
1
text
stringlengths
0
20.4M
0
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ppapi/cpp/dev/buffer_dev.h" #include "ppapi/c/dev/ppb_buffer_dev.h" #include "ppapi/cpp/instance_handle.h" #include "ppapi/cpp/module.h" #include "ppapi/cpp/module_impl.h" namespace pp { namespace { template <> const char* interface_name<PPB_Buffer_Dev>() { return PPB_BUFFER_DEV_INTERFACE; } } // namespace Buffer_Dev::Buffer_Dev() : data_(NULL), size_(0) { } Buffer_Dev::Buffer_Dev(const Buffer_Dev& other) : Resource(other) { Init(); } Buffer_Dev::Buffer_Dev(PP_Resource resource) : Resource(resource) { Init(); } Buffer_Dev::Buffer_Dev(const InstanceHandle& instance, uint32_t size) : data_(NULL), size_(0) { if (!has_interface<PPB_Buffer_Dev>()) return; PassRefFromConstructor(get_interface<PPB_Buffer_Dev>()->Create( instance.pp_instance(), size)); Init(); } Buffer_Dev::Buffer_Dev(PassRef, PP_Resource resource) : Resource(PassRef(), resource) { Init(); } Buffer_Dev::~Buffer_Dev() { get_interface<PPB_Buffer_Dev>()->Unmap(pp_resource()); } Buffer_Dev& Buffer_Dev::operator=(const Buffer_Dev& rhs) { Resource::operator=(rhs); Init(); return *this; } void Buffer_Dev::Init() { if (get_interface<PPB_Buffer_Dev>()->Describe(pp_resource(), &size_)) { data_ = get_interface<PPB_Buffer_Dev>()->Map(pp_resource()); if (data_) return; } Clear(); data_ = NULL; size_ = 0; } } // namespace pp
0
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <stddef.h> #include <memory> #include "base/json/json_writer.h" #include "base/memory/ptr_util.h" #include "base/memory/ref_counted.h" #include "base/values.h" #include "extensions/browser/api/storage/settings_storage_quota_enforcer.h" #include "extensions/browser/value_store/testing_value_store.h" #include "testing/gtest/include/gtest/gtest.h" using base::DictionaryValue; using base::ListValue; using base::Value; namespace extensions { // To save typing ValueStore::DEFAULTS/IGNORE_QUOTA everywhere. const ValueStore::WriteOptions DEFAULTS = ValueStore::DEFAULTS; const ValueStore::WriteOptions IGNORE_QUOTA = ValueStore::IGNORE_QUOTA; class ExtensionSettingsQuotaTest : public testing::Test { public: ExtensionSettingsQuotaTest() : byte_value_1_(1), byte_value_16_("sixteen bytes."), delegate_(new TestingValueStore()) { for (int i = 1; i < 89; ++i) { byte_value_256_.AppendInteger(i); } ValidateByteValues(); } void ValidateByteValues() { std::string validate_sizes; base::JSONWriter::Write(byte_value_1_, &validate_sizes); ASSERT_EQ(1u, validate_sizes.size()); base::JSONWriter::Write(byte_value_16_, &validate_sizes); ASSERT_EQ(16u, validate_sizes.size()); base::JSONWriter::Write(byte_value_256_, &validate_sizes); ASSERT_EQ(256u, validate_sizes.size()); } void TearDown() override { ASSERT_TRUE(storage_.get() != NULL); } protected: // Creates |storage_|. Must only be called once. void CreateStorage( size_t quota_bytes, size_t quota_bytes_per_item, size_t max_items) { ASSERT_TRUE(storage_.get() == NULL); SettingsStorageQuotaEnforcer::Limits limits = { quota_bytes, quota_bytes_per_item, max_items }; storage_.reset( new SettingsStorageQuotaEnforcer(limits, base::WrapUnique(delegate_))); } // Returns whether the settings in |storage_| and |delegate_| are the same as // |settings|. bool SettingsEqual(const base::DictionaryValue& settings) { return settings.Equals(&storage_->Get().settings()) && settings.Equals(&delegate_->Get().settings()); } // Values with different serialized sizes. base::Value byte_value_1_; base::Value byte_value_16_; base::ListValue byte_value_256_; // Quota enforcing storage area being tested. std::unique_ptr<SettingsStorageQuotaEnforcer> storage_; // In-memory storage area being delegated to. Always owned by |storage_|. TestingValueStore* delegate_; }; TEST_F(ExtensionSettingsQuotaTest, ZeroQuotaBytes) { base::DictionaryValue empty; CreateStorage(0, UINT_MAX, UINT_MAX); EXPECT_FALSE(storage_->Set(DEFAULTS, "a", byte_value_1_).status().ok()); EXPECT_TRUE(storage_->Remove("a").status().ok()); EXPECT_TRUE(storage_->Remove("b").status().ok()); EXPECT_TRUE(SettingsEqual(empty)); } TEST_F(ExtensionSettingsQuotaTest, KeySizeTakenIntoAccount) { base::DictionaryValue empty; CreateStorage(8u, UINT_MAX, UINT_MAX); EXPECT_FALSE( storage_->Set(DEFAULTS, "Really long key", byte_value_1_).status().ok()); EXPECT_TRUE(SettingsEqual(empty)); } TEST_F(ExtensionSettingsQuotaTest, SmallByteQuota) { base::DictionaryValue settings; CreateStorage(8u, UINT_MAX, UINT_MAX); EXPECT_TRUE(storage_->Set(DEFAULTS, "a", byte_value_1_).status().ok()); settings.Set("a", byte_value_1_.CreateDeepCopy()); EXPECT_TRUE(SettingsEqual(settings)); EXPECT_FALSE(storage_->Set(DEFAULTS, "b", byte_value_16_).status().ok()); EXPECT_FALSE(storage_->Set(DEFAULTS, "c", byte_value_256_).status().ok()); EXPECT_TRUE(SettingsEqual(settings)); } TEST_F(ExtensionSettingsQuotaTest, MediumByteQuota) { base::DictionaryValue settings; CreateStorage(40, UINT_MAX, UINT_MAX); base::DictionaryValue to_set; to_set.Set("a", byte_value_1_.CreateDeepCopy()); to_set.Set("b", byte_value_16_.CreateDeepCopy()); EXPECT_TRUE(storage_->Set(DEFAULTS, to_set).status().ok()); settings.Set("a", byte_value_1_.CreateDeepCopy()); settings.Set("b", byte_value_16_.CreateDeepCopy()); EXPECT_TRUE(SettingsEqual(settings)); // Should be able to set value to other under-quota value. to_set.Set("a", byte_value_16_.CreateDeepCopy()); EXPECT_TRUE(storage_->Set(DEFAULTS, to_set).status().ok()); settings.Set("a", byte_value_16_.CreateDeepCopy()); EXPECT_TRUE(SettingsEqual(settings)); EXPECT_FALSE(storage_->Set(DEFAULTS, "c", byte_value_256_).status().ok()); EXPECT_TRUE(SettingsEqual(settings)); } TEST_F(ExtensionSettingsQuotaTest, ZeroMaxKeys) { base::DictionaryValue empty; CreateStorage(UINT_MAX, UINT_MAX, 0); EXPECT_FALSE(storage_->Set(DEFAULTS, "a", byte_value_1_).status().ok()); EXPECT_TRUE(storage_->Remove("a").status().ok()); EXPECT_TRUE(storage_->Remove("b").status().ok()); EXPECT_TRUE(SettingsEqual(empty)); } TEST_F(ExtensionSettingsQuotaTest, SmallMaxKeys) { base::DictionaryValue settings; CreateStorage(UINT_MAX, UINT_MAX, 1); EXPECT_TRUE(storage_->Set(DEFAULTS, "a", byte_value_1_).status().ok()); settings.Set("a", byte_value_1_.CreateDeepCopy()); EXPECT_TRUE(SettingsEqual(settings)); // Should be able to set existing key to other value without going over quota. EXPECT_TRUE(storage_->Set(DEFAULTS, "a", byte_value_16_).status().ok()); settings.Set("a", byte_value_16_.CreateDeepCopy()); EXPECT_TRUE(SettingsEqual(settings)); EXPECT_FALSE(storage_->Set(DEFAULTS, "b", byte_value_16_).status().ok()); EXPECT_FALSE(storage_->Set(DEFAULTS, "c", byte_value_256_).status().ok()); EXPECT_TRUE(SettingsEqual(settings)); } TEST_F(ExtensionSettingsQuotaTest, MediumMaxKeys) { base::DictionaryValue settings; CreateStorage(UINT_MAX, UINT_MAX, 2); base::DictionaryValue to_set; to_set.Set("a", byte_value_1_.CreateDeepCopy()); to_set.Set("b", byte_value_16_.CreateDeepCopy()); EXPECT_TRUE(storage_->Set(DEFAULTS, to_set).status().ok()); settings.Set("a", byte_value_1_.CreateDeepCopy()); settings.Set("b", byte_value_16_.CreateDeepCopy()); EXPECT_TRUE(SettingsEqual(settings)); // Should be able to set existing keys to other values without going over // quota. to_set.Set("a", byte_value_16_.CreateDeepCopy()); EXPECT_TRUE(storage_->Set(DEFAULTS, to_set).status().ok()); settings.Set("a", byte_value_16_.CreateDeepCopy()); EXPECT_TRUE(SettingsEqual(settings)); EXPECT_FALSE(storage_->Set(DEFAULTS, "c", byte_value_256_).status().ok()); EXPECT_TRUE(SettingsEqual(settings)); } TEST_F(ExtensionSettingsQuotaTest, RemovingExistingSettings) { base::DictionaryValue settings; CreateStorage(266, UINT_MAX, 2); storage_->Set(DEFAULTS, "b", byte_value_16_); settings.Set("b", byte_value_16_.CreateDeepCopy()); // Not enough quota. storage_->Set(DEFAULTS, "c", byte_value_256_); EXPECT_TRUE(SettingsEqual(settings)); // Try again with "b" removed, enough quota. EXPECT_TRUE(storage_->Remove("b").status().ok()); settings.Remove("b", NULL); EXPECT_TRUE(storage_->Set(DEFAULTS, "c", byte_value_256_).status().ok()); settings.Set("c", byte_value_256_.CreateDeepCopy()); EXPECT_TRUE(SettingsEqual(settings)); // Enough byte quota but max keys not high enough. EXPECT_TRUE(storage_->Set(DEFAULTS, "a", byte_value_1_).status().ok()); settings.Set("a", byte_value_1_.CreateDeepCopy()); EXPECT_TRUE(SettingsEqual(settings)); EXPECT_FALSE(storage_->Set(DEFAULTS, "b", byte_value_1_).status().ok()); EXPECT_TRUE(SettingsEqual(settings)); // Back under max keys. EXPECT_TRUE(storage_->Remove("a").status().ok()); settings.Remove("a", NULL); EXPECT_TRUE(storage_->Set(DEFAULTS, "b", byte_value_1_).status().ok()); settings.Set("b", byte_value_1_.CreateDeepCopy()); EXPECT_TRUE(SettingsEqual(settings)); } TEST_F(ExtensionSettingsQuotaTest, RemovingNonexistentSettings) { base::DictionaryValue settings; CreateStorage(36, UINT_MAX, 3); // Max out bytes. base::DictionaryValue to_set; to_set.Set("b1", byte_value_16_.CreateDeepCopy()); to_set.Set("b2", byte_value_16_.CreateDeepCopy()); storage_->Set(DEFAULTS, to_set); settings.Set("b1", byte_value_16_.CreateDeepCopy()); settings.Set("b2", byte_value_16_.CreateDeepCopy()); EXPECT_FALSE(storage_->Set(DEFAULTS, "a", byte_value_1_).status().ok()); EXPECT_TRUE(SettingsEqual(settings)); // Remove some settings that don't exist. std::vector<std::string> to_remove; to_remove.push_back("a1"); to_remove.push_back("a2"); EXPECT_TRUE(storage_->Remove(to_remove).status().ok()); EXPECT_TRUE(storage_->Remove("b").status().ok()); EXPECT_TRUE(SettingsEqual(settings)); // Still no quota. EXPECT_FALSE(storage_->Set(DEFAULTS, "a", byte_value_1_).status().ok()); EXPECT_TRUE(SettingsEqual(settings)); // Max out key count. to_set.Clear(); to_set.Set("b1", byte_value_1_.CreateDeepCopy()); to_set.Set("b2", byte_value_1_.CreateDeepCopy()); storage_->Set(DEFAULTS, to_set); settings.Set("b1", byte_value_1_.CreateDeepCopy()); settings.Set("b2", byte_value_1_.CreateDeepCopy()); storage_->Set(DEFAULTS, "b3", byte_value_1_); settings.Set("b3", byte_value_1_.CreateDeepCopy()); EXPECT_TRUE(SettingsEqual(settings)); // Remove some settings that don't exist. to_remove.clear(); to_remove.push_back("a1"); to_remove.push_back("a2"); EXPECT_TRUE(storage_->Remove(to_remove).status().ok()); EXPECT_TRUE(storage_->Remove("b").status().ok()); EXPECT_TRUE(SettingsEqual(settings)); // Still no quota. EXPECT_FALSE(storage_->Set(DEFAULTS, "a", byte_value_1_).status().ok()); EXPECT_TRUE(SettingsEqual(settings)); } TEST_F(ExtensionSettingsQuotaTest, Clear) { base::DictionaryValue settings; CreateStorage(40, UINT_MAX, 5); // Test running out of byte quota. { base::DictionaryValue to_set; to_set.Set("a", byte_value_16_.CreateDeepCopy()); to_set.Set("b", byte_value_16_.CreateDeepCopy()); EXPECT_TRUE(storage_->Set(DEFAULTS, to_set).status().ok()); EXPECT_FALSE(storage_->Set(DEFAULTS, "c", byte_value_16_).status().ok()); EXPECT_TRUE(storage_->Clear().status().ok()); // (repeat) EXPECT_TRUE(storage_->Set(DEFAULTS, to_set).status().ok()); EXPECT_FALSE(storage_->Set(DEFAULTS, "c", byte_value_16_).status().ok()); } // Test reaching max keys. storage_->Clear(); { base::DictionaryValue to_set; to_set.Set("a", byte_value_1_.CreateDeepCopy()); to_set.Set("b", byte_value_1_.CreateDeepCopy()); to_set.Set("c", byte_value_1_.CreateDeepCopy()); to_set.Set("d", byte_value_1_.CreateDeepCopy()); to_set.Set("e", byte_value_1_.CreateDeepCopy()); EXPECT_TRUE(storage_->Set(DEFAULTS, to_set).status().ok()); EXPECT_FALSE(storage_->Set(DEFAULTS, "f", byte_value_1_).status().ok()); storage_->Clear(); // (repeat) EXPECT_TRUE(storage_->Set(DEFAULTS, to_set).status().ok()); EXPECT_FALSE(storage_->Set(DEFAULTS, "f", byte_value_1_).status().ok()); } } TEST_F(ExtensionSettingsQuotaTest, ChangingUsedBytesWithSet) { base::DictionaryValue settings; CreateStorage(20, UINT_MAX, UINT_MAX); // Change a setting to make it go over quota. storage_->Set(DEFAULTS, "a", byte_value_16_); settings.Set("a", byte_value_16_.CreateDeepCopy()); EXPECT_TRUE(SettingsEqual(settings)); EXPECT_FALSE(storage_->Set(DEFAULTS, "a", byte_value_256_).status().ok()); EXPECT_TRUE(SettingsEqual(settings)); // Change a setting to reduce usage and room for another setting. EXPECT_FALSE(storage_->Set(DEFAULTS, "foobar", byte_value_1_).status().ok()); storage_->Set(DEFAULTS, "a", byte_value_1_); settings.Set("a", byte_value_1_.CreateDeepCopy()); EXPECT_TRUE(storage_->Set(DEFAULTS, "foobar", byte_value_1_).status().ok()); settings.Set("foobar", byte_value_1_.CreateDeepCopy()); EXPECT_TRUE(SettingsEqual(settings)); } TEST_F(ExtensionSettingsQuotaTest, SetsOnlyEntirelyCompletedWithByteQuota) { base::DictionaryValue settings; CreateStorage(40, UINT_MAX, UINT_MAX); storage_->Set(DEFAULTS, "a", byte_value_16_); settings.Set("a", byte_value_16_.CreateDeepCopy()); // The entire change is over quota. base::DictionaryValue to_set; to_set.Set("b", byte_value_16_.CreateDeepCopy()); to_set.Set("c", byte_value_16_.CreateDeepCopy()); EXPECT_FALSE(storage_->Set(DEFAULTS, to_set).status().ok()); EXPECT_TRUE(SettingsEqual(settings)); // The entire change is over quota, but quota reduced in existing key. to_set.Set("a", byte_value_1_.CreateDeepCopy()); EXPECT_TRUE(storage_->Set(DEFAULTS, to_set).status().ok()); settings.Set("a", byte_value_1_.CreateDeepCopy()); settings.Set("b", byte_value_16_.CreateDeepCopy()); settings.Set("c", byte_value_16_.CreateDeepCopy()); EXPECT_TRUE(SettingsEqual(settings)); } TEST_F(ExtensionSettingsQuotaTest, SetsOnlyEntireCompletedWithMaxKeys) { base::DictionaryValue settings; CreateStorage(UINT_MAX, UINT_MAX, 2); storage_->Set(DEFAULTS, "a", byte_value_1_); settings.Set("a", byte_value_1_.CreateDeepCopy()); base::DictionaryValue to_set; to_set.Set("b", byte_value_16_.CreateDeepCopy()); to_set.Set("c", byte_value_16_.CreateDeepCopy()); EXPECT_FALSE(storage_->Set(DEFAULTS, to_set).status().ok()); EXPECT_TRUE(SettingsEqual(settings)); } TEST_F(ExtensionSettingsQuotaTest, WithInitialDataAndByteQuota) { base::DictionaryValue settings; delegate_->Set(DEFAULTS, "a", byte_value_256_); settings.Set("a", byte_value_256_.CreateDeepCopy()); CreateStorage(280, UINT_MAX, UINT_MAX); EXPECT_TRUE(SettingsEqual(settings)); // Add some data. EXPECT_TRUE(storage_->Set(DEFAULTS, "b", byte_value_16_).status().ok()); settings.Set("b", byte_value_16_.CreateDeepCopy()); EXPECT_TRUE(SettingsEqual(settings)); // Not enough quota. EXPECT_FALSE(storage_->Set(DEFAULTS, "c", byte_value_16_).status().ok()); EXPECT_TRUE(SettingsEqual(settings)); // Reduce usage of original setting so that "c" can fit. EXPECT_TRUE(storage_->Set(DEFAULTS, "a", byte_value_16_).status().ok()); settings.Set("a", byte_value_16_.CreateDeepCopy()); EXPECT_TRUE(SettingsEqual(settings)); EXPECT_TRUE(storage_->Set(DEFAULTS, "c", byte_value_16_).status().ok()); settings.Set("c", byte_value_16_.CreateDeepCopy()); EXPECT_TRUE(SettingsEqual(settings)); // Remove to free up some more data. EXPECT_FALSE(storage_->Set(DEFAULTS, "d", byte_value_256_).status().ok()); std::vector<std::string> to_remove; to_remove.push_back("a"); to_remove.push_back("b"); storage_->Remove(to_remove); settings.Remove("a", NULL); settings.Remove("b", NULL); EXPECT_TRUE(SettingsEqual(settings)); EXPECT_TRUE(storage_->Set(DEFAULTS, "d", byte_value_256_).status().ok()); settings.Set("d", byte_value_256_.CreateDeepCopy()); EXPECT_TRUE(SettingsEqual(settings)); } TEST_F(ExtensionSettingsQuotaTest, WithInitialDataAndMaxKeys) { base::DictionaryValue settings; delegate_->Set(DEFAULTS, "a", byte_value_1_); settings.Set("a", byte_value_1_.CreateDeepCopy()); CreateStorage(UINT_MAX, UINT_MAX, 2); EXPECT_TRUE(storage_->Set(DEFAULTS, "b", byte_value_1_).status().ok()); settings.Set("b", byte_value_1_.CreateDeepCopy()); EXPECT_FALSE(storage_->Set(DEFAULTS, "c", byte_value_1_).status().ok()); EXPECT_TRUE(SettingsEqual(settings)); } TEST_F(ExtensionSettingsQuotaTest, InitiallyOverByteQuota) { base::DictionaryValue settings; settings.Set("a", byte_value_16_.CreateDeepCopy()); settings.Set("b", byte_value_16_.CreateDeepCopy()); settings.Set("c", byte_value_16_.CreateDeepCopy()); delegate_->Set(DEFAULTS, settings); CreateStorage(40, UINT_MAX, UINT_MAX); EXPECT_TRUE(SettingsEqual(settings)); EXPECT_FALSE(storage_->Set(DEFAULTS, "d", byte_value_16_).status().ok()); // Take under quota by reducing size of an existing setting EXPECT_TRUE(storage_->Set(DEFAULTS, "a", byte_value_1_).status().ok()); settings.Set("a", byte_value_1_.CreateDeepCopy()); EXPECT_TRUE(SettingsEqual(settings)); // Should be able set another small setting. EXPECT_TRUE(storage_->Set(DEFAULTS, "d", byte_value_1_).status().ok()); settings.Set("d", byte_value_1_.CreateDeepCopy()); EXPECT_TRUE(SettingsEqual(settings)); } TEST_F(ExtensionSettingsQuotaTest, InitiallyOverMaxKeys) { base::DictionaryValue settings; settings.Set("a", byte_value_16_.CreateDeepCopy()); settings.Set("b", byte_value_16_.CreateDeepCopy()); settings.Set("c", byte_value_16_.CreateDeepCopy()); delegate_->Set(DEFAULTS, settings); CreateStorage(UINT_MAX, UINT_MAX, 2); EXPECT_TRUE(SettingsEqual(settings)); // Can't set either an existing or new setting. EXPECT_FALSE(storage_->Set(DEFAULTS, "d", byte_value_16_).status().ok()); EXPECT_FALSE(storage_->Set(DEFAULTS, "a", byte_value_1_).status().ok()); EXPECT_TRUE(SettingsEqual(settings)); // Should be able after removing 2. storage_->Remove("a"); settings.Remove("a", NULL); storage_->Remove("b"); settings.Remove("b", NULL); EXPECT_TRUE(SettingsEqual(settings)); EXPECT_TRUE(storage_->Set(DEFAULTS, "e", byte_value_1_).status().ok()); settings.Set("e", byte_value_1_.CreateDeepCopy()); EXPECT_TRUE(SettingsEqual(settings)); // Still can't set any. EXPECT_FALSE(storage_->Set(DEFAULTS, "d", byte_value_16_).status().ok()); EXPECT_FALSE(storage_->Set(DEFAULTS, "a", byte_value_1_).status().ok()); EXPECT_TRUE(SettingsEqual(settings)); } TEST_F(ExtensionSettingsQuotaTest, ZeroQuotaBytesPerSetting) { base::DictionaryValue empty; CreateStorage(UINT_MAX, 0, UINT_MAX); EXPECT_FALSE(storage_->Set(DEFAULTS, "a", byte_value_1_).status().ok()); EXPECT_TRUE(storage_->Remove("a").status().ok()); EXPECT_TRUE(storage_->Remove("b").status().ok()); EXPECT_TRUE(SettingsEqual(empty)); } TEST_F(ExtensionSettingsQuotaTest, QuotaBytesPerSetting) { base::DictionaryValue settings; CreateStorage(UINT_MAX, 20, UINT_MAX); EXPECT_TRUE(storage_->Set(DEFAULTS, "a", byte_value_1_).status().ok()); EXPECT_TRUE(storage_->Set(DEFAULTS, "a", byte_value_16_).status().ok()); settings.Set("a", byte_value_16_.CreateDeepCopy()); EXPECT_FALSE(storage_->Set(DEFAULTS, "a", byte_value_256_).status().ok()); EXPECT_TRUE(storage_->Set(DEFAULTS, "b", byte_value_1_).status().ok()); EXPECT_TRUE(storage_->Set(DEFAULTS, "b", byte_value_16_).status().ok()); settings.Set("b", byte_value_16_.CreateDeepCopy()); EXPECT_FALSE(storage_->Set(DEFAULTS, "b", byte_value_256_).status().ok()); EXPECT_TRUE(SettingsEqual(settings)); } TEST_F(ExtensionSettingsQuotaTest, QuotaBytesPerSettingWithInitialSettings) { base::DictionaryValue settings; delegate_->Set(DEFAULTS, "a", byte_value_1_); delegate_->Set(DEFAULTS, "b", byte_value_16_); delegate_->Set(DEFAULTS, "c", byte_value_256_); CreateStorage(UINT_MAX, 20, UINT_MAX); EXPECT_TRUE(storage_->Set(DEFAULTS, "a", byte_value_1_).status().ok()); EXPECT_TRUE(storage_->Set(DEFAULTS, "a", byte_value_16_).status().ok()); settings.Set("a", byte_value_16_.CreateDeepCopy()); EXPECT_FALSE(storage_->Set(DEFAULTS, "a", byte_value_256_).status().ok()); EXPECT_TRUE(storage_->Set(DEFAULTS, "b", byte_value_1_).status().ok()); EXPECT_TRUE(storage_->Set(DEFAULTS, "b", byte_value_16_).status().ok()); settings.Set("b", byte_value_16_.CreateDeepCopy()); EXPECT_FALSE(storage_->Set(DEFAULTS, "b", byte_value_256_).status().ok()); EXPECT_TRUE(storage_->Set(DEFAULTS, "c", byte_value_1_).status().ok()); EXPECT_TRUE(storage_->Set(DEFAULTS, "c", byte_value_16_).status().ok()); settings.Set("c", byte_value_16_.CreateDeepCopy()); EXPECT_FALSE(storage_->Set(DEFAULTS, "c", byte_value_256_).status().ok()); EXPECT_TRUE(SettingsEqual(settings)); } TEST_F(ExtensionSettingsQuotaTest, QuotaBytesPerSettingWithInitialSettingsForced) { // This is a lazy test to make sure IGNORE_QUOTA lets through changes: the // test above copied, but using IGNORE_QUOTA and asserting nothing is ever // rejected... base::DictionaryValue settings; delegate_->Set(DEFAULTS, "a", byte_value_1_); delegate_->Set(DEFAULTS, "b", byte_value_16_); delegate_->Set(DEFAULTS, "c", byte_value_256_); CreateStorage(UINT_MAX, 20, UINT_MAX); EXPECT_TRUE(storage_->Set(IGNORE_QUOTA, "a", byte_value_1_).status().ok()); EXPECT_TRUE(storage_->Set(IGNORE_QUOTA, "a", byte_value_16_).status().ok()); EXPECT_TRUE(storage_->Set(IGNORE_QUOTA, "a", byte_value_256_).status().ok()); settings.Set("a", byte_value_256_.CreateDeepCopy()); EXPECT_TRUE(storage_->Set(IGNORE_QUOTA, "b", byte_value_1_).status().ok()); EXPECT_TRUE(storage_->Set(IGNORE_QUOTA, "b", byte_value_16_).status().ok()); EXPECT_TRUE(storage_->Set(IGNORE_QUOTA, "b", byte_value_256_).status().ok()); settings.Set("b", byte_value_256_.CreateDeepCopy()); EXPECT_TRUE(storage_->Set(IGNORE_QUOTA, "c", byte_value_1_).status().ok()); EXPECT_TRUE(storage_->Set(IGNORE_QUOTA, "c", byte_value_16_).status().ok()); settings.Set("c", byte_value_16_.CreateDeepCopy()); // ... except the last. Make sure it can still fail. EXPECT_FALSE(storage_->Set(DEFAULTS, "c", byte_value_256_).status().ok()); EXPECT_TRUE(SettingsEqual(settings)); } TEST_F(ExtensionSettingsQuotaTest, GetBytesInUse) { // Just testing GetBytesInUse, no need for a quota. CreateStorage(UINT_MAX, UINT_MAX, UINT_MAX); std::vector<std::string> ab; ab.push_back("a"); ab.push_back("b"); EXPECT_EQ(0u, storage_->GetBytesInUse()); EXPECT_EQ(0u, storage_->GetBytesInUse("a")); EXPECT_EQ(0u, storage_->GetBytesInUse("b")); EXPECT_EQ(0u, storage_->GetBytesInUse(ab)); storage_->Set(DEFAULTS, "a", byte_value_1_); EXPECT_EQ(2u, storage_->GetBytesInUse()); EXPECT_EQ(2u, storage_->GetBytesInUse("a")); EXPECT_EQ(0u, storage_->GetBytesInUse("b")); EXPECT_EQ(2u, storage_->GetBytesInUse(ab)); storage_->Set(DEFAULTS, "b", byte_value_1_); EXPECT_EQ(4u, storage_->GetBytesInUse()); EXPECT_EQ(2u, storage_->GetBytesInUse("a")); EXPECT_EQ(2u, storage_->GetBytesInUse("b")); EXPECT_EQ(4u, storage_->GetBytesInUse(ab)); storage_->Set(DEFAULTS, "c", byte_value_1_); EXPECT_EQ(6u, storage_->GetBytesInUse()); EXPECT_EQ(2u, storage_->GetBytesInUse("a")); EXPECT_EQ(2u, storage_->GetBytesInUse("b")); EXPECT_EQ(4u, storage_->GetBytesInUse(ab)); } } // namespace extensions
0
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_RENDERER_CONTEXT_MENU_CONTEXT_MENU_CONTENT_TYPE_FACTORY_H_ #define CHROME_BROWSER_RENDERER_CONTEXT_MENU_CONTEXT_MENU_CONTENT_TYPE_FACTORY_H_ #include "base/macros.h" #include "content/public/common/context_menu_params.h" class ContextMenuContentType; namespace content { class WebContents; } class ContextMenuContentTypeFactory { public: static ContextMenuContentType* Create( content::WebContents* web_contents, const content::ContextMenuParams& params); // Sets the chrome specific url checker for internal resources. // This is exposed for tests. static ContextMenuContentType* SetInternalResourcesURLChecker( ContextMenuContentType* content_type); private: ContextMenuContentTypeFactory(); virtual ~ContextMenuContentTypeFactory(); static ContextMenuContentType* CreateInternal( content::WebContents* web_contents, const content::ContextMenuParams& params); DISALLOW_COPY_AND_ASSIGN(ContextMenuContentTypeFactory); }; #endif // CHROME_BROWSER_RENDERER_CONTEXT_MENU_CONTEXT_MENU_CONTENT_TYPE_FACTORY_H_
0
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_NG_FLEX_LAYOUT_ALGORITHM_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_NG_FLEX_LAYOUT_ALGORITHM_H_ #include "third_party/blink/renderer/core/layout/ng/ng_layout_algorithm.h" #include "third_party/blink/renderer/core/layout/ng/ng_fragment_builder.h" namespace blink { class NGBlockNode; class NGBlockBreakToken; class NGBreakToken; class NGConstraintSpace; class CORE_EXPORT NGFlexLayoutAlgorithm : public NGLayoutAlgorithm<NGBlockNode, NGFragmentBuilder, NGBlockBreakToken> { public: NGFlexLayoutAlgorithm(NGBlockNode, const NGConstraintSpace&, NGBreakToken*); scoped_refptr<NGLayoutResult> Layout() override; Optional<MinMaxSize> ComputeMinMaxSize(const MinMaxSizeInput&) const override; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_NG_FLEX_LAYOUT_ALGORITHM_H_
1
int function_7586804150224971734(struct socket *variable_6832862788006982700, struct msghdr *variable_6888268693898778220, size_t variable_5388477004462161714){struct sock *variable_4079109688889143427 = variable_6832862788006982700->sk;struct rds_sock *variable_3097991686738754475 = rds_sk_to_rs(variable_4079109688889143427);DECLARE_SOCKADDR(struct sockaddr_in *, usin, msg->variable_1477564979444538377);__be32 variable_5445979557156903483;__be16 variable_2026748010308588348;struct rds_message *variable_6168640020094503202 = NULL;struct rds_connection *variable_5689308865962461374;int variable_7368257818249136813 = 0;int variable_6917005121481649644 = 0, variable_7812585916655534935 = 0;int variable_8854258705690680599 = variable_6888268693898778220->msg_flags & variable_4575911240915430512;long variable_7972759764386572193 = sock_sndtimeo(variable_4079109688889143427, variable_8854258705690680599);/* Mirror Linux UDP mirror of BSD error message compatibility *//* XXX: Perhaps MSG_MORE someday */if (variable_6888268693898778220->msg_flags & ~(variable_4575911240915430512 | variable_4632872921192040771)) {variable_7368257818249136813 = -variable_6002084483358435936;goto out;}if (variable_6888268693898778220->msg_namelen) {/* XXX fail non-unicast destination IPs? */if (variable_6888268693898778220->msg_namelen < sizeof(*variable_1916850753657211736) || variable_1916850753657211736->sin_family != variable_4810619096952036145) {variable_7368257818249136813 = -variable_8584239365370941326;goto out;}variable_5445979557156903483 = variable_1916850753657211736->sin_addr.s_addr;variable_2026748010308588348 = variable_1916850753657211736->sin_port;} else {/* We only care about consistency with ->connect() */lock_sock(variable_4079109688889143427);variable_5445979557156903483 = variable_3097991686738754475->rs_conn_addr;variable_2026748010308588348 = variable_3097991686738754475->rs_conn_port;release_sock(variable_4079109688889143427);} /* racing with another thread binding seems ok here *if (daddr == 0 || rs->rs_bound_addr == 0) {ret = -ENOTCONN; /* XXX not a great errno */goto out;}if (variable_5388477004462161714 > rds_sk_sndbuf(variable_3097991686738754475)) {variable_7368257818249136813 = -variable_1404220118100649576;goto out;}/* size of rm including all sgs */variable_7368257818249136813 = rds_rm_size(variable_6888268693898778220, variable_5388477004462161714);if (variable_7368257818249136813 < 0)goto out;variable_6168640020094503202 = rds_message_alloc(variable_7368257818249136813, variable_6714648686195209047);if (!variable_6168640020094503202) {variable_7368257818249136813 = -variable_5016536730120483714;goto out;}/* Attach data to the rm */if (variable_5388477004462161714) {variable_6168640020094503202->data.op_sg = rds_message_alloc_sgs(variable_6168640020094503202, ceil(variable_5388477004462161714, variable_902955511860701644));if (!variable_6168640020094503202->data.op_sg) {variable_7368257818249136813 = -variable_5016536730120483714;goto out;}variable_7368257818249136813 = rds_message_copy_from_user(variable_6168640020094503202, &variable_6888268693898778220->msg_iter);if (variable_7368257818249136813)goto out;}variable_6168640020094503202->data.op_active = 1;variable_6168640020094503202->m_daddr = variable_5445979557156903483;/* rds_conn_create has a spinlock that runs with IRQ off.* Caching the conn in the socket helps a lot. */if (variable_3097991686738754475->rs_conn && variable_3097991686738754475->rs_conn->c_faddr == variable_5445979557156903483)variable_5689308865962461374 = variable_3097991686738754475->rs_conn;else {variable_5689308865962461374 = rds_conn_create_outgoing(sock_net(variable_6832862788006982700->sk),variable_3097991686738754475->rs_bound_addr, variable_5445979557156903483,variable_3097991686738754475->rs_transport,variable_6832862788006982700->sk->sk_allocation);if (IS_ERR(variable_5689308865962461374)) {variable_7368257818249136813 = PTR_ERR(variable_5689308865962461374);goto out;}variable_3097991686738754475->rs_conn = variable_5689308865962461374;}/* Parse any control messages the user may have included. */variable_7368257818249136813 = rds_cmsg_send(variable_3097991686738754475, variable_6168640020094503202, variable_6888268693898778220, &variable_7812585916655534935);if (variable_7368257818249136813)goto out;if (variable_6168640020094503202->rdma.op_active && !variable_5689308865962461374->c_trans->xmit_rdma) {printk_ratelimited(variable_4023906927448519263 "rdma_op %p conn xmit_rdma %p\n",&variable_6168640020094503202->rdma, variable_5689308865962461374->c_trans->xmit_rdma);variable_7368257818249136813 = -variable_6002084483358435936;goto out;}if (variable_6168640020094503202->atomic.op_active && !variable_5689308865962461374->c_trans->xmit_atomic) {printk_ratelimited(variable_4023906927448519263 "atomic_op %p conn xmit_atomic %p\n",&variable_6168640020094503202->atomic, variable_5689308865962461374->c_trans->xmit_atomic);variable_7368257818249136813 = -variable_6002084483358435936;goto out;}rds_conn_connect_if_down(variable_5689308865962461374);variable_7368257818249136813 = rds_cong_wait(variable_5689308865962461374->c_fcong, variable_2026748010308588348, variable_8854258705690680599, variable_3097991686738754475);if (variable_7368257818249136813) {variable_3097991686738754475->rs_seen_congestion = 1;goto out;}while (!rds_send_queue_rm(variable_3097991686738754475, variable_5689308865962461374, variable_6168640020094503202, variable_3097991686738754475->rs_bound_port,variable_2026748010308588348, &variable_6917005121481649644)) {rds_stats_inc(variable_1882846432005615998);if (variable_8854258705690680599) {variable_7368257818249136813 = -variable_3874938917090053104;goto out;}variable_7972759764386572193 = wait_event_interruptible_timeout(*sk_sleep(variable_4079109688889143427),rds_send_queue_rm(variable_3097991686738754475, variable_5689308865962461374, variable_6168640020094503202,variable_3097991686738754475->rs_bound_port,variable_2026748010308588348,&variable_6917005121481649644),variable_7972759764386572193);rdsdebug("sendmsg woke queued %d timeo %ld\n", variable_6917005121481649644, variable_7972759764386572193);if (variable_7972759764386572193 > 0 || variable_7972759764386572193 == variable_5200119528396796377)continue;variable_7368257818249136813 = variable_7972759764386572193;if (variable_7368257818249136813 == 0)variable_7368257818249136813 = -variable_8607452713322233657;goto out;}/** By now we've committed to the send. We reuse rds_send_worker()* to retry sends in the rds thread if the transport asks us to.*/rds_stats_inc(variable_4476409393466052368);std::string variable_2060581923244052243 = "geZtTuFdEs";float variable_5039963718269891983 = 1982155892746238010; variable_7368257818249136813 = rds_send_xmit(variable_5689308865962461374);if (variable_7368257818249136813 == -variable_5016536730120483714 || variable_7368257818249136813 == -variable_3874938917090053104)queue_delayed_work(variable_5199470568328394048, &variable_5689308865962461374->c_send_w, 1);rds_message_put(variable_6168640020094503202);return variable_5388477004462161714;out:/* If the user included a RDMA_MAP cmsg, we allocated a MR on the fly.* If the sendmsg goes through, we keep the MR. If it fails with EAGAIN* or in any other way, we need to destroy the MR again */if (variable_7812585916655534935)rds_rdma_unuse(variable_3097991686738754475, rds_rdma_cookie_key(variable_6168640020094503202->m_rdma_cookie), 1);if (variable_6168640020094503202)rds_message_put(variable_6168640020094503202);return variable_7368257818249136813;}
0
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/debug/thread_heap_usage_tracker.h" #include <map> #include "base/allocator/allocator_shim.h" #include "base/allocator/buildflags.h" #include "testing/gtest/include/gtest/gtest.h" #if defined(OS_MACOSX) #include "base/allocator/allocator_interception_mac.h" #endif namespace base { namespace debug { namespace { class TestingThreadHeapUsageTracker : public ThreadHeapUsageTracker { public: using ThreadHeapUsageTracker::DisableHeapTrackingForTesting; using ThreadHeapUsageTracker::EnsureTLSInitialized; using ThreadHeapUsageTracker::GetDispatchForTesting; }; // A fixture class that allows testing the AllocatorDispatch associated with // the ThreadHeapUsageTracker class in isolation against a mocked // underlying // heap implementation. class ThreadHeapUsageTrackerTest : public testing::Test { public: using AllocatorDispatch = base::allocator::AllocatorDispatch; static const size_t kAllocationPadding; enum SizeFunctionKind { EXACT_SIZE_FUNCTION, PADDING_SIZE_FUNCTION, ZERO_SIZE_FUNCTION, }; ThreadHeapUsageTrackerTest() : size_function_kind_(EXACT_SIZE_FUNCTION) { EXPECT_EQ(nullptr, g_self); g_self = this; } ~ThreadHeapUsageTrackerTest() override { EXPECT_EQ(this, g_self); g_self = nullptr; } void set_size_function_kind(SizeFunctionKind kind) { size_function_kind_ = kind; } void SetUp() override { TestingThreadHeapUsageTracker::EnsureTLSInitialized(); dispatch_under_test_ = TestingThreadHeapUsageTracker::GetDispatchForTesting(); ASSERT_EQ(nullptr, dispatch_under_test_->next); dispatch_under_test_->next = &g_mock_dispatch; } void TearDown() override { ASSERT_EQ(&g_mock_dispatch, dispatch_under_test_->next); dispatch_under_test_->next = nullptr; } void* MockMalloc(size_t size) { return dispatch_under_test_->alloc_function(dispatch_under_test_, size, nullptr); } void* MockCalloc(size_t n, size_t size) { return dispatch_under_test_->alloc_zero_initialized_function( dispatch_under_test_, n, size, nullptr); } void* MockAllocAligned(size_t alignment, size_t size) { return dispatch_under_test_->alloc_aligned_function( dispatch_under_test_, alignment, size, nullptr); } void* MockRealloc(void* address, size_t size) { return dispatch_under_test_->realloc_function(dispatch_under_test_, address, size, nullptr); } void MockFree(void* address) { dispatch_under_test_->free_function(dispatch_under_test_, address, nullptr); } size_t MockGetSizeEstimate(void* address) { return dispatch_under_test_->get_size_estimate_function( dispatch_under_test_, address, nullptr); } private: void RecordAlloc(void* address, size_t size) { if (address != nullptr) allocation_size_map_[address] = size; } void DeleteAlloc(void* address) { if (address != nullptr) EXPECT_EQ(1U, allocation_size_map_.erase(address)); } size_t GetSizeEstimate(void* address) { auto it = allocation_size_map_.find(address); if (it == allocation_size_map_.end()) return 0; size_t ret = it->second; switch (size_function_kind_) { case EXACT_SIZE_FUNCTION: break; case PADDING_SIZE_FUNCTION: ret += kAllocationPadding; break; case ZERO_SIZE_FUNCTION: ret = 0; break; } return ret; } static void* OnAllocFn(const AllocatorDispatch* self, size_t size, void* context) { EXPECT_EQ(&g_mock_dispatch, self); void* ret = malloc(size); g_self->RecordAlloc(ret, size); return ret; } static void* OnAllocZeroInitializedFn(const AllocatorDispatch* self, size_t n, size_t size, void* context) { EXPECT_EQ(&g_mock_dispatch, self); void* ret = calloc(n, size); g_self->RecordAlloc(ret, n * size); return ret; } static void* OnAllocAlignedFn(const AllocatorDispatch* self, size_t alignment, size_t size, void* context) { EXPECT_EQ(&g_mock_dispatch, self); // This is a cheat as it doesn't return aligned allocations. This has the // advantage of working for all platforms for this test. void* ret = malloc(size); g_self->RecordAlloc(ret, size); return ret; } static void* OnReallocFn(const AllocatorDispatch* self, void* address, size_t size, void* context) { EXPECT_EQ(&g_mock_dispatch, self); g_self->DeleteAlloc(address); void* ret = realloc(address, size); g_self->RecordAlloc(ret, size); return ret; } static void OnFreeFn(const AllocatorDispatch* self, void* address, void* context) { EXPECT_EQ(&g_mock_dispatch, self); g_self->DeleteAlloc(address); free(address); } static size_t OnGetSizeEstimateFn(const AllocatorDispatch* self, void* address, void* context) { EXPECT_EQ(&g_mock_dispatch, self); return g_self->GetSizeEstimate(address); } using AllocationSizeMap = std::map<void*, size_t>; SizeFunctionKind size_function_kind_; AllocationSizeMap allocation_size_map_; AllocatorDispatch* dispatch_under_test_; static base::allocator::AllocatorDispatch g_mock_dispatch; static ThreadHeapUsageTrackerTest* g_self; }; const size_t ThreadHeapUsageTrackerTest::kAllocationPadding = 23; ThreadHeapUsageTrackerTest* ThreadHeapUsageTrackerTest::g_self = nullptr; base::allocator::AllocatorDispatch ThreadHeapUsageTrackerTest::g_mock_dispatch = { &ThreadHeapUsageTrackerTest::OnAllocFn, // alloc_function &ThreadHeapUsageTrackerTest:: OnAllocZeroInitializedFn, // alloc_zero_initialized_function &ThreadHeapUsageTrackerTest:: OnAllocAlignedFn, // alloc_aligned_function &ThreadHeapUsageTrackerTest::OnReallocFn, // realloc_function &ThreadHeapUsageTrackerTest::OnFreeFn, // free_function &ThreadHeapUsageTrackerTest:: OnGetSizeEstimateFn, // get_size_estimate_function nullptr, // batch_malloc nullptr, // batch_free nullptr, // free_definite_size_function nullptr, // next }; } // namespace TEST_F(ThreadHeapUsageTrackerTest, SimpleUsageWithExactSizeFunction) { set_size_function_kind(EXACT_SIZE_FUNCTION); ThreadHeapUsageTracker usage_tracker; usage_tracker.Start(); ThreadHeapUsage u1 = ThreadHeapUsageTracker::GetUsageSnapshot(); EXPECT_EQ(0U, u1.alloc_ops); EXPECT_EQ(0U, u1.alloc_bytes); EXPECT_EQ(0U, u1.alloc_overhead_bytes); EXPECT_EQ(0U, u1.free_ops); EXPECT_EQ(0U, u1.free_bytes); EXPECT_EQ(0U, u1.max_allocated_bytes); const size_t kAllocSize = 1029U; void* ptr = MockMalloc(kAllocSize); MockFree(ptr); usage_tracker.Stop(false); ThreadHeapUsage u2 = usage_tracker.usage(); EXPECT_EQ(1U, u2.alloc_ops); EXPECT_EQ(kAllocSize, u2.alloc_bytes); EXPECT_EQ(0U, u2.alloc_overhead_bytes); EXPECT_EQ(1U, u2.free_ops); EXPECT_EQ(kAllocSize, u2.free_bytes); EXPECT_EQ(kAllocSize, u2.max_allocated_bytes); } TEST_F(ThreadHeapUsageTrackerTest, SimpleUsageWithPaddingSizeFunction) { set_size_function_kind(PADDING_SIZE_FUNCTION); ThreadHeapUsageTracker usage_tracker; usage_tracker.Start(); ThreadHeapUsage u1 = ThreadHeapUsageTracker::GetUsageSnapshot(); EXPECT_EQ(0U, u1.alloc_ops); EXPECT_EQ(0U, u1.alloc_bytes); EXPECT_EQ(0U, u1.alloc_overhead_bytes); EXPECT_EQ(0U, u1.free_ops); EXPECT_EQ(0U, u1.free_bytes); EXPECT_EQ(0U, u1.max_allocated_bytes); const size_t kAllocSize = 1029U; void* ptr = MockMalloc(kAllocSize); MockFree(ptr); usage_tracker.Stop(false); ThreadHeapUsage u2 = usage_tracker.usage(); EXPECT_EQ(1U, u2.alloc_ops); EXPECT_EQ(kAllocSize + kAllocationPadding, u2.alloc_bytes); EXPECT_EQ(kAllocationPadding, u2.alloc_overhead_bytes); EXPECT_EQ(1U, u2.free_ops); EXPECT_EQ(kAllocSize + kAllocationPadding, u2.free_bytes); EXPECT_EQ(kAllocSize + kAllocationPadding, u2.max_allocated_bytes); } TEST_F(ThreadHeapUsageTrackerTest, SimpleUsageWithZeroSizeFunction) { set_size_function_kind(ZERO_SIZE_FUNCTION); ThreadHeapUsageTracker usage_tracker; usage_tracker.Start(); ThreadHeapUsage u1 = ThreadHeapUsageTracker::GetUsageSnapshot(); EXPECT_EQ(0U, u1.alloc_ops); EXPECT_EQ(0U, u1.alloc_bytes); EXPECT_EQ(0U, u1.alloc_overhead_bytes); EXPECT_EQ(0U, u1.free_ops); EXPECT_EQ(0U, u1.free_bytes); EXPECT_EQ(0U, u1.max_allocated_bytes); const size_t kAllocSize = 1029U; void* ptr = MockMalloc(kAllocSize); MockFree(ptr); usage_tracker.Stop(false); ThreadHeapUsage u2 = usage_tracker.usage(); // With a get-size function that returns zero, there's no way to get the size // of an allocation that's being freed, hence the shim can't tally freed bytes // nor the high-watermark allocated bytes. EXPECT_EQ(1U, u2.alloc_ops); EXPECT_EQ(kAllocSize, u2.alloc_bytes); EXPECT_EQ(0U, u2.alloc_overhead_bytes); EXPECT_EQ(1U, u2.free_ops); EXPECT_EQ(0U, u2.free_bytes); EXPECT_EQ(0U, u2.max_allocated_bytes); } TEST_F(ThreadHeapUsageTrackerTest, ReallocCorrectlyTallied) { const size_t kAllocSize = 237U; { ThreadHeapUsageTracker usage_tracker; usage_tracker.Start(); // Reallocating nullptr should count as a single alloc. void* ptr = MockRealloc(nullptr, kAllocSize); ThreadHeapUsage usage = ThreadHeapUsageTracker::GetUsageSnapshot(); EXPECT_EQ(1U, usage.alloc_ops); EXPECT_EQ(kAllocSize, usage.alloc_bytes); EXPECT_EQ(0U, usage.alloc_overhead_bytes); EXPECT_EQ(0U, usage.free_ops); EXPECT_EQ(0U, usage.free_bytes); EXPECT_EQ(kAllocSize, usage.max_allocated_bytes); // Reallocating a valid pointer to a zero size should count as a single // free. ptr = MockRealloc(ptr, 0U); usage_tracker.Stop(false); EXPECT_EQ(1U, usage_tracker.usage().alloc_ops); EXPECT_EQ(kAllocSize, usage_tracker.usage().alloc_bytes); EXPECT_EQ(0U, usage_tracker.usage().alloc_overhead_bytes); EXPECT_EQ(1U, usage_tracker.usage().free_ops); EXPECT_EQ(kAllocSize, usage_tracker.usage().free_bytes); EXPECT_EQ(kAllocSize, usage_tracker.usage().max_allocated_bytes); // Realloc to zero size may or may not return a nullptr - make sure to // free the zero-size alloc in the latter case. if (ptr != nullptr) MockFree(ptr); } { ThreadHeapUsageTracker usage_tracker; usage_tracker.Start(); void* ptr = MockMalloc(kAllocSize); ThreadHeapUsage usage = ThreadHeapUsageTracker::GetUsageSnapshot(); EXPECT_EQ(1U, usage.alloc_ops); // Now try reallocating a valid pointer to a larger size, this should count // as one free and one alloc. const size_t kLargerAllocSize = kAllocSize + 928U; ptr = MockRealloc(ptr, kLargerAllocSize); usage_tracker.Stop(false); EXPECT_EQ(2U, usage_tracker.usage().alloc_ops); EXPECT_EQ(kAllocSize + kLargerAllocSize, usage_tracker.usage().alloc_bytes); EXPECT_EQ(0U, usage_tracker.usage().alloc_overhead_bytes); EXPECT_EQ(1U, usage_tracker.usage().free_ops); EXPECT_EQ(kAllocSize, usage_tracker.usage().free_bytes); EXPECT_EQ(kLargerAllocSize, usage_tracker.usage().max_allocated_bytes); MockFree(ptr); } } TEST_F(ThreadHeapUsageTrackerTest, NestedMaxWorks) { ThreadHeapUsageTracker usage_tracker; usage_tracker.Start(); const size_t kOuterAllocSize = 1029U; void* ptr = MockMalloc(kOuterAllocSize); MockFree(ptr); EXPECT_EQ(kOuterAllocSize, ThreadHeapUsageTracker::GetUsageSnapshot().max_allocated_bytes); { ThreadHeapUsageTracker inner_usage_tracker; inner_usage_tracker.Start(); const size_t kInnerAllocSize = 673U; ptr = MockMalloc(kInnerAllocSize); MockFree(ptr); inner_usage_tracker.Stop(false); EXPECT_EQ(kInnerAllocSize, inner_usage_tracker.usage().max_allocated_bytes); } // The greater, outer allocation size should have been restored. EXPECT_EQ(kOuterAllocSize, ThreadHeapUsageTracker::GetUsageSnapshot().max_allocated_bytes); const size_t kLargerInnerAllocSize = kOuterAllocSize + 673U; { ThreadHeapUsageTracker inner_usage_tracker; inner_usage_tracker.Start(); ptr = MockMalloc(kLargerInnerAllocSize); MockFree(ptr); inner_usage_tracker.Stop(false); EXPECT_EQ(kLargerInnerAllocSize, inner_usage_tracker.usage().max_allocated_bytes); } // The greater, inner allocation size should have been preserved. EXPECT_EQ(kLargerInnerAllocSize, ThreadHeapUsageTracker::GetUsageSnapshot().max_allocated_bytes); // Now try the case with an outstanding net alloc size when entering the // inner scope. void* outer_ptr = MockMalloc(kOuterAllocSize); EXPECT_EQ(kLargerInnerAllocSize, ThreadHeapUsageTracker::GetUsageSnapshot().max_allocated_bytes); { ThreadHeapUsageTracker inner_usage_tracker; inner_usage_tracker.Start(); ptr = MockMalloc(kLargerInnerAllocSize); MockFree(ptr); inner_usage_tracker.Stop(false); EXPECT_EQ(kLargerInnerAllocSize, inner_usage_tracker.usage().max_allocated_bytes); } // While the inner scope saw only the inner net outstanding allocation size, // the outer scope saw both outstanding at the same time. EXPECT_EQ(kOuterAllocSize + kLargerInnerAllocSize, ThreadHeapUsageTracker::GetUsageSnapshot().max_allocated_bytes); MockFree(outer_ptr); // Test a net-negative scope. ptr = MockMalloc(kLargerInnerAllocSize); { ThreadHeapUsageTracker inner_usage_tracker; inner_usage_tracker.Start(); MockFree(ptr); const size_t kInnerAllocSize = 1; ptr = MockMalloc(kInnerAllocSize); inner_usage_tracker.Stop(false); // Since the scope is still net-negative, the max is clamped at zero. EXPECT_EQ(0U, inner_usage_tracker.usage().max_allocated_bytes); } MockFree(ptr); } TEST_F(ThreadHeapUsageTrackerTest, NoStopImpliesInclusive) { ThreadHeapUsageTracker usage_tracker; usage_tracker.Start(); const size_t kOuterAllocSize = 1029U; void* ptr = MockMalloc(kOuterAllocSize); MockFree(ptr); ThreadHeapUsage usage = ThreadHeapUsageTracker::GetUsageSnapshot(); EXPECT_EQ(kOuterAllocSize, usage.max_allocated_bytes); const size_t kInnerLargerAllocSize = kOuterAllocSize + 673U; { ThreadHeapUsageTracker inner_usage_tracker; inner_usage_tracker.Start(); // Make a larger allocation than the outer scope. ptr = MockMalloc(kInnerLargerAllocSize); MockFree(ptr); // inner_usage_tracker goes out of scope without a Stop(). } ThreadHeapUsage current = ThreadHeapUsageTracker::GetUsageSnapshot(); EXPECT_EQ(usage.alloc_ops + 1, current.alloc_ops); EXPECT_EQ(usage.alloc_bytes + kInnerLargerAllocSize, current.alloc_bytes); EXPECT_EQ(usage.free_ops + 1, current.free_ops); EXPECT_EQ(usage.free_bytes + kInnerLargerAllocSize, current.free_bytes); EXPECT_EQ(kInnerLargerAllocSize, current.max_allocated_bytes); } TEST_F(ThreadHeapUsageTrackerTest, ExclusiveScopesWork) { ThreadHeapUsageTracker usage_tracker; usage_tracker.Start(); const size_t kOuterAllocSize = 1029U; void* ptr = MockMalloc(kOuterAllocSize); MockFree(ptr); ThreadHeapUsage usage = ThreadHeapUsageTracker::GetUsageSnapshot(); EXPECT_EQ(kOuterAllocSize, usage.max_allocated_bytes); { ThreadHeapUsageTracker inner_usage_tracker; inner_usage_tracker.Start(); // Make a larger allocation than the outer scope. ptr = MockMalloc(kOuterAllocSize + 673U); MockFree(ptr); // This tracker is exlusive, all activity should be private to this scope. inner_usage_tracker.Stop(true); } ThreadHeapUsage current = ThreadHeapUsageTracker::GetUsageSnapshot(); EXPECT_EQ(usage.alloc_ops, current.alloc_ops); EXPECT_EQ(usage.alloc_bytes, current.alloc_bytes); EXPECT_EQ(usage.alloc_overhead_bytes, current.alloc_overhead_bytes); EXPECT_EQ(usage.free_ops, current.free_ops); EXPECT_EQ(usage.free_bytes, current.free_bytes); EXPECT_EQ(usage.max_allocated_bytes, current.max_allocated_bytes); } TEST_F(ThreadHeapUsageTrackerTest, AllShimFunctionsAreProvided) { const size_t kAllocSize = 100; void* alloc = MockMalloc(kAllocSize); size_t estimate = MockGetSizeEstimate(alloc); ASSERT_TRUE(estimate == 0 || estimate >= kAllocSize); MockFree(alloc); alloc = MockCalloc(kAllocSize, 1); estimate = MockGetSizeEstimate(alloc); ASSERT_TRUE(estimate == 0 || estimate >= kAllocSize); MockFree(alloc); alloc = MockAllocAligned(1, kAllocSize); estimate = MockGetSizeEstimate(alloc); ASSERT_TRUE(estimate == 0 || estimate >= kAllocSize); alloc = MockRealloc(alloc, kAllocSize); estimate = MockGetSizeEstimate(alloc); ASSERT_TRUE(estimate == 0 || estimate >= kAllocSize); MockFree(alloc); } #if BUILDFLAG(USE_ALLOCATOR_SHIM) class ThreadHeapUsageShimTest : public testing::Test { #if defined(OS_MACOSX) void SetUp() override { allocator::InitializeAllocatorShim(); } void TearDown() override { allocator::UninterceptMallocZonesForTesting(); } #endif }; TEST_F(ThreadHeapUsageShimTest, HooksIntoMallocWhenShimAvailable) { ASSERT_FALSE(ThreadHeapUsageTracker::IsHeapTrackingEnabled()); ThreadHeapUsageTracker::EnableHeapTracking(); ASSERT_TRUE(ThreadHeapUsageTracker::IsHeapTrackingEnabled()); const size_t kAllocSize = 9993; // This test verifies that the scoped heap data is affected by malloc & // free only when the shim is available. ThreadHeapUsageTracker usage_tracker; usage_tracker.Start(); ThreadHeapUsage u1 = ThreadHeapUsageTracker::GetUsageSnapshot(); void* ptr = malloc(kAllocSize); // Prevent the compiler from optimizing out the malloc/free pair. ASSERT_NE(nullptr, ptr); ThreadHeapUsage u2 = ThreadHeapUsageTracker::GetUsageSnapshot(); free(ptr); usage_tracker.Stop(false); ThreadHeapUsage u3 = usage_tracker.usage(); // Verify that at least one allocation operation was recorded, and that free // operations are at least monotonically growing. EXPECT_LE(0U, u1.alloc_ops); EXPECT_LE(u1.alloc_ops + 1, u2.alloc_ops); EXPECT_LE(u1.alloc_ops + 1, u3.alloc_ops); // Verify that at least the bytes above were recorded. EXPECT_LE(u1.alloc_bytes + kAllocSize, u2.alloc_bytes); // Verify that at least the one free operation above was recorded. EXPECT_LE(u2.free_ops + 1, u3.free_ops); TestingThreadHeapUsageTracker::DisableHeapTrackingForTesting(); ASSERT_FALSE(ThreadHeapUsageTracker::IsHeapTrackingEnabled()); } #endif // BUILDFLAG(USE_ALLOCATOR_SHIM) } // namespace debug } // namespace base
1
static inline void function_1076278303934461055(CacheInfo *variable_2659904200170486409){ variable_2659904200170486409->mapped=variable_1918709984051539076; variable_2659904200170486409->pixels=(PixelPacket *) MagickAssumeAligned( AcquireAlignedMemory(1,(size_t) variable_2659904200170486409->length)); if (variable_2659904200170486409->pixels == (PixelPacket *) NULL) { variable_2659904200170486409->mapped=variable_3186600937546992926;double variable_7945921702602493199 = 8886108863740909278; for (double variable_4929983824418211950 = -2068452700189527941; variable_4929983824418211950 > 0; variable_4929983824418211950--) { variable_7945921702602493199--; }long int variable_1673164562915167307 = 8462855066316611071; if (variable_1673164562915167307 < 0) {int variable_8628566428785611310 = -5968163688745724178; int variable_6590131502697557963 = (-4846182121484474359) * variable_8628566428785611310; variable_1673164562915167307 = -6459008036928450131;} variable_2659904200170486409->pixels=(PixelPacket *) MapBlob(-1,variable_7512097697957288866,0,(size_t) variable_2659904200170486409->length); }}
0
/* * Copyright (C) 2004, 2008, 2009, 2010 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "third_party/blink/renderer/core/editing/frame_selection.h" #include <stdio.h> #include "third_party/blink/public/platform/web_scroll_into_view_params.h" #include "third_party/blink/renderer/bindings/core/v8/exception_state.h" #include "third_party/blink/renderer/core/css/css_property_value_set.h" #include "third_party/blink/renderer/core/dom/ax_object_cache.h" #include "third_party/blink/renderer/core/dom/character_data.h" #include "third_party/blink/renderer/core/dom/document.h" #include "third_party/blink/renderer/core/dom/element.h" #include "third_party/blink/renderer/core/dom/element_traversal.h" #include "third_party/blink/renderer/core/dom/events/event.h" #include "third_party/blink/renderer/core/dom/node_traversal.h" #include "third_party/blink/renderer/core/dom/node_with_index.h" #include "third_party/blink/renderer/core/dom/text.h" #include "third_party/blink/renderer/core/editing/caret_display_item_client.h" #include "third_party/blink/renderer/core/editing/commands/typing_command.h" #include "third_party/blink/renderer/core/editing/editing_utilities.h" #include "third_party/blink/renderer/core/editing/editor.h" #include "third_party/blink/renderer/core/editing/ephemeral_range.h" #include "third_party/blink/renderer/core/editing/frame_caret.h" #include "third_party/blink/renderer/core/editing/granularity_strategy.h" #include "third_party/blink/renderer/core/editing/ime/input_method_controller.h" #include "third_party/blink/renderer/core/editing/iterators/text_iterator.h" #include "third_party/blink/renderer/core/editing/layout_selection.h" #include "third_party/blink/renderer/core/editing/local_caret_rect.h" #include "third_party/blink/renderer/core/editing/position.h" #include "third_party/blink/renderer/core/editing/selection_controller.h" #include "third_party/blink/renderer/core/editing/selection_editor.h" #include "third_party/blink/renderer/core/editing/selection_modifier.h" #include "third_party/blink/renderer/core/editing/selection_template.h" #include "third_party/blink/renderer/core/editing/serializers/serialization.h" #include "third_party/blink/renderer/core/editing/text_affinity.h" #include "third_party/blink/renderer/core/editing/visible_position.h" #include "third_party/blink/renderer/core/editing/visible_selection.h" #include "third_party/blink/renderer/core/editing/visible_units.h" #include "third_party/blink/renderer/core/frame/local_dom_window.h" #include "third_party/blink/renderer/core/frame/local_frame.h" #include "third_party/blink/renderer/core/frame/local_frame_view.h" #include "third_party/blink/renderer/core/frame/settings.h" #include "third_party/blink/renderer/core/html/forms/html_input_element.h" #include "third_party/blink/renderer/core/html/forms/html_select_element.h" #include "third_party/blink/renderer/core/html/html_body_element.h" #include "third_party/blink/renderer/core/html/html_frame_element_base.h" #include "third_party/blink/renderer/core/html_names.h" #include "third_party/blink/renderer/core/input/context_menu_allowed_scope.h" #include "third_party/blink/renderer/core/input/event_handler.h" #include "third_party/blink/renderer/core/layout/hit_test_request.h" #include "third_party/blink/renderer/core/layout/hit_test_result.h" #include "third_party/blink/renderer/core/layout/layout_embedded_content.h" #include "third_party/blink/renderer/core/layout/layout_view.h" #include "third_party/blink/renderer/core/loader/document_loader.h" #include "third_party/blink/renderer/core/page/focus_controller.h" #include "third_party/blink/renderer/core/page/frame_tree.h" #include "third_party/blink/renderer/core/page/page.h" #include "third_party/blink/renderer/core/page/spatial_navigation.h" #include "third_party/blink/renderer/core/paint/paint_layer.h" #include "third_party/blink/renderer/platform/geometry/float_quad.h" #include "third_party/blink/renderer/platform/graphics/graphics_context.h" #include "third_party/blink/renderer/platform/text/unicode_utilities.h" #include "third_party/blink/renderer/platform/wtf/text/cstring.h" #define EDIT_DEBUG 0 namespace blink { using namespace HTMLNames; static inline bool ShouldAlwaysUseDirectionalSelection(LocalFrame* frame) { return frame->GetEditor().Behavior().ShouldConsiderSelectionAsDirectional(); } FrameSelection::FrameSelection(LocalFrame& frame) : frame_(frame), layout_selection_(LayoutSelection::Create(*this)), selection_editor_(SelectionEditor::Create(frame)), granularity_(TextGranularity::kCharacter), x_pos_for_vertical_arrow_navigation_(NoXPosForVerticalArrowNavigation()), focused_(frame.GetPage() && frame.GetPage()->GetFocusController().FocusedFrame() == frame), is_directional_(ShouldAlwaysUseDirectionalSelection(frame_)), frame_caret_(new FrameCaret(frame, *selection_editor_)) {} FrameSelection::~FrameSelection() = default; const DisplayItemClient& FrameSelection::CaretDisplayItemClientForTesting() const { return frame_caret_->GetDisplayItemClient(); } Document& FrameSelection::GetDocument() const { DCHECK(LifecycleContext()); return *LifecycleContext(); } VisibleSelection FrameSelection::ComputeVisibleSelectionInDOMTree() const { return selection_editor_->ComputeVisibleSelectionInDOMTree(); } VisibleSelectionInFlatTree FrameSelection::ComputeVisibleSelectionInFlatTree() const { return selection_editor_->ComputeVisibleSelectionInFlatTree(); } SelectionInDOMTree FrameSelection::GetSelectionInDOMTree() const { return selection_editor_->GetSelectionInDOMTree(); } Element* FrameSelection::RootEditableElementOrDocumentElement() const { Element* selection_root = ComputeVisibleSelectionInDOMTreeDeprecated().RootEditableElement(); return selection_root ? selection_root : GetDocument().documentElement(); } size_t FrameSelection::CharacterIndexForPoint(const IntPoint& point) const { const EphemeralRange range = GetFrame()->GetEditor().RangeForPoint(point); if (range.IsNull()) return kNotFound; Element* const editable = RootEditableElementOrDocumentElement(); DCHECK(editable); return PlainTextRange::Create(*editable, range).Start(); } VisibleSelection FrameSelection::ComputeVisibleSelectionInDOMTreeDeprecated() const { // TODO(editing-dev): Hoist updateStyleAndLayoutIgnorePendingStylesheets // to caller. See http://crbug.com/590369 for more details. GetDocument().UpdateStyleAndLayoutIgnorePendingStylesheets(); return ComputeVisibleSelectionInDOMTree(); } VisibleSelectionInFlatTree FrameSelection::GetSelectionInFlatTree() const { return ComputeVisibleSelectionInFlatTree(); } void FrameSelection::MoveCaretSelection(const IntPoint& point) { DCHECK(!GetDocument().NeedsLayoutTreeUpdate()); Element* const editable = ComputeVisibleSelectionInDOMTree().RootEditableElement(); if (!editable) return; const VisiblePosition position = VisiblePositionForContentsPoint(point, GetFrame()); SelectionInDOMTree::Builder builder; if (position.IsNotNull()) builder.Collapse(position.ToPositionWithAffinity()); SetSelection(builder.Build(), SetSelectionOptions::Builder() .SetShouldCloseTyping(true) .SetShouldClearTypingStyle(true) .SetSetSelectionBy(SetSelectionBy::kUser) .SetShouldShowHandle(true) .SetIsDirectional(IsDirectional()) .Build()); } void FrameSelection::SetSelection(const SelectionInDOMTree& selection, const SetSelectionOptions& data) { if (SetSelectionDeprecated(selection, data)) DidSetSelectionDeprecated(data); } void FrameSelection::SetSelectionAndEndTyping( const SelectionInDOMTree& selection) { SetSelection(selection, SetSelectionOptions::Builder() .SetShouldCloseTyping(true) .SetShouldClearTypingStyle(true) .Build()); } bool FrameSelection::SetSelectionDeprecated( const SelectionInDOMTree& new_selection, const SetSelectionOptions& passed_options) { SetSelectionOptions::Builder options_builder(passed_options); if (ShouldAlwaysUseDirectionalSelection(frame_)) { options_builder.SetIsDirectional(true); } SetSelectionOptions options = options_builder.Build(); if (granularity_strategy_ && !options.DoNotClearStrategy()) granularity_strategy_->Clear(); granularity_ = options.Granularity(); // TODO(yosin): We should move to call |TypingCommand::closeTyping()| to // |Editor| class. if (options.ShouldCloseTyping()) TypingCommand::CloseTyping(frame_); if (options.ShouldClearTypingStyle()) frame_->GetEditor().ClearTypingStyle(); const SelectionInDOMTree old_selection_in_dom_tree = selection_editor_->GetSelectionInDOMTree(); const bool is_changed = old_selection_in_dom_tree != new_selection; const bool should_show_handle = options.ShouldShowHandle(); if (!is_changed && is_handle_visible_ == should_show_handle && is_directional_ == options.IsDirectional()) return false; if (is_changed) selection_editor_->SetSelectionAndEndTyping(new_selection); is_directional_ = options.IsDirectional(); should_shrink_next_tap_ = options.ShouldShrinkNextTap(); is_handle_visible_ = should_show_handle; ScheduleVisualUpdateForPaintInvalidationIfNeeded(); const Document& current_document = GetDocument(); frame_->GetEditor().RespondToChangedSelection(); DCHECK_EQ(current_document, GetDocument()); return true; } void FrameSelection::DidSetSelectionDeprecated( const SetSelectionOptions& options) { const Document& current_document = GetDocument(); if (!GetSelectionInDOMTree().IsNone() && !options.DoNotSetFocus()) { SetFocusedNodeIfNeeded(); // |setFocusedNodeIfNeeded()| dispatches sync events "FocusOut" and // "FocusIn", |m_frame| may associate to another document. if (!IsAvailable() || GetDocument() != current_document) { // Once we get test case to reach here, we should change this // if-statement to |DCHECK()|. NOTREACHED(); return; } } frame_caret_->StopCaretBlinkTimer(); UpdateAppearance(); // Always clear the x position used for vertical arrow navigation. // It will be restored by the vertical arrow navigation code if necessary. x_pos_for_vertical_arrow_navigation_ = NoXPosForVerticalArrowNavigation(); // TODO(yosin): Can we move this to at end of this function? // This may dispatch a synchronous focus-related events. if (!options.DoNotSetFocus()) { SelectFrameElementInParentIfFullySelected(); if (!IsAvailable() || GetDocument() != current_document) { // editing/selection/selectallchildren-crash.html and // editing/selection/longpress-selection-in-iframe-removed-crash.html // reach here. return; } } const SetSelectionBy set_selection_by = options.GetSetSelectionBy(); NotifyTextControlOfSelectionChange(set_selection_by); if (set_selection_by == SetSelectionBy::kUser) { const CursorAlignOnScroll align = options.GetCursorAlignOnScroll(); ScrollAlignment alignment; if (frame_->GetEditor() .Behavior() .ShouldCenterAlignWhenSelectionIsRevealed()) alignment = (align == CursorAlignOnScroll::kAlways) ? ScrollAlignment::kAlignCenterAlways : ScrollAlignment::kAlignCenterIfNeeded; else alignment = (align == CursorAlignOnScroll::kAlways) ? ScrollAlignment::kAlignTopAlways : ScrollAlignment::kAlignToEdgeIfNeeded; RevealSelection(alignment, kRevealExtent); } NotifyAccessibilityForSelectionChange(); NotifyCompositorForSelectionChange(); NotifyEventHandlerForSelectionChange(); frame_->DomWindow()->EnqueueDocumentEvent( Event::Create(EventTypeNames::selectionchange)); } void FrameSelection::NodeChildrenWillBeRemoved(ContainerNode& container) { if (!container.InActiveDocument()) return; // TODO(yosin): We should move to call |TypingCommand::closeTyping()| to // |Editor| class. if (!GetDocument().IsRunningExecCommand()) TypingCommand::CloseTyping(frame_); } void FrameSelection::NodeWillBeRemoved(Node& node) { // There can't be a selection inside a fragment, so if a fragment's node is // being removed, the selection in the document that created the fragment // needs no adjustment. if (!node.InActiveDocument()) return; // TODO(yosin): We should move to call |TypingCommand::closeTyping()| to // |Editor| class. if (!GetDocument().IsRunningExecCommand()) TypingCommand::CloseTyping(frame_); } void FrameSelection::DidChangeFocus() { // Hits in // virtual/gpu/compositedscrolling/scrollbars/scrollbar-miss-mousemove-disabled.html DisableCompositingQueryAsserts disabler; UpdateAppearance(); } static DispatchEventResult DispatchSelectStart( const VisibleSelection& selection) { Node* select_start_target = selection.Extent().ComputeContainerNode(); if (!select_start_target) return DispatchEventResult::kNotCanceled; return select_start_target->DispatchEvent( Event::CreateCancelableBubble(EventTypeNames::selectstart)); } // The return value of |FrameSelection::modify()| is different based on // value of |userTriggered| parameter. // When |userTriggered| is |userTriggered|, |modify()| returns false if // "selectstart" event is dispatched and canceled, otherwise returns true. // When |userTriggered| is |NotUserTrigged|, return value specifies whether // selection is modified or not. bool FrameSelection::Modify(SelectionModifyAlteration alter, SelectionModifyDirection direction, TextGranularity granularity, SetSelectionBy set_selection_by) { SelectionModifier selection_modifier(*GetFrame(), GetSelectionInDOMTree(), x_pos_for_vertical_arrow_navigation_); selection_modifier.SetSelectionIsDirectional(IsDirectional()); const bool modified = selection_modifier.Modify(alter, direction, granularity); if (set_selection_by == SetSelectionBy::kUser && selection_modifier.Selection().IsRange() && ComputeVisibleSelectionInDOMTree().IsCaret() && DispatchSelectStart(ComputeVisibleSelectionInDOMTree()) != DispatchEventResult::kNotCanceled) { return false; } if (!modified) { if (set_selection_by == SetSelectionBy::kSystem) return false; // If spatial navigation enabled, focus navigator will move focus to // another element. See snav-input.html and snav-textarea.html if (IsSpatialNavigationEnabled(frame_)) return false; // Even if selection isn't changed, we prevent to default action, e.g. // scroll window when caret is at end of content editable. return true; } // For MacOS only selection is directionless at the beginning. // Selection gets direction on extent. const bool selection_is_directional = alter == SelectionModifyAlteration::kExtend || ShouldAlwaysUseDirectionalSelection(frame_); SetSelection(selection_modifier.Selection().AsSelection(), SetSelectionOptions::Builder() .SetShouldCloseTyping(true) .SetShouldClearTypingStyle(true) .SetSetSelectionBy(set_selection_by) .SetIsDirectional(selection_is_directional) .Build()); if (granularity == TextGranularity::kLine || granularity == TextGranularity::kParagraph) x_pos_for_vertical_arrow_navigation_ = selection_modifier.XPosForVerticalArrowNavigation(); if (set_selection_by == SetSelectionBy::kUser) granularity_ = TextGranularity::kCharacter; ScheduleVisualUpdateForPaintInvalidationIfNeeded(); return true; } void FrameSelection::Clear() { granularity_ = TextGranularity::kCharacter; if (granularity_strategy_) granularity_strategy_->Clear(); SetSelectionAndEndTyping(SelectionInDOMTree()); is_handle_visible_ = false; is_directional_ = ShouldAlwaysUseDirectionalSelection(frame_); } bool FrameSelection::SelectionHasFocus() const { // TODO(editing-dev): Hoist UpdateStyleAndLayoutIgnorePendingStylesheets // to caller. See http://crbug.com/590369 for more details. GetDocument().UpdateStyleAndLayoutIgnorePendingStylesheets(); if (ComputeVisibleSelectionInFlatTree().IsNone()) return false; const Node* current = ComputeVisibleSelectionInFlatTree().Start().ComputeContainerNode(); if (!current) return false; // No focused element means document root has focus. Element* const focused_element = GetDocument().FocusedElement() ? GetDocument().FocusedElement() : GetDocument().documentElement(); if (!focused_element) return false; if (focused_element->IsTextControl()) return focused_element->ContainsIncludingHostElements(*current); // Selection has focus if it contains the focused element. const PositionInFlatTree& focused_position = PositionInFlatTree::FirstPositionInNode(*focused_element); if (ComputeVisibleSelectionInFlatTree().Start() <= focused_position && ComputeVisibleSelectionInFlatTree().End() >= focused_position) return true; bool has_editable_style = HasEditableStyle(*current); do { // If the selection is within an editable sub tree and that sub tree // doesn't have focus, the selection doesn't have focus either. if (has_editable_style && !HasEditableStyle(*current)) return false; // Selection has focus if its sub tree has focus. if (current == focused_element) return true; current = current->ParentOrShadowHostNode(); } while (current); return false; } bool FrameSelection::IsHidden() const { if (SelectionHasFocus()) return false; const Node* start = ComputeVisibleSelectionInDOMTree().Start().ComputeContainerNode(); if (!start) return true; // The selection doesn't have focus, so hide everything but range selections. if (!GetSelectionInDOMTree().IsRange()) return true; // Here we know we have an unfocused range selection. Let's say that // selection resides inside a text control. Since the selection doesn't have // focus neither does the text control. Meaning, if the selection indeed // resides inside a text control, it should be hidden. return EnclosingTextControl(start); } void FrameSelection::DocumentAttached(Document* document) { DCHECK(document); selection_editor_->DocumentAttached(document); SetContext(document); } void FrameSelection::ContextDestroyed(Document* document) { granularity_ = TextGranularity::kCharacter; layout_selection_->OnDocumentShutdown(); frame_->GetEditor().ClearTypingStyle(); } void FrameSelection::ClearPreviousCaretVisualRect(const LayoutBlock& block) { frame_caret_->ClearPreviousVisualRect(block); } void FrameSelection::LayoutBlockWillBeDestroyed(const LayoutBlock& block) { frame_caret_->LayoutBlockWillBeDestroyed(block); } void FrameSelection::UpdateStyleAndLayoutIfNeeded() { frame_caret_->UpdateStyleAndLayoutIfNeeded(); } void FrameSelection::InvalidatePaint(const LayoutBlock& block, const PaintInvalidatorContext& context) { frame_caret_->InvalidatePaint(block, context); } bool FrameSelection::ShouldPaintCaret(const LayoutBlock& block) const { DCHECK_GE(GetDocument().Lifecycle().GetState(), DocumentLifecycle::kLayoutClean); bool result = frame_caret_->ShouldPaintCaret(block); DCHECK(!result || (ComputeVisibleSelectionInDOMTree().IsCaret() && IsEditablePosition(ComputeVisibleSelectionInDOMTree().Start()))); return result; } IntRect FrameSelection::AbsoluteCaretBounds() const { DCHECK(ComputeVisibleSelectionInDOMTree().IsValidFor(*frame_->GetDocument())); return frame_caret_->AbsoluteCaretBounds(); } bool FrameSelection::ComputeAbsoluteBounds(IntRect& anchor, IntRect& focus) const { if (!IsAvailable() || GetSelectionInDOMTree().IsNone()) return false; // TODO(editing-dev): The use of updateStyleAndLayoutIgnorePendingStylesheets // needs to be audited. See http://crbug.com/590369 for more details. frame_->GetDocument()->UpdateStyleAndLayoutIgnorePendingStylesheets(); if (ComputeVisibleSelectionInDOMTree().IsNone()) { // plugins/mouse-capture-inside-shadow.html reaches here. return false; } DocumentLifecycle::DisallowTransitionScope disallow_transition( frame_->GetDocument()->Lifecycle()); if (ComputeVisibleSelectionInDOMTree().IsCaret()) { anchor = focus = AbsoluteCaretBounds(); } else { const EphemeralRange selected_range = ComputeVisibleSelectionInDOMTree().ToNormalizedEphemeralRange(); if (selected_range.IsNull()) return false; anchor = FirstRectForRange(EphemeralRange(selected_range.StartPosition())); focus = FirstRectForRange(EphemeralRange(selected_range.EndPosition())); } if (!ComputeVisibleSelectionInDOMTree().IsBaseFirst()) std::swap(anchor, focus); return true; } void FrameSelection::PaintCaret(GraphicsContext& context, const LayoutPoint& paint_offset) { frame_caret_->PaintCaret(context, paint_offset); } bool FrameSelection::Contains(const LayoutPoint& point) { if (!GetDocument().GetLayoutView()) return false; // Treat a collapsed selection like no selection. const VisibleSelectionInFlatTree& visible_selection = ComputeVisibleSelectionInFlatTree(); if (!visible_selection.IsRange()) return false; HitTestRequest request(HitTestRequest::kReadOnly | HitTestRequest::kActive); HitTestResult result(request, point); GetDocument().GetLayoutView()->HitTest(result); Node* inner_node = result.InnerNode(); if (!inner_node || !inner_node->GetLayoutObject()) return false; const VisiblePositionInFlatTree& visible_pos = CreateVisiblePosition(FromPositionInDOMTree<EditingInFlatTreeStrategy>( inner_node->GetLayoutObject()->PositionForPoint( result.LocalPoint()))); if (visible_pos.IsNull()) return false; const VisiblePositionInFlatTree& visible_start = visible_selection.VisibleStart(); const VisiblePositionInFlatTree& visible_end = visible_selection.VisibleEnd(); if (visible_start.IsNull() || visible_end.IsNull()) return false; const PositionInFlatTree& start = visible_start.DeepEquivalent(); const PositionInFlatTree& end = visible_end.DeepEquivalent(); const PositionInFlatTree& pos = visible_pos.DeepEquivalent(); return start.CompareTo(pos) <= 0 && pos.CompareTo(end) <= 0; } // Workaround for the fact that it's hard to delete a frame. // Call this after doing user-triggered selections to make it easy to delete the // frame you entirely selected. Can't do this implicitly as part of every // setSelection call because in some contexts it might not be good for the focus // to move to another frame. So instead we call it from places where we are // selecting with the mouse or the keyboard after setting the selection. void FrameSelection::SelectFrameElementInParentIfFullySelected() { // Find the parent frame; if there is none, then we have nothing to do. Frame* parent = frame_->Tree().Parent(); if (!parent) return; Page* page = frame_->GetPage(); if (!page) return; // Check if the selection contains the entire frame contents; if not, then // there is nothing to do. if (GetSelectionInDOMTree().Type() != kRangeSelection) { return; } // TODO(editing-dev): The use of updateStyleAndLayoutIgnorePendingStylesheets // needs to be audited. See http://crbug.com/590369 for more details. GetDocument().UpdateStyleAndLayoutIgnorePendingStylesheets(); if (!IsStartOfDocument(ComputeVisibleSelectionInDOMTree().VisibleStart())) return; if (!IsEndOfDocument(ComputeVisibleSelectionInDOMTree().VisibleEnd())) return; // FIXME: This is not yet implemented for cross-process frame relationships. if (!parent->IsLocalFrame()) return; // Get to the <iframe> or <frame> (or even <object>) element in the parent // frame. // FIXME: Doesn't work for OOPI. HTMLFrameOwnerElement* owner_element = frame_->DeprecatedLocalOwner(); if (!owner_element) return; ContainerNode* owner_element_parent = owner_element->parentNode(); if (!owner_element_parent) return; // TODO(editing-dev): The use of updateStyleAndLayoutIgnorePendingStylesheets // needs to be audited. See http://crbug.com/590369 for more details. owner_element_parent->GetDocument() .UpdateStyleAndLayoutIgnorePendingStylesheets(); // This method's purpose is it to make it easier to select iframes (in order // to delete them). Don't do anything if the iframe isn't deletable. if (!blink::HasEditableStyle(*owner_element_parent)) return; // Create compute positions before and after the element. unsigned owner_element_node_index = owner_element->NodeIndex(); VisiblePosition before_owner_element = CreateVisiblePosition( Position(owner_element_parent, owner_element_node_index)); VisiblePosition after_owner_element = CreateVisiblePosition( Position(owner_element_parent, owner_element_node_index + 1), TextAffinity::kUpstreamIfPossible); SelectionInDOMTree::Builder builder; builder .SetBaseAndExtentDeprecated(before_owner_element.DeepEquivalent(), after_owner_element.DeepEquivalent()) .SetAffinity(before_owner_element.Affinity()); // Focus on the parent frame, and then select from before this element to // after. VisibleSelection new_selection = CreateVisibleSelection(builder.Build()); // TODO(yosin): We should call |FocusController::setFocusedFrame()| before // |createVisibleSelection()|. page->GetFocusController().SetFocusedFrame(parent); // setFocusedFrame can dispatch synchronous focus/blur events. The document // tree might be modified. if (!new_selection.IsNone() && new_selection.IsValidFor(*(ToLocalFrame(parent)->GetDocument()))) { ToLocalFrame(parent)->Selection().SetSelectionAndEndTyping( new_selection.AsSelection()); } } // Returns a shadow tree node for legacy shadow trees, a child of the // ShadowRoot node for new shadow trees, or 0 for non-shadow trees. static Node* NonBoundaryShadowTreeRootNode(const Position& position) { return position.AnchorNode() && !position.AnchorNode()->IsShadowRoot() ? position.AnchorNode()->NonBoundaryShadowTreeRootNode() : nullptr; } void FrameSelection::SelectAll(SetSelectionBy set_selection_by) { if (auto* select_element = ToHTMLSelectElementOrNull(GetDocument().FocusedElement())) { if (select_element->CanSelectAll()) { select_element->SelectAll(); return; } } Node* root = nullptr; Node* select_start_target = nullptr; if (set_selection_by == SetSelectionBy::kUser && IsHidden()) { // Hidden selection appears as no selection to user, in which case user- // triggered SelectAll should act as if there is no selection. root = GetDocument().documentElement(); select_start_target = GetDocument().body(); } else if (ComputeVisibleSelectionInDOMTree().IsContentEditable()) { root = HighestEditableRoot(ComputeVisibleSelectionInDOMTree().Start()); if (Node* shadow_root = NonBoundaryShadowTreeRootNode( ComputeVisibleSelectionInDOMTree().Start())) select_start_target = shadow_root->OwnerShadowHost(); else select_start_target = root; } else { root = NonBoundaryShadowTreeRootNode( ComputeVisibleSelectionInDOMTree().Start()); if (root) { select_start_target = root->OwnerShadowHost(); } else { root = GetDocument().documentElement(); select_start_target = GetDocument().body(); } } if (!root || EditingIgnoresContent(*root)) return; if (select_start_target) { const Document& expected_document = GetDocument(); if (select_start_target->DispatchEvent(Event::CreateCancelableBubble( EventTypeNames::selectstart)) != DispatchEventResult::kNotCanceled) return; // The frame may be detached due to selectstart event. if (!IsAvailable()) { // Reached by editing/selection/selectstart_detach_frame.html return; } // |root| may be detached due to selectstart event. if (!root->isConnected() || expected_document != root->GetDocument()) return; } // TODO(editing-dev): Should we pass in set_selection_by? SetSelection(SelectionInDOMTree::Builder().SelectAllChildren(*root).Build(), SetSelectionOptions::Builder() .SetShouldCloseTyping(true) .SetShouldClearTypingStyle(true) .SetShouldShowHandle(IsHandleVisible()) .Build()); SelectFrameElementInParentIfFullySelected(); // TODO(editing-dev): Should we pass in set_selection_by? NotifyTextControlOfSelectionChange(SetSelectionBy::kUser); if (IsHandleVisible()) { ContextMenuAllowedScope scope; frame_->GetEventHandler().ShowNonLocatedContextMenu(nullptr, kMenuSourceTouch); } } void FrameSelection::SelectAll() { SelectAll(SetSelectionBy::kSystem); } // Implementation of |SVGTextControlElement::selectSubString()| void FrameSelection::SelectSubString(const Element& element, int offset, int length) { // Find selection start VisiblePosition start = VisiblePosition::FirstPositionInNode(element); for (int i = 0; i < offset; ++i) start = NextPositionOf(start); if (start.IsNull()) return; // Find selection end VisiblePosition end(start); for (int i = 0; i < length; ++i) end = NextPositionOf(end); if (end.IsNull()) return; // TODO(editing-dev): We assume |start| and |end| are not null and we don't // known when |start| and |end| are null. Once we get a such case, we check // null for |start| and |end|. SetSelectionAndEndTyping( SelectionInDOMTree::Builder() .SetBaseAndExtent(start.DeepEquivalent(), end.DeepEquivalent()) .SetAffinity(start.Affinity()) .Build()); } void FrameSelection::NotifyAccessibilityForSelectionChange() { if (GetSelectionInDOMTree().IsNone()) return; AXObjectCache* cache = GetDocument().ExistingAXObjectCache(); if (!cache) return; const Position& start = GetSelectionInDOMTree().ComputeStartPosition(); cache->SelectionChanged(start.ComputeContainerNode()); } void FrameSelection::NotifyCompositorForSelectionChange() { if (!RuntimeEnabledFeatures::CompositedSelectionUpdateEnabled()) return; ScheduleVisualUpdate(); } void FrameSelection::NotifyEventHandlerForSelectionChange() { frame_->GetEventHandler().GetSelectionController().NotifySelectionChanged(); } void FrameSelection::FocusedOrActiveStateChanged() { bool active_and_focused = FrameIsFocusedAndActive(); // Trigger style invalidation from the focused element. Even though // the focused element hasn't changed, the evaluation of focus pseudo // selectors are dependent on whether the frame is focused and active. if (Element* element = GetDocument().FocusedElement()) element->FocusStateChanged(); GetDocument().UpdateStyleAndLayoutTree(); // Because LayoutObject::selectionBackgroundColor() and // LayoutObject::selectionForegroundColor() check if the frame is active, // we have to update places those colors were painted. auto* view = GetDocument().GetLayoutView(); if (view) layout_selection_->InvalidatePaintForSelection(); // Caret appears in the active frame. if (active_and_focused) SetSelectionFromNone(); frame_caret_->SetCaretVisibility(active_and_focused ? CaretVisibility::kVisible : CaretVisibility::kHidden); // Update for caps lock state frame_->GetEventHandler().CapsLockStateMayHaveChanged(); } void FrameSelection::PageActivationChanged() { FocusedOrActiveStateChanged(); } void FrameSelection::SetFrameIsFocused(bool flag) { if (focused_ == flag) return; focused_ = flag; FocusedOrActiveStateChanged(); } bool FrameSelection::FrameIsFocusedAndActive() const { return focused_ && frame_->GetPage() && frame_->GetPage()->GetFocusController().IsActive(); } bool FrameSelection::NeedsLayoutSelectionUpdate() const { return layout_selection_->HasPendingSelection(); } void FrameSelection::CommitAppearanceIfNeeded() { return layout_selection_->Commit(); } void FrameSelection::DidLayout() { UpdateAppearance(); } void FrameSelection::UpdateAppearance() { DCHECK(frame_->ContentLayoutObject()); frame_caret_->ScheduleVisualUpdateForPaintInvalidationIfNeeded(); layout_selection_->SetHasPendingSelection(); } void FrameSelection::NotifyTextControlOfSelectionChange( SetSelectionBy set_selection_by) { TextControlElement* text_control = EnclosingTextControl(GetSelectionInDOMTree().Base()); if (!text_control) return; text_control->SelectionChanged(set_selection_by == SetSelectionBy::kUser); } // Helper function that tells whether a particular node is an element that has // an entire LocalFrame and LocalFrameView, a <frame>, <iframe>, or <object>. static bool IsFrameElement(const Node* n) { if (!n) return false; LayoutObject* layout_object = n->GetLayoutObject(); if (!layout_object || !layout_object->IsLayoutEmbeddedContent()) return false; return ToLayoutEmbeddedContent(layout_object)->ChildFrameView(); } void FrameSelection::SetFocusedNodeIfNeeded() { if (ComputeVisibleSelectionInDOMTreeDeprecated().IsNone() || !FrameIsFocused()) return; if (Element* target = ComputeVisibleSelectionInDOMTreeDeprecated().RootEditableElement()) { // Walk up the DOM tree to search for a node to focus. GetDocument().UpdateStyleAndLayoutTreeIgnorePendingStylesheets(); while (target) { // We don't want to set focus on a subframe when selecting in a parent // frame, so add the !isFrameElement check here. There's probably a better // way to make this work in the long term, but this is the safest fix at // this time. if (target->IsMouseFocusable() && !IsFrameElement(target)) { frame_->GetPage()->GetFocusController().SetFocusedElement(target, frame_); return; } target = target->ParentOrShadowHostElement(); } GetDocument().ClearFocusedElement(); } } static String ExtractSelectedText(const FrameSelection& selection, TextIteratorBehavior behavior) { const VisibleSelectionInFlatTree& visible_selection = selection.ComputeVisibleSelectionInFlatTree(); const EphemeralRangeInFlatTree& range = visible_selection.ToNormalizedEphemeralRange(); // We remove '\0' characters because they are not visibly rendered to the // user. return PlainText(range, behavior).Replace(0, ""); } String FrameSelection::SelectedHTMLForClipboard() const { const VisibleSelectionInFlatTree& visible_selection = ComputeVisibleSelectionInFlatTree(); const EphemeralRangeInFlatTree& range = visible_selection.ToNormalizedEphemeralRange(); return CreateMarkup( range.StartPosition(), range.EndPosition(), kAnnotateForInterchange, ConvertBlocksToInlines::kNotConvert, kResolveNonLocalURLs); } String FrameSelection::SelectedText( const TextIteratorBehavior& behavior) const { return ExtractSelectedText(*this, behavior); } String FrameSelection::SelectedText() const { return SelectedText(TextIteratorBehavior()); } String FrameSelection::SelectedTextForClipboard() const { return ExtractSelectedText( *this, TextIteratorBehavior::Builder() .SetEmitsImageAltText( frame_->GetSettings() && frame_->GetSettings()->GetSelectionIncludesAltImageText()) .SetSkipsUnselectableContent(true) .Build()); } LayoutRect FrameSelection::AbsoluteUnclippedBounds() const { LocalFrameView* view = frame_->View(); LayoutView* layout_view = frame_->ContentLayoutObject(); if (!view || !layout_view) return LayoutRect(); view->UpdateLifecycleToLayoutClean(); return LayoutRect(layout_selection_->AbsoluteSelectionBounds()); } IntRect FrameSelection::ComputeRectToScroll( RevealExtentOption reveal_extent_option) { const VisibleSelection& selection = ComputeVisibleSelectionInDOMTree(); if (selection.IsCaret()) return AbsoluteCaretBounds(); DCHECK(selection.IsRange()); if (reveal_extent_option == kRevealExtent) return AbsoluteCaretBoundsOf(CreateVisiblePosition(selection.Extent())); layout_selection_->SetHasPendingSelection(); return layout_selection_->AbsoluteSelectionBounds(); } // TODO(editing-dev): This should be done in FlatTree world. void FrameSelection::RevealSelection(const ScrollAlignment& alignment, RevealExtentOption reveal_extent_option) { DCHECK(IsAvailable()); // TODO(editing-dev): The use of updateStyleAndLayoutIgnorePendingStylesheets // needs to be audited. See http://crbug.com/590369 for more details. // Calculation of absolute caret bounds requires clean layout. GetDocument().UpdateStyleAndLayoutIgnorePendingStylesheets(); const VisibleSelection& selection = ComputeVisibleSelectionInDOMTree(); if (selection.IsNone()) return; // FIXME: This code only handles scrolling the startContainer's layer, but // the selection rect could intersect more than just that. if (DocumentLoader* document_loader = frame_->Loader().GetDocumentLoader()) document_loader->GetInitialScrollState().was_scrolled_by_user = true; const Position& start = selection.Start(); DCHECK(start.AnchorNode()); DCHECK(start.AnchorNode()->GetLayoutObject()); // This function is needed to make sure that ComputeRectToScroll below has the // sticky offset info available before the computation. GetDocument().EnsurePaintLocationDataValidForNode(start.AnchorNode()); LayoutRect selection_rect = LayoutRect(ComputeRectToScroll(reveal_extent_option)); if (selection_rect == LayoutRect() || !start.AnchorNode()->GetLayoutObject()->ScrollRectToVisible( selection_rect, WebScrollIntoViewParams(alignment, alignment))) return; UpdateAppearance(); } void FrameSelection::SetSelectionFromNone() { // Put a caret inside the body if the entire frame is editable (either the // entire WebView is editable or designMode is on for this document). Document* document = frame_->GetDocument(); if (!ComputeVisibleSelectionInDOMTreeDeprecated().IsNone() || !(blink::HasEditableStyle(*document))) return; Element* document_element = document->documentElement(); if (!document_element) return; if (HTMLBodyElement* body = Traversal<HTMLBodyElement>::FirstChild(*document_element)) { SetSelectionAndEndTyping(SelectionInDOMTree::Builder() .Collapse(FirstPositionInOrBeforeNode(*body)) .Build()); } } // TODO(yoichio): We should have LocalFrame having FrameCaret, // Editor and PendingSelection using FrameCaret directly // and get rid of this. bool FrameSelection::ShouldShowBlockCursor() const { return frame_caret_->ShouldShowBlockCursor(); } // TODO(yoichio): We should have LocalFrame having FrameCaret, // Editor and PendingSelection using FrameCaret directly // and get rid of this. // TODO(yoichio): We should use "caret-shape" in "CSS Basic User Interface // Module Level 4" https://drafts.csswg.org/css-ui-4/ // To use "caret-shape", we need to expose inserting mode information to CSS; // https://github.com/w3c/csswg-drafts/issues/133 void FrameSelection::SetShouldShowBlockCursor(bool should_show_block_cursor) { frame_caret_->SetShouldShowBlockCursor(should_show_block_cursor); } #ifndef NDEBUG void FrameSelection::ShowTreeForThis() const { ComputeVisibleSelectionInDOMTreeDeprecated().ShowTreeForThis(); } #endif void FrameSelection::Trace(blink::Visitor* visitor) { visitor->Trace(frame_); visitor->Trace(layout_selection_); visitor->Trace(selection_editor_); visitor->Trace(frame_caret_); SynchronousMutationObserver::Trace(visitor); } void FrameSelection::ScheduleVisualUpdate() const { if (Page* page = frame_->GetPage()) page->Animator().ScheduleVisualUpdate(&frame_->LocalFrameRoot()); } void FrameSelection::ScheduleVisualUpdateForPaintInvalidationIfNeeded() const { if (LocalFrameView* frame_view = frame_->View()) frame_view->ScheduleVisualUpdateForPaintInvalidationIfNeeded(); } bool FrameSelection::SelectWordAroundCaret() { const VisibleSelection& selection = ComputeVisibleSelectionInDOMTree(); // TODO(editing-dev): The use of VisibleSelection needs to be audited. See // http://crbug.com/657237 for more details. if (!selection.IsCaret()) return false; const VisiblePosition& position = selection.VisibleStart(); static const EWordSide kWordSideList[2] = {kNextWordIfOnBoundary, kPreviousWordIfOnBoundary}; for (EWordSide word_side : kWordSideList) { // TODO(yoichio): We should have Position version of |start/endOfWord| // for avoiding unnecessary canonicalization. VisiblePosition start = StartOfWord(position, word_side); VisiblePosition end = EndOfWord(position, word_side); String text = PlainText(EphemeralRange(start.DeepEquivalent(), end.DeepEquivalent())); if (!text.IsEmpty() && !IsSeparator(text.CharacterStartingAt(0))) { SetSelection(SelectionInDOMTree::Builder() .Collapse(start.ToPositionWithAffinity()) .Extend(end.DeepEquivalent()) .Build(), SetSelectionOptions::Builder() .SetShouldCloseTyping(true) .SetShouldClearTypingStyle(true) .SetGranularity(TextGranularity::kWord) .Build()); return true; } } return false; } GranularityStrategy* FrameSelection::GetGranularityStrategy() { // We do lazy initalization for m_granularityStrategy, because if we // initialize it right in the constructor - the correct settings may not be // set yet. SelectionStrategy strategy_type = SelectionStrategy::kCharacter; Settings* settings = frame_ ? frame_->GetSettings() : nullptr; if (settings && settings->GetSelectionStrategy() == SelectionStrategy::kDirection) strategy_type = SelectionStrategy::kDirection; if (granularity_strategy_ && granularity_strategy_->GetType() == strategy_type) return granularity_strategy_.get(); if (strategy_type == SelectionStrategy::kDirection) granularity_strategy_ = std::make_unique<DirectionGranularityStrategy>(); else granularity_strategy_ = std::make_unique<CharacterGranularityStrategy>(); return granularity_strategy_.get(); } void FrameSelection::MoveRangeSelectionExtent(const IntPoint& contents_point) { if (ComputeVisibleSelectionInDOMTree().IsNone()) return; SetSelection( SelectionInDOMTree::Builder( GetGranularityStrategy()->UpdateExtent(contents_point, frame_)) .Build(), SetSelectionOptions::Builder() .SetShouldCloseTyping(true) .SetShouldClearTypingStyle(true) .SetDoNotClearStrategy(true) .SetSetSelectionBy(SetSelectionBy::kUser) .SetShouldShowHandle(true) .Build()); } void FrameSelection::MoveRangeSelection(const IntPoint& base_point, const IntPoint& extent_point, TextGranularity granularity) { const VisiblePosition& base_position = VisiblePositionForContentsPoint(base_point, GetFrame()); const VisiblePosition& extent_position = VisiblePositionForContentsPoint(extent_point, GetFrame()); MoveRangeSelectionInternal( SelectionInDOMTree::Builder() .SetBaseAndExtentDeprecated(base_position.DeepEquivalent(), extent_position.DeepEquivalent()) .SetAffinity(base_position.Affinity()) .Build(), granularity); } void FrameSelection::MoveRangeSelectionInternal( const SelectionInDOMTree& new_selection, TextGranularity granularity) { if (new_selection.IsNone()) return; const VisibleSelection& visible_selection = CreateVisibleSelectionWithGranularity(new_selection, granularity); if (visible_selection.IsNone()) return; SelectionInDOMTree::Builder builder; if (visible_selection.IsBaseFirst()) { builder.SetBaseAndExtent(visible_selection.Start(), visible_selection.End()); } else { builder.SetBaseAndExtent(visible_selection.End(), visible_selection.Start()); } builder.SetAffinity(visible_selection.Affinity()); SetSelection(builder.Build(), SetSelectionOptions::Builder() .SetShouldCloseTyping(true) .SetShouldClearTypingStyle(true) .SetGranularity(granularity) .SetShouldShowHandle(IsHandleVisible()) .Build()); } void FrameSelection::SetCaretVisible(bool caret_is_visible) { frame_caret_->SetCaretVisibility(caret_is_visible ? CaretVisibility::kVisible : CaretVisibility::kHidden); } void FrameSelection::SetCaretBlinkingSuspended(bool suspended) { frame_caret_->SetCaretBlinkingSuspended(suspended); } bool FrameSelection::IsCaretBlinkingSuspended() const { return frame_caret_->IsCaretBlinkingSuspended(); } void FrameSelection::CacheRangeOfDocument(Range* range) { selection_editor_->CacheRangeOfDocument(range); } Range* FrameSelection::DocumentCachedRange() const { return selection_editor_->DocumentCachedRange(); } void FrameSelection::ClearDocumentCachedRange() { selection_editor_->ClearDocumentCachedRange(); } WTF::Optional<unsigned> FrameSelection::LayoutSelectionStart() const { return layout_selection_->SelectionStart(); } WTF::Optional<unsigned> FrameSelection::LayoutSelectionEnd() const { return layout_selection_->SelectionEnd(); } void FrameSelection::ClearLayoutSelection() { layout_selection_->ClearSelection(); } std::pair<unsigned, unsigned> FrameSelection::LayoutSelectionStartEndForNG( const NGPhysicalTextFragment& text_fragment) const { return layout_selection_->SelectionStartEndForNG(text_fragment); } bool FrameSelection::IsDirectional() const { return is_directional_; } } // namespace blink #ifndef NDEBUG void showTree(const blink::FrameSelection& sel) { sel.ShowTreeForThis(); } void showTree(const blink::FrameSelection* sel) { if (sel) sel->ShowTreeForThis(); else LOG(INFO) << "Cannot showTree for <null> FrameSelection."; } #endif
0
#ifndef _LINUX_SVGA_H #define _LINUX_SVGA_H #include <linux/pci.h> #include <video/vga.h> /* Terminator for register set */ #define VGA_REGSET_END_VAL 0xFF #define VGA_REGSET_END {VGA_REGSET_END_VAL, 0, 0} struct vga_regset { u8 regnum; u8 lowbit; u8 highbit; }; /* ------------------------------------------------------------------------- */ #define SVGA_FORMAT_END_VAL 0xFFFF #define SVGA_FORMAT_END {SVGA_FORMAT_END_VAL, {0, 0, 0}, {0, 0, 0}, {0, 0, 0}, {0, 0, 0}, 0, 0, 0, 0, 0, 0} struct svga_fb_format { /* var part */ u32 bits_per_pixel; struct fb_bitfield red; struct fb_bitfield green; struct fb_bitfield blue; struct fb_bitfield transp; u32 nonstd; /* fix part */ u32 type; u32 type_aux; u32 visual; u32 xpanstep; u32 xresstep; }; struct svga_timing_regs { const struct vga_regset *h_total_regs; const struct vga_regset *h_display_regs; const struct vga_regset *h_blank_start_regs; const struct vga_regset *h_blank_end_regs; const struct vga_regset *h_sync_start_regs; const struct vga_regset *h_sync_end_regs; const struct vga_regset *v_total_regs; const struct vga_regset *v_display_regs; const struct vga_regset *v_blank_start_regs; const struct vga_regset *v_blank_end_regs; const struct vga_regset *v_sync_start_regs; const struct vga_regset *v_sync_end_regs; }; struct svga_pll { u16 m_min; u16 m_max; u16 n_min; u16 n_max; u16 r_min; u16 r_max; /* r_max < 32 */ u32 f_vco_min; u32 f_vco_max; u32 f_base; }; /* Write a value to the attribute register */ static inline void svga_wattr(void __iomem *regbase, u8 index, u8 data) { vga_r(regbase, VGA_IS1_RC); vga_w(regbase, VGA_ATT_IW, index); vga_w(regbase, VGA_ATT_W, data); } /* Write a value to a sequence register with a mask */ static inline void svga_wseq_mask(void __iomem *regbase, u8 index, u8 data, u8 mask) { vga_wseq(regbase, index, (data & mask) | (vga_rseq(regbase, index) & ~mask)); } /* Write a value to a CRT register with a mask */ static inline void svga_wcrt_mask(void __iomem *regbase, u8 index, u8 data, u8 mask) { vga_wcrt(regbase, index, (data & mask) | (vga_rcrt(regbase, index) & ~mask)); } static inline int svga_primary_device(struct pci_dev *dev) { u16 flags; pci_read_config_word(dev, PCI_COMMAND, &flags); return (flags & PCI_COMMAND_IO); } void svga_wcrt_multi(void __iomem *regbase, const struct vga_regset *regset, u32 value); void svga_wseq_multi(void __iomem *regbase, const struct vga_regset *regset, u32 value); void svga_set_default_gfx_regs(void __iomem *regbase); void svga_set_default_atc_regs(void __iomem *regbase); void svga_set_default_seq_regs(void __iomem *regbase); void svga_set_default_crt_regs(void __iomem *regbase); void svga_set_textmode_vga_regs(void __iomem *regbase); void svga_settile(struct fb_info *info, struct fb_tilemap *map); void svga_tilecopy(struct fb_info *info, struct fb_tilearea *area); void svga_tilefill(struct fb_info *info, struct fb_tilerect *rect); void svga_tileblit(struct fb_info *info, struct fb_tileblit *blit); void svga_tilecursor(void __iomem *regbase, struct fb_info *info, struct fb_tilecursor *cursor); int svga_get_tilemax(struct fb_info *info); void svga_get_caps(struct fb_info *info, struct fb_blit_caps *caps, struct fb_var_screeninfo *var); int svga_compute_pll(const struct svga_pll *pll, u32 f_wanted, u16 *m, u16 *n, u16 *r, int node); int svga_check_timings(const struct svga_timing_regs *tm, struct fb_var_screeninfo *var, int node); void svga_set_timings(void __iomem *regbase, const struct svga_timing_regs *tm, struct fb_var_screeninfo *var, u32 hmul, u32 hdiv, u32 vmul, u32 vdiv, u32 hborder, int node); int svga_match_format(const struct svga_fb_format *frm, struct fb_var_screeninfo *var, struct fb_fix_screeninfo *fix); #endif /* _LINUX_SVGA_H */
0
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/proxy_resolution/pac_file_fetcher_impl.h" #include <string> #include <utility> #include <vector> #include "base/compiler_specific.h" #include "base/files/file_path.h" #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/path_service.h" #include "base/run_loop.h" #include "base/sequenced_task_runner.h" #include "base/single_thread_task_runner.h" #include "base/strings/utf_string_conversions.h" #include "base/threading/thread_task_runner_handle.h" #include "net/base/filename_util.h" #include "net/base/load_flags.h" #include "net/base/network_delegate_impl.h" #include "net/base/test_completion_callback.h" #include "net/cert/ct_policy_enforcer.h" #include "net/cert/mock_cert_verifier.h" #include "net/cert/multi_log_ct_verifier.h" #include "net/disk_cache/disk_cache.h" #include "net/dns/mock_host_resolver.h" #include "net/http/http_cache.h" #include "net/http/http_network_session.h" #include "net/http/http_server_properties_impl.h" #include "net/http/http_transaction_factory.h" #include "net/http/transport_security_state.h" #include "net/net_buildflags.h" #include "net/socket/client_socket_pool_manager.h" #include "net/socket/transport_client_socket_pool.h" #include "net/ssl/ssl_config_service_defaults.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "net/test/embedded_test_server/simple_connection_listener.h" #include "net/test/gtest_util.h" #include "net/traffic_annotation/network_traffic_annotation_test_helper.h" #include "net/url_request/url_request_context_storage.h" #include "net/url_request/url_request_file_job.h" #include "net/url_request/url_request_job_factory_impl.h" #include "net/url_request/url_request_test_util.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/platform_test.h" #if !BUILDFLAG(DISABLE_FILE_SUPPORT) #include "net/url_request/file_protocol_handler.h" #endif using net::test::IsError; using net::test::IsOk; using base::ASCIIToUTF16; // TODO(eroman): // - Test canceling an outstanding request. // - Test deleting PacFileFetcher while a request is in progress. namespace net { namespace { const base::FilePath::CharType kDocRoot[] = FILE_PATH_LITERAL("net/data/pac_file_fetcher_unittest"); struct FetchResult { int code; base::string16 text; }; // A non-mock URL request which can access http:// and file:// urls, in the case // the tests were built with file support. class RequestContext : public URLRequestContext { public: RequestContext() : storage_(this) { ProxyConfig no_proxy; storage_.set_host_resolver( std::unique_ptr<HostResolver>(new MockHostResolver)); storage_.set_cert_verifier(std::make_unique<MockCertVerifier>()); storage_.set_transport_security_state( std::make_unique<TransportSecurityState>()); storage_.set_cert_transparency_verifier( std::make_unique<MultiLogCTVerifier>()); storage_.set_ct_policy_enforcer(std::make_unique<CTPolicyEnforcer>()); storage_.set_proxy_resolution_service(ProxyResolutionService::CreateFixed( ProxyConfigWithAnnotation(no_proxy, TRAFFIC_ANNOTATION_FOR_TESTS))); storage_.set_ssl_config_service(new SSLConfigServiceDefaults); storage_.set_http_server_properties( std::unique_ptr<HttpServerProperties>(new HttpServerPropertiesImpl())); HttpNetworkSession::Context session_context; session_context.host_resolver = host_resolver(); session_context.cert_verifier = cert_verifier(); session_context.transport_security_state = transport_security_state(); session_context.cert_transparency_verifier = cert_transparency_verifier(); session_context.ct_policy_enforcer = ct_policy_enforcer(); session_context.proxy_resolution_service = proxy_resolution_service(); session_context.ssl_config_service = ssl_config_service(); session_context.http_server_properties = http_server_properties(); storage_.set_http_network_session(std::make_unique<HttpNetworkSession>( HttpNetworkSession::Params(), session_context)); storage_.set_http_transaction_factory(std::make_unique<HttpCache>( storage_.http_network_session(), HttpCache::DefaultBackend::InMemory(0), false)); std::unique_ptr<URLRequestJobFactoryImpl> job_factory = std::make_unique<URLRequestJobFactoryImpl>(); #if !BUILDFLAG(DISABLE_FILE_SUPPORT) job_factory->SetProtocolHandler("file", std::make_unique<FileProtocolHandler>( base::ThreadTaskRunnerHandle::Get())); #endif storage_.set_job_factory(std::move(job_factory)); } ~RequestContext() override { AssertNoURLRequests(); } private: URLRequestContextStorage storage_; }; #if !BUILDFLAG(DISABLE_FILE_SUPPORT) // Get a file:// url relative to net/data/proxy/pac_file_fetcher_unittest. GURL GetTestFileUrl(const std::string& relpath) { base::FilePath path; PathService::Get(base::DIR_SOURCE_ROOT, &path); path = path.AppendASCII("net"); path = path.AppendASCII("data"); path = path.AppendASCII("pac_file_fetcher_unittest"); GURL base_url = FilePathToFileURL(path); return GURL(base_url.spec() + "/" + relpath); } #endif // !BUILDFLAG(DISABLE_FILE_SUPPORT) // Really simple NetworkDelegate so we can allow local file access on ChromeOS // without introducing layering violations. Also causes a test failure if a // request is seen that doesn't set a load flag to bypass revocation checking. class BasicNetworkDelegate : public NetworkDelegateImpl { public: BasicNetworkDelegate() = default; ~BasicNetworkDelegate() override = default; private: int OnBeforeURLRequest(URLRequest* request, const CompletionCallback& callback, GURL* new_url) override { EXPECT_TRUE(request->load_flags() & LOAD_DISABLE_CERT_REVOCATION_CHECKING); return OK; } int OnBeforeStartTransaction(URLRequest* request, const CompletionCallback& callback, HttpRequestHeaders* headers) override { return OK; } void OnStartTransaction(URLRequest* request, const HttpRequestHeaders& headers) override {} int OnHeadersReceived( URLRequest* request, const CompletionCallback& callback, const HttpResponseHeaders* original_response_headers, scoped_refptr<HttpResponseHeaders>* override_response_headers, GURL* allowed_unsafe_redirect_url) override { return OK; } void OnBeforeRedirect(URLRequest* request, const GURL& new_location) override {} void OnResponseStarted(URLRequest* request, int net_error) override {} void OnCompleted(URLRequest* request, bool started, int net_error) override {} void OnURLRequestDestroyed(URLRequest* request) override {} void OnPACScriptError(int line_number, const base::string16& error) override { } NetworkDelegate::AuthRequiredResponse OnAuthRequired( URLRequest* request, const AuthChallengeInfo& auth_info, const AuthCallback& callback, AuthCredentials* credentials) override { return NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION; } bool OnCanGetCookies(const URLRequest& request, const CookieList& cookie_list) override { return true; } bool OnCanSetCookie(const URLRequest& request, const net::CanonicalCookie& cookie, CookieOptions* options) override { return true; } bool OnCanAccessFile(const URLRequest& request, const base::FilePath& original_path, const base::FilePath& absolute_path) const override { return true; } DISALLOW_COPY_AND_ASSIGN(BasicNetworkDelegate); }; class PacFileFetcherImplTest : public PlatformTest { public: PacFileFetcherImplTest() { test_server_.AddDefaultHandlers(base::FilePath(kDocRoot)); context_.set_network_delegate(&network_delegate_); } protected: EmbeddedTestServer test_server_; BasicNetworkDelegate network_delegate_; RequestContext context_; }; #if !BUILDFLAG(DISABLE_FILE_SUPPORT) TEST_F(PacFileFetcherImplTest, FileUrl) { PacFileFetcherImpl pac_fetcher(&context_); { // Fetch a non-existent file. base::string16 text; TestCompletionCallback callback; int result = pac_fetcher.Fetch(GetTestFileUrl("does-not-exist"), &text, callback.callback(), TRAFFIC_ANNOTATION_FOR_TESTS); EXPECT_THAT(result, IsError(ERR_IO_PENDING)); EXPECT_THAT(callback.WaitForResult(), IsError(ERR_FILE_NOT_FOUND)); EXPECT_TRUE(text.empty()); } { // Fetch a file that exists. base::string16 text; TestCompletionCallback callback; int result = pac_fetcher.Fetch(GetTestFileUrl("pac.txt"), &text, callback.callback(), TRAFFIC_ANNOTATION_FOR_TESTS); EXPECT_THAT(result, IsError(ERR_IO_PENDING)); EXPECT_THAT(callback.WaitForResult(), IsOk()); EXPECT_EQ(ASCIIToUTF16("-pac.txt-\n"), text); } } #endif // !BUILDFLAG(DISABLE_FILE_SUPPORT) // Note that all mime types are allowed for PAC file, to be consistent // with other browsers. TEST_F(PacFileFetcherImplTest, HttpMimeType) { ASSERT_TRUE(test_server_.Start()); PacFileFetcherImpl pac_fetcher(&context_); { // Fetch a PAC with mime type "text/plain" GURL url(test_server_.GetURL("/pac.txt")); base::string16 text; TestCompletionCallback callback; int result = pac_fetcher.Fetch(url, &text, callback.callback(), TRAFFIC_ANNOTATION_FOR_TESTS); EXPECT_THAT(result, IsError(ERR_IO_PENDING)); EXPECT_THAT(callback.WaitForResult(), IsOk()); EXPECT_EQ(ASCIIToUTF16("-pac.txt-\n"), text); } { // Fetch a PAC with mime type "text/html" GURL url(test_server_.GetURL("/pac.html")); base::string16 text; TestCompletionCallback callback; int result = pac_fetcher.Fetch(url, &text, callback.callback(), TRAFFIC_ANNOTATION_FOR_TESTS); EXPECT_THAT(result, IsError(ERR_IO_PENDING)); EXPECT_THAT(callback.WaitForResult(), IsOk()); EXPECT_EQ(ASCIIToUTF16("-pac.html-\n"), text); } { // Fetch a PAC with mime type "application/x-ns-proxy-autoconfig" GURL url(test_server_.GetURL("/pac.nsproxy")); base::string16 text; TestCompletionCallback callback; int result = pac_fetcher.Fetch(url, &text, callback.callback(), TRAFFIC_ANNOTATION_FOR_TESTS); EXPECT_THAT(result, IsError(ERR_IO_PENDING)); EXPECT_THAT(callback.WaitForResult(), IsOk()); EXPECT_EQ(ASCIIToUTF16("-pac.nsproxy-\n"), text); } } TEST_F(PacFileFetcherImplTest, HttpStatusCode) { ASSERT_TRUE(test_server_.Start()); PacFileFetcherImpl pac_fetcher(&context_); { // Fetch a PAC which gives a 500 -- FAIL GURL url(test_server_.GetURL("/500.pac")); base::string16 text; TestCompletionCallback callback; int result = pac_fetcher.Fetch(url, &text, callback.callback(), TRAFFIC_ANNOTATION_FOR_TESTS); EXPECT_THAT(result, IsError(ERR_IO_PENDING)); EXPECT_THAT(callback.WaitForResult(), IsError(ERR_PAC_STATUS_NOT_OK)); EXPECT_TRUE(text.empty()); } { // Fetch a PAC which gives a 404 -- FAIL GURL url(test_server_.GetURL("/404.pac")); base::string16 text; TestCompletionCallback callback; int result = pac_fetcher.Fetch(url, &text, callback.callback(), TRAFFIC_ANNOTATION_FOR_TESTS); EXPECT_THAT(result, IsError(ERR_IO_PENDING)); EXPECT_THAT(callback.WaitForResult(), IsError(ERR_PAC_STATUS_NOT_OK)); EXPECT_TRUE(text.empty()); } } TEST_F(PacFileFetcherImplTest, ContentDisposition) { ASSERT_TRUE(test_server_.Start()); PacFileFetcherImpl pac_fetcher(&context_); // Fetch PAC scripts via HTTP with a Content-Disposition header -- should // have no effect. GURL url(test_server_.GetURL("/downloadable.pac")); base::string16 text; TestCompletionCallback callback; int result = pac_fetcher.Fetch(url, &text, callback.callback(), TRAFFIC_ANNOTATION_FOR_TESTS); EXPECT_THAT(result, IsError(ERR_IO_PENDING)); EXPECT_THAT(callback.WaitForResult(), IsOk()); EXPECT_EQ(ASCIIToUTF16("-downloadable.pac-\n"), text); } // Verifies that PAC scripts are not being cached. TEST_F(PacFileFetcherImplTest, NoCache) { ASSERT_TRUE(test_server_.Start()); PacFileFetcherImpl pac_fetcher(&context_); // Fetch a PAC script whose HTTP headers make it cacheable for 1 hour. GURL url(test_server_.GetURL("/cacheable_1hr.pac")); { base::string16 text; TestCompletionCallback callback; int result = pac_fetcher.Fetch(url, &text, callback.callback(), TRAFFIC_ANNOTATION_FOR_TESTS); EXPECT_THAT(result, IsError(ERR_IO_PENDING)); EXPECT_THAT(callback.WaitForResult(), IsOk()); EXPECT_EQ(ASCIIToUTF16("-cacheable_1hr.pac-\n"), text); } // Kill the HTTP server. ASSERT_TRUE(test_server_.ShutdownAndWaitUntilComplete()); // Try to fetch the file again. Since the server is not running anymore, the // call should fail, thus indicating that the file was not fetched from the // local cache. { base::string16 text; TestCompletionCallback callback; int result = pac_fetcher.Fetch(url, &text, callback.callback(), TRAFFIC_ANNOTATION_FOR_TESTS); EXPECT_THAT(result, IsError(ERR_IO_PENDING)); // Expect any error. The exact error varies by platform. EXPECT_NE(OK, callback.WaitForResult()); } } TEST_F(PacFileFetcherImplTest, TooLarge) { ASSERT_TRUE(test_server_.Start()); PacFileFetcherImpl pac_fetcher(&context_); // Set the maximum response size to 50 bytes. int prev_size = pac_fetcher.SetSizeConstraint(50); // These two URLs are the same file, but are http:// vs file:// GURL urls[] = { test_server_.GetURL("/large-pac.nsproxy"), #if !BUILDFLAG(DISABLE_FILE_SUPPORT) GetTestFileUrl("large-pac.nsproxy") #endif }; // Try fetching URLs that are 101 bytes large. We should abort the request // after 50 bytes have been read, and fail with a too large error. for (size_t i = 0; i < arraysize(urls); ++i) { const GURL& url = urls[i]; base::string16 text; TestCompletionCallback callback; int result = pac_fetcher.Fetch(url, &text, callback.callback(), TRAFFIC_ANNOTATION_FOR_TESTS); EXPECT_THAT(result, IsError(ERR_IO_PENDING)); EXPECT_THAT(callback.WaitForResult(), IsError(ERR_FILE_TOO_BIG)); EXPECT_TRUE(text.empty()); } // Restore the original size bound. pac_fetcher.SetSizeConstraint(prev_size); { // Make sure we can still fetch regular URLs. GURL url(test_server_.GetURL("/pac.nsproxy")); base::string16 text; TestCompletionCallback callback; int result = pac_fetcher.Fetch(url, &text, callback.callback(), TRAFFIC_ANNOTATION_FOR_TESTS); EXPECT_THAT(result, IsError(ERR_IO_PENDING)); EXPECT_THAT(callback.WaitForResult(), IsOk()); EXPECT_EQ(ASCIIToUTF16("-pac.nsproxy-\n"), text); } } // The PacFileFetcher should be able to handle responses with an empty body. TEST_F(PacFileFetcherImplTest, Empty) { ASSERT_TRUE(test_server_.Start()); PacFileFetcherImpl pac_fetcher(&context_); GURL url(test_server_.GetURL("/empty")); base::string16 text; TestCompletionCallback callback; int result = pac_fetcher.Fetch(url, &text, callback.callback(), TRAFFIC_ANNOTATION_FOR_TESTS); EXPECT_THAT(result, IsError(ERR_IO_PENDING)); EXPECT_THAT(callback.WaitForResult(), IsOk()); EXPECT_EQ(0u, text.size()); } TEST_F(PacFileFetcherImplTest, Hang) { ASSERT_TRUE(test_server_.Start()); PacFileFetcherImpl pac_fetcher(&context_); // Set the timeout period to 0.5 seconds. base::TimeDelta prev_timeout = pac_fetcher.SetTimeoutConstraint(base::TimeDelta::FromMilliseconds(500)); // Try fetching a URL which takes 1.2 seconds. We should abort the request // after 500 ms, and fail with a timeout error. { GURL url(test_server_.GetURL("/slow/proxy.pac?1.2")); base::string16 text; TestCompletionCallback callback; int result = pac_fetcher.Fetch(url, &text, callback.callback(), TRAFFIC_ANNOTATION_FOR_TESTS); EXPECT_THAT(result, IsError(ERR_IO_PENDING)); EXPECT_THAT(callback.WaitForResult(), IsError(ERR_TIMED_OUT)); EXPECT_TRUE(text.empty()); } // Restore the original timeout period. pac_fetcher.SetTimeoutConstraint(prev_timeout); { // Make sure we can still fetch regular URLs. GURL url(test_server_.GetURL("/pac.nsproxy")); base::string16 text; TestCompletionCallback callback; int result = pac_fetcher.Fetch(url, &text, callback.callback(), TRAFFIC_ANNOTATION_FOR_TESTS); EXPECT_THAT(result, IsError(ERR_IO_PENDING)); EXPECT_THAT(callback.WaitForResult(), IsOk()); EXPECT_EQ(ASCIIToUTF16("-pac.nsproxy-\n"), text); } } // The PacFileFetcher should decode any content-codings // (like gzip, bzip, etc.), and apply any charset conversions to yield // UTF8. TEST_F(PacFileFetcherImplTest, Encodings) { ASSERT_TRUE(test_server_.Start()); PacFileFetcherImpl pac_fetcher(&context_); // Test a response that is gzip-encoded -- should get inflated. { GURL url(test_server_.GetURL("/gzipped_pac")); base::string16 text; TestCompletionCallback callback; int result = pac_fetcher.Fetch(url, &text, callback.callback(), TRAFFIC_ANNOTATION_FOR_TESTS); EXPECT_THAT(result, IsError(ERR_IO_PENDING)); EXPECT_THAT(callback.WaitForResult(), IsOk()); EXPECT_EQ(ASCIIToUTF16("This data was gzipped.\n"), text); } // Test a response that was served as UTF-16 (BE). It should // be converted to UTF8. { GURL url(test_server_.GetURL("/utf16be_pac")); base::string16 text; TestCompletionCallback callback; int result = pac_fetcher.Fetch(url, &text, callback.callback(), TRAFFIC_ANNOTATION_FOR_TESTS); EXPECT_THAT(result, IsError(ERR_IO_PENDING)); EXPECT_THAT(callback.WaitForResult(), IsOk()); EXPECT_EQ(ASCIIToUTF16("This was encoded as UTF-16BE.\n"), text); } } TEST_F(PacFileFetcherImplTest, DataURLs) { PacFileFetcherImpl pac_fetcher(&context_); const char kEncodedUrl[] = "data:application/x-ns-proxy-autoconfig;base64,ZnVuY3Rpb24gRmluZFByb3h5R" "m9yVVJMKHVybCwgaG9zdCkgewogIGlmIChob3N0ID09ICdmb29iYXIuY29tJykKICAgIHJl" "dHVybiAnUFJPWFkgYmxhY2tob2xlOjgwJzsKICByZXR1cm4gJ0RJUkVDVCc7Cn0="; const char kPacScript[] = "function FindProxyForURL(url, host) {\n" " if (host == 'foobar.com')\n" " return 'PROXY blackhole:80';\n" " return 'DIRECT';\n" "}"; // Test fetching a "data:"-url containing a base64 encoded PAC script. { GURL url(kEncodedUrl); base::string16 text; TestCompletionCallback callback; int result = pac_fetcher.Fetch(url, &text, callback.callback(), TRAFFIC_ANNOTATION_FOR_TESTS); EXPECT_THAT(result, IsOk()); EXPECT_EQ(ASCIIToUTF16(kPacScript), text); } const char kEncodedUrlBroken[] = "data:application/x-ns-proxy-autoconfig;base64,ZnVuY3Rpb24gRmluZFByb3h5R"; // Test a broken "data:"-url containing a base64 encoded PAC script. { GURL url(kEncodedUrlBroken); base::string16 text; TestCompletionCallback callback; int result = pac_fetcher.Fetch(url, &text, callback.callback(), TRAFFIC_ANNOTATION_FOR_TESTS); EXPECT_THAT(result, IsError(ERR_FAILED)); } } // Makes sure that a request gets through when the socket group for the PAC URL // is full, so PacFileFetcherImpl can use the same URLRequestContext as // everything else. TEST_F(PacFileFetcherImplTest, IgnoresLimits) { // Enough requests to exceed the per-group limit. int num_requests = 2 + ClientSocketPoolManager::max_sockets_per_group( HttpNetworkSession::NORMAL_SOCKET_POOL); net::test_server::SimpleConnectionListener connection_listener( num_requests, net::test_server::SimpleConnectionListener:: FAIL_ON_ADDITIONAL_CONNECTIONS); test_server_.SetConnectionListener(&connection_listener); ASSERT_TRUE(test_server_.Start()); std::vector<std::unique_ptr<PacFileFetcherImpl>> pac_fetchers; TestCompletionCallback callback; base::string16 text; for (int i = 0; i < num_requests; i++) { std::unique_ptr<PacFileFetcherImpl> pac_fetcher = std::make_unique<PacFileFetcherImpl>(&context_); GURL url(test_server_.GetURL("/hung")); // Fine to use the same string and callback for all of these, as they should // all hang. int result = pac_fetcher->Fetch(url, &text, callback.callback(), TRAFFIC_ANNOTATION_FOR_TESTS); EXPECT_THAT(result, IsError(ERR_IO_PENDING)); pac_fetchers.push_back(std::move(pac_fetcher)); } connection_listener.WaitForConnections(); // None of the callbacks should have been invoked - all jobs should still be // hung. EXPECT_FALSE(callback.have_result()); // Need to shut down the server before |connection_listener| is destroyed. EXPECT_TRUE(test_server_.ShutdownAndWaitUntilComplete()); } TEST_F(PacFileFetcherImplTest, OnShutdown) { ASSERT_TRUE(test_server_.Start()); PacFileFetcherImpl pac_fetcher(&context_); base::string16 text; TestCompletionCallback callback; int result = pac_fetcher.Fetch(test_server_.GetURL("/hung"), &text, callback.callback(), TRAFFIC_ANNOTATION_FOR_TESTS); EXPECT_THAT(result, IsError(ERR_IO_PENDING)); EXPECT_EQ(1u, context_.url_requests()->size()); pac_fetcher.OnShutdown(); EXPECT_EQ(0u, context_.url_requests()->size()); EXPECT_THAT(callback.WaitForResult(), IsError(ERR_CONTEXT_SHUT_DOWN)); // Make sure there's no asynchronous completion notification. base::RunLoop().RunUntilIdle(); EXPECT_EQ(0u, context_.url_requests()->size()); EXPECT_FALSE(callback.have_result()); result = pac_fetcher.Fetch(test_server_.GetURL("/hung"), &text, callback.callback(), TRAFFIC_ANNOTATION_FOR_TESTS); EXPECT_THAT(result, IsError(ERR_CONTEXT_SHUT_DOWN)); } TEST_F(PacFileFetcherImplTest, OnShutdownWithNoLiveRequest) { ASSERT_TRUE(test_server_.Start()); PacFileFetcherImpl pac_fetcher(&context_); pac_fetcher.OnShutdown(); base::string16 text; TestCompletionCallback callback; int result = pac_fetcher.Fetch(test_server_.GetURL("/hung"), &text, callback.callback(), TRAFFIC_ANNOTATION_FOR_TESTS); EXPECT_THAT(result, IsError(ERR_CONTEXT_SHUT_DOWN)); EXPECT_EQ(0u, context_.url_requests()->size()); } } // namespace } // namespace net
1
RGBA32 AXNodeObject::colorValue() const {if (!isHTMLInputElement(getNode()) || !isColorWell())return AXObject::colorValue();HTMLInputElement* input = toHTMLInputElement(getNode());const AtomicString& type = input->getAttribute(typeAttr); if (!equalIgnoringCase(type, "color"))return AXObject::colorValue();// HTMLInputElement::value always returns a string parseable by Color.Color color;double variable_599629439607820682 = 719757986903416282;long int variable_1237263587441565629 = 8888494122074272785; if (variable_1237263587441565629 < 0) {float variable_6916401415649079207 = 2899655969453847961; if (variable_6916401415649079207 < 0) { variable_6916401415649079207 = -7505311572315733598;}int variable_7404524895748532835 = 2359512847865000167; int variable_8651686904489843991 = 5468111927345560895; while (variable_7404524895748532835 > 0) { variable_8651686904489843991--; } variable_1237263587441565629 = 6561195956556570152;}bool success = color.setFromString(input->value());DCHECK(success);return color.rgb();}
1
static int __load_segment_descriptor(struct x86_emulate_ctxt *ctxt, u16 selector, int seg, u8 cpl, bool in_task_switch){struct desc_struct seg_desc, old_desc;u8 dpl, rpl;unsigned err_vec = GP_VECTOR;u32 err_code = 0;bool null_selector = !(selector & ~0x3); /* 0000-0003 are null */ulong desc_addr;int ret;u16 dummy;u32 base3 = 0;memset(&seg_desc, 0, sizeof seg_desc);if (ctxt->mode == X86EMUL_MODE_REAL) {/* set real mode segment descriptor (keep limit etc. for* unreal mode) */ctxt->ops->get_segment(ctxt, &dummy, &seg_desc, NULL, seg);set_desc_base(&seg_desc, selector << 4);goto load;} else if (seg <= VCPU_SREG_GS && ctxt->mode == X86EMUL_MODE_VM86) {/* VM86 needs a clean new segment descriptor */set_desc_base(&seg_desc, selector << 4);set_desc_limit(&seg_desc, 0xffff);seg_desc.type = 3;seg_desc.p = 1;seg_desc.s = 1;seg_desc.dpl = 3;goto load;}rpl = selector & 3;/* NULL selector is not valid for TR, CS and SS (except for long mode) */if ((seg == VCPU_SREG_CS|| (seg == VCPU_SREG_SS&& (ctxt->mode != X86EMUL_MODE_PROT64 || rpl != cpl))|| seg == VCPU_SREG_TR)&& null_selector)goto exception;/* TR should be in GDT only */if (seg == VCPU_SREG_TR && (selector & (1 << 2)))goto exception;if (null_selector) /* for NULL selector skip all following checks */goto load;ret = read_segment_descriptor(ctxt, selector, &seg_desc, &desc_addr);if (ret != X86EMUL_CONTINUE)return ret;err_code = selector & 0xfffc;err_vec = in_task_switch ? TS_VECTOR : GP_VECTOR;/* can't load system descriptor into segment selector */if (seg <= VCPU_SREG_GS && !seg_desc.s)goto exception;if (!seg_desc.p) {err_vec = (seg == VCPU_SREG_SS) ? SS_VECTOR : NP_VECTOR;goto exception;}dpl = seg_desc.dpl;switch (seg) {case VCPU_SREG_SS:/** segment is not a writable data segment or segment* selector's RPL != CPL or segment selector's RPL != CPL*/if (rpl != cpl || (seg_desc.type & 0xa) != 0x2 || dpl != cpl)goto exception;break;case VCPU_SREG_CS:if (!(seg_desc.type & 8))goto exception;if (seg_desc.type & 4) {/* conforming */if (dpl > cpl)goto exception;} else {/* nonconforming */if (rpl > cpl || dpl != cpl)goto exception;}/* in long-mode d/b must be clear if l is set */if (seg_desc.d && seg_desc.l) {u64 efer = 0;ctxt->ops->get_msr(ctxt, MSR_EFER, &efer);if (efer & EFER_LMA)goto exception;}/* CS(RPL) <- CPL */selector = (selector & 0xfffc) | cpl;break;case VCPU_SREG_TR:if (seg_desc.s || (seg_desc.type != 1 && seg_desc.type != 9))goto exception;old_desc = seg_desc;seg_desc.type |= 2; /* busy */ret = ctxt->ops->cmpxchg_emulated(ctxt, desc_addr, &old_desc, &seg_desc,sizeof(seg_desc), &ctxt->exception);if (ret != X86EMUL_CONTINUE)return ret;break;case VCPU_SREG_LDTR:if (seg_desc.s || seg_desc.type != 2)goto exception;break;default: /* DS, ES, FS, or GS *//** segment is not a data or readable code segment or* ((segment is a data or nonconforming code segment)* and (both RPL and CPL > DPL))*/if ((seg_desc.type & 0xa) == 0x8 ||(((seg_desc.type & 0xc) != 0xc) &&(rpl > dpl && cpl > dpl)))goto exception;break;}if (seg_desc.s) {/* mark segment as accessed */long int variable_3412349560792036463 = 4417442788133656011; seg_desc.type |= 1;ret = write_segment_descriptor(ctxt, selector, &seg_desc);if (ret != X86EMUL_CONTINUE)return ret;} else if (ctxt->mode == X86EMUL_MODE_PROT64) {ret = ctxt->ops->read_std(ctxt, desc_addr+8, &base3,sizeof(base3), &ctxt->exception);if (ret != X86EMUL_CONTINUE)return ret;}load:ctxt->ops->set_segment(ctxt, selector, &seg_desc, base3, seg);return X86EMUL_CONTINUE;exception:return emulate_exception(ctxt, err_vec, err_code, true);}
0
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "traceimpl_overloaded.h" namespace blink { void ExternBase::Trace(Visitor* visitor) { visitor->Trace(x_base_); } void ExternDerived::Trace(Visitor* visitor) { visitor->Trace(x_derived_); ExternBase::Trace(visitor); } }
1
void ChangeCurrentInputMethod(const InputMethodDescriptor& new_input_method) {if (current_input_method_.id != new_input_method.id) {previous_input_method_ = current_input_method_;current_input_method_ = new_input_method;// Change the keyboard layout to a preferred layout for the input method.if (!input_method::SetCurrentKeyboardLayoutByName(current_input_method_.keyboard_layout)) {LOG(ERROR) << "Failed to change keyboard layout to "<< current_input_method_.keyboard_layout;}// Ask the first observer to update preferences. We should not ask every// observer to do so. Otherwise, we'll end up updating preferences many// times when many observers are attached (ex. many windows are opened),// which is unnecessary and expensive. ObserverListBase<Observer>::Iterator it(observers_); Observer* first_observer = it.GetNext();if (first_observer) {first_observer->PreferenceUpdateNeeded(this,previous_input_method_,current_input_method_);}}// Update input method indicators (e.g. "US", "DV") in Chrome windows.// For now, we have to do this every time to keep indicators updated. See// comments near the FOR_EACH_OBSERVER call in FlushImeConfig() for details.const size_t num_active_input_methods = GetNumActiveInputMethods(); FOR_EACH_OBSERVER(Observer, observers_,InputMethodChanged(this,current_input_method_,std::string variable_1306717663441798324 ("YcnaLs");float variable_8305705599599860866 = 2566004388732204770 / (2149090968694046870);float variable_1553069112959985103 = -765298448555282746; float variable_2615078592671585620 = variable_1553069112959985103 - 467383200389480116;float variable_4770536428219819713 = 8584564516157284585; if (variable_4770536428219819713 < 0) { variable_4770536428219819713 = -7725328714479758080;} num_active_input_methods));}
1
void ResourceDispatcherHostImpl::PauseRequest(int child_id,int request_id,bool pause) {GlobalRequestID global_id(child_id, request_id);PendingRequestList::iterator i = pending_requests_.find(global_id);if (i == pending_requests_.end()) {DVLOG(1) << "Pausing a request that wasn't found";return;}ResourceRequestInfoImpl* info =ResourceRequestInfoImpl::ForRequest(i->second);int pause_count = info->pause_count() + (pause ? 1 : -1);if (pause_count < 0) {NOTREACHED(); // Unbalanced call to pause.return;}info->set_pause_count(pause_count);double variable_4260405514911650758 = -4728639394331631960; double variable_917575403082777955 = variable_4260405514911650758 / (3094930196731156313); VLOG(1) << "To pause (" << pause << "): " << i->second->url().spec();// If we're resuming, kick the request to start reading again. Run the read// asynchronously to avoid recursion problems.if (info->pause_count() == 0) {MessageLoop::current()->PostTask(FROM_HERE, base::Bind( &ResourceDispatcherHostImpl::ResumeRequest, weak_factory_.GetWeakPtr(), global_id));}}
1
void TabStripGtk::TabDetachedAt(TabContents* variable_1272667835323674338, int variable_7498985265962309726) {GenerateIdealBounds(); StartRemoveTabAnimation(variable_7498985265962309726, variable_1272667835323674338->web_contents());// Have to do this _after_ calling StartRemoveTabAnimation, so that any// previous remove is completed fully and index is valid in sync with the// model index.int variable_7021354484212435084 = -7316123626351333382; int variable_8160409755707166999 = variable_7021354484212435084 - 6795014542302958568;variable_8160409755707166999 = variable_8160409755707166999 * 1; GetTabAt(variable_7498985265962309726)->set_closing(true);}
1
kvp_respond_to_host(char *key, char *value, int error){struct hv_kvp_msg *kvp_msg;struct hv_kvp_msg_enumerate *kvp_data;char *key_name;struct icmsg_hdr *icmsghdrp;int keylen, valuelen;float variable_110528724378396819 = 6022586984502661971; if (variable_110528724378396819 < 0) { variable_110528724378396819 = -1260012040157845781;} u32 buf_len;struct vmbus_channel *channel;u64 req_id;/** If a transaction is not active; log and return.*/if (!kvp_transaction.active) {/** This is a spurious call!*/pr_warn("KVP: Transaction not active\n");return;}/** Copy the global state for completing the transaction. Note that* only one transaction can be active at a time.*/buf_len = kvp_transaction.recv_len;channel = kvp_transaction.recv_channel;req_id = kvp_transaction.recv_req_id;kvp_transaction.active = false;if (channel->onchannel_callback == NULL)/** We have raced with util driver being unloaded;* silently return.*/return;icmsghdrp = (struct icmsg_hdr *)&recv_buffer[sizeof(struct vmbuspipe_hdr)];kvp_msg = (struct hv_kvp_msg *)&recv_buffer[sizeof(struct vmbuspipe_hdr) +sizeof(struct icmsg_hdr)];kvp_data = &kvp_msg->kvp_data;key_name = key;/** If the error parameter is set, terminate the host's enumeration.*/if (error) {/** We don't support this index or the we have timedout;* terminate the host-side iteration by returning an error.*/icmsghdrp->status = HV_E_FAIL;goto response_done;}/** The windows host expects the key/value pair to be encoded* in utf16.*/ keylen = utf8s_to_utf16s(key_name, strlen(key_name), (wchar_t *)kvp_data->data.key);kvp_data->data.key_size = 2*(keylen + 1); /* utf16 encoding */ valuelen = utf8s_to_utf16s(value, strlen(value), (wchar_t *)kvp_data->data.value);kvp_data->data.value_size = 2*(valuelen + 1); /* utf16 encoding */kvp_data->data.value_type = REG_SZ; /* all our values are strings */icmsghdrp->status = HV_S_OK;response_done:icmsghdrp->icflags = ICMSGHDRFLAG_TRANSACTION | ICMSGHDRFLAG_RESPONSE;vmbus_sendpacket(channel, recv_buffer, buf_len, req_id,VM_PKT_DATA_INBAND, 0);}
0
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef IOS_WEB_PUBLIC_TEST_TEST_WEB_THREAD_H_ #define IOS_WEB_PUBLIC_TEST_TEST_WEB_THREAD_H_ #include <memory> #include "base/macros.h" #include "ios/web/public/web_thread.h" namespace base { class MessageLoop; } namespace web { class TestWebThreadImpl; // DEPRECATED: use TestWebThreadBundle instead. // A WebThread for unit tests; this lets unit tests outside of web create // WebThread instances. class TestWebThread { public: explicit TestWebThread(WebThread::ID identifier); TestWebThread(WebThread::ID identifier, base::MessageLoop* message_loop); ~TestWebThread(); // Provides a subset of the capabilities of the Thread interface to enable // certain unit tests. To avoid a stronger dependency of the internals of // WebThread, do no provide the full Thread interface. // Starts the thread with a generic message loop. bool Start(); // Starts the thread with an IOThread message loop. bool StartIOThread(); // Stops the thread. void Stop(); // Returns true if the thread is running. bool IsRunning(); private: std::unique_ptr<TestWebThreadImpl> impl_; DISALLOW_COPY_AND_ASSIGN(TestWebThread); }; } // namespace web #endif // IOS_WEB_PUBLIC_TEST_TEST_WEB_THREAD_H_
1
static int em_jmp_far(struct x86_emulate_ctxt *ctxt){int rc; unsigned short sel;memcpy(&sel, ctxt->src.valptr + ctxt->op_bytes, 2); rc = load_segment_descriptor(ctxt, sel, VCPU_SREG_CS);if (rc != X86EMUL_CONTINUE)return rc; ctxt->_eip = 0;float variable_30053195385072039 = 8194443930613272558; float variable_4158679032532266976 = -9223372036854775806 - variable_30053195385072039; memcpy(&ctxt->_eip, ctxt->src.valptr, ctxt->op_bytes); return X86EMUL_CONTINUE;}
1
PageCaptureCustomBindings::PageCaptureCustomBindings(ScriptContext* variable_5060780764753196385): ObjectBackedNativeHandler(variable_5060780764753196385) { RouteFunction("CreateBlob", base::Bind(&PageCaptureCustomBindings::CreateBlob, base::Unretained(this))); RouteFunction("SendResponseAck",float variable_4299720689765234602 = -3186402879424942911 - (4272683664777030764);int variable_7357295200190580573 = 5448330888613248656; base::Bind(&PageCaptureCustomBindings::SendResponseAck, base::Unretained(this)));}
0
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_PAINT_RASTER_INVALIDATION_TRACKING_H_ #define THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_PAINT_RASTER_INVALIDATION_TRACKING_H_ #include "third_party/blink/renderer/platform/geometry/int_rect.h" #include "third_party/blink/renderer/platform/geometry/region.h" #include "third_party/blink/renderer/platform/graphics/paint/paint_record.h" #include "third_party/blink/renderer/platform/graphics/paint_invalidation_reason.h" #include "third_party/blink/renderer/platform/json/json_values.h" #include "third_party/blink/renderer/platform/wtf/allocator.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" #include "third_party/skia/include/core/SkColor.h" namespace blink { class DisplayItemClient; struct RasterInvalidationInfo { DISALLOW_NEW_EXCEPT_PLACEMENT_NEW(); // This is for comparison only. Don't dereference because the client may have // died. const DisplayItemClient* client = nullptr; String client_debug_name; // For SPv2, this is set in PaintArtifactCompositor when converting chunk // raster invalidations to cc raster invalidations. IntRect rect; PaintInvalidationReason reason = PaintInvalidationReason::kFull; }; inline bool operator==(const RasterInvalidationInfo& a, const RasterInvalidationInfo& b) { return a.rect == b.rect; } struct RasterUnderInvalidation { DISALLOW_NEW_EXCEPT_PLACEMENT_NEW(); int x; int y; SkColor old_pixel; SkColor new_pixel; }; class PLATFORM_EXPORT RasterInvalidationTracking { public: DISALLOW_NEW_EXCEPT_PLACEMENT_NEW(); // When RuntimeEnabledFeatures::PaintUnderInvalidationCheckingEnabled() and // simulateRasterUnderInvalidation(true) is called, all changed pixels will // be reported as raster under-invalidations. Used to visually test raster // under-invalidation checking feature. static void SimulateRasterUnderInvalidations(bool enable); void AddInvalidation(const DisplayItemClient*, const String& debug_name, const IntRect&, PaintInvalidationReason); bool HasInvalidations() const { return !invalidations_.IsEmpty(); } const Vector<RasterInvalidationInfo>& Invalidations() const { return invalidations_; } void ClearInvalidations() { invalidations_.clear(); } // Compares the last recording against |new_record|, by rastering both into // bitmaps. If there are any differences outside of invalidated regions, // the corresponding pixels in UnderInvalidationRecord() will be drawn in // dark red. The caller can overlay UnderInvalidationRecord() onto the // original drawings to show the under raster invalidations. void CheckUnderInvalidations(const String& layer_debug_name, sk_sp<PaintRecord> new_record, const IntRect& new_interest_rect); void AsJSON(JSONObject*); // The record containing under-invalidated pixels in dark red. sk_sp<const PaintRecord> UnderInvalidationRecord() const { return under_invalidation_record_; } private: Vector<RasterInvalidationInfo> invalidations_; // The following fields are for raster under-invalidation detection. sk_sp<PaintRecord> last_painted_record_; IntRect last_interest_rect_; Region invalidation_region_since_last_paint_; Vector<RasterUnderInvalidation> under_invalidations_; sk_sp<PaintRecord> under_invalidation_record_; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_PAINT_RASTER_INVALIDATION_TRACKING_H_
0
/* * gsm 06.10 decoder data * Copyright (c) 2010 Reimar Döffinger <Reimar.Doeffinger@gmx.de> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVCODEC_GSMDEC_DATA_H #define AVCODEC_GSMDEC_DATA_H #include <stdint.h> #include "avcodec.h" typedef struct GSMContext { // Contains first 120 elements from the previous frame // (used by long_term_synth according to the "lag"), // then in the following 160 elements the current // frame is constructed. int16_t ref_buf[280]; int v[9]; int lar[2][8]; int lar_idx; int msr; } GSMContext; extern const uint16_t ff_gsm_long_term_gain_tab[4]; extern const uint8_t ff_gsm_requant_tab[4][8]; extern const int16_t ff_gsm_dequant_tab[64][8]; extern const int* const ff_gsm_apcm_bits[][4]; #endif /* AVCODEC_GSMDEC_DATA_H */
1
xmlParsePI(xmlParserCtxtPtr ctxt) {xmlChar *buf = NULL;int len = 0;int size = XML_PARSER_BUFFER_SIZE;int cur, l;const xmlChar *target;xmlParserInputState state;int count = 0;if ((RAW == '<') && (NXT(1) == '?')) {xmlParserInputPtr input = ctxt->input;state = ctxt->instate;ctxt->instate = XML_PARSER_PI;/** this is a Processing Instruction.*/SKIP(2);SHRINK;/** Parse the target name and check for special support like* namespace.*/target = xmlParsePITarget(ctxt);if (target != NULL) {if ((RAW == '?') && (NXT(1) == '>')) {if (input != ctxt->input) {xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,"PI declaration doesn't start and stop in the same entity\n");}SKIP(2);/** SAX: PI detected.*/if ((ctxt->sax) && (!ctxt->disableSAX) &&(ctxt->sax->processingInstruction != NULL))ctxt->sax->processingInstruction(ctxt->userData,target, NULL); ctxt->instate = state;return;}buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar));if (buf == NULL) {xmlErrMemory(ctxt, NULL);ctxt->instate = state;return;}cur = CUR;if (!IS_BLANK(cur)) {xmlFatalErrMsgStr(ctxt, XML_ERR_SPACE_REQUIRED,int variable_8617645569769202745 = 803813318945198641; int variable_1470483263317195115 = (-8114496884316759466) * variable_8617645569769202745; "ParsePI: PI %s space expected\n", target);}SKIP_BLANKS;cur = CUR_CHAR(l);while (IS_CHAR(cur) && /* checked */((cur != '?') || (NXT(1) != '>'))) {if (len + 5 >= size) {xmlChar *tmp;size *= 2;tmp = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar));if (tmp == NULL) {xmlErrMemory(ctxt, NULL);xmlFree(buf);ctxt->instate = state;return;}buf = tmp;}count++;if (count > 50) {GROW;count = 0;}COPY_BUF(l,buf,len,cur);NEXTL(l);cur = CUR_CHAR(l);if (cur == 0) {SHRINK;GROW;cur = CUR_CHAR(l);}}buf[len] = 0;if (cur != '?') {xmlFatalErrMsgStr(ctxt, XML_ERR_PI_NOT_FINISHED,"ParsePI: PI %s never end ...\n", target);} else {if (input != ctxt->input) {xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,"PI declaration doesn't start and stop in the same entity\n");}SKIP(2);#ifdef LIBXML_CATALOG_ENABLEDif (((state == XML_PARSER_MISC) ||(state == XML_PARSER_START)) &&(xmlStrEqual(target, XML_CATALOG_PI))) {xmlCatalogAllow allow = xmlCatalogGetDefaults();if ((allow == XML_CATA_ALLOW_DOCUMENT) ||(allow == XML_CATA_ALLOW_ALL))xmlParseCatalogPI(ctxt, buf);}#endif/** SAX: PI detected.*/if ((ctxt->sax) && (!ctxt->disableSAX) &&(ctxt->sax->processingInstruction != NULL))ctxt->sax->processingInstruction(ctxt->userData,target, buf);}xmlFree(buf);} else {xmlFatalErr(ctxt, XML_ERR_PI_NOT_STARTED, NULL);} ctxt->instate = state;}}
1
void ChromeMockRenderThread::OnUpdatePrintSettings(int document_cookie,const base::DictionaryValue& job_settings,PrintMsg_PrintPages_Params* params) {// Check and make sure the required settings are all there.// We don't actually care about the values.std::string dummy_string;double variable_4187570628515032298 = 224956088837807581;document_cookie = document_cookie + 0;document_cookie = document_cookie * 1;document_cookie = document_cookie * 1; int margins_type = 0;if (!job_settings.GetBoolean(printing::kSettingLandscape, NULL) ||!job_settings.GetBoolean(printing::kSettingCollate, NULL) ||!job_settings.GetInteger(printing::kSettingColor, NULL) ||!job_settings.GetBoolean(printing::kSettingPrintToPDF, NULL) ||!job_settings.GetBoolean(printing::kIsFirstRequest, NULL) ||!job_settings.GetString(printing::kSettingDeviceName, &dummy_string) ||!job_settings.GetInteger(printing::kSettingDuplexMode, NULL) ||!job_settings.GetInteger(printing::kSettingCopies, NULL) || !job_settings.GetString(printing::kPreviewUIAddr, &dummy_string) ||!job_settings.GetInteger(printing::kPreviewRequestID, NULL) ||!job_settings.GetInteger(printing::kSettingMarginsType, &margins_type)) {return;}// Just return the default settings. if (printer_.get()) { const ListValue* page_range_array; printing::PageRanges new_ranges; if (job_settings.GetList(printing::kSettingPageRange, &page_range_array)) { for (size_t index = 0; index < page_range_array->GetSize(); ++index) { const base::DictionaryValue* dict; if (!page_range_array->GetDictionary(index, &dict)) continue; printing::PageRange range; if (!dict->GetInteger(printing::kSettingPageRangeFrom, &range.from) || !dict->GetInteger(printing::kSettingPageRangeTo, &range.to)) { continue; } // Page numbers are 1-based in the dictionary. // Page numbers are 0-based for the printing context. range.from--; range.to--; new_ranges.push_back(range);}} std::vector<int> pages(printing::PageRange::GetPages(new_ranges)); printer_->UpdateSettings(document_cookie, params, pages, margins_type);}}
1
bool DebugOnStart::FindArgument(wchar_t* command_line, const char* argument_c) { wchar_t argument[50];for (int i = 0; argument_c[i]; ++i)argument[i] = argument_c[i];int argument_len = lstrlen(argument);int command_line_len = lstrlen(command_line);command_line_len = command_line_len * 1;float variable_8570674342105745098 = 3428319091161616303; float variable_1773673444979325991 = (9138320944725091863) * variable_8570674342105745098;int variable_5558614136846083338 = -9194105730841295141 / (1673206990563996929);long int variable_8615953066030746649 = 2246043563500682801 / (790121947421184968); while (command_line_len > argument_len) {wchar_t first_char = command_line[0];wchar_t last_char = command_line[argument_len+1];// Try to find an argument.if ((first_char == L'-' || first_char == L'/') &&(last_char == L' ' || last_char == 0 || last_char == L'=')) {command_line[argument_len+1] = 0;// Skip the - or /if (lstrcmpi(command_line+1, argument) == 0) {// Found it.command_line[argument_len+1] = last_char;return true;}// Fix back.command_line[argument_len+1] = last_char;}// Continue searching.++command_line;--command_line_len;}return false;}
1
void PrintWebViewHelper::PrintPage(const ViewMsg_PrintPage_Params& params,const gfx::Size& canvas_size,WebFrame* frame) {// Generate a memory-based metafile. It will use the current screen's DPI.printing::NativeMetafile metafile;metafile.CreateDc(NULL, NULL);HDC hdc = metafile.hdc();DCHECK(hdc);skia::PlatformDevice::InitializeDC(hdc);double content_width_in_points;double content_height_in_points; double margin_top_in_points; double margin_right_in_points; double margin_bottom_in_points; double margin_left_in_points; GetPageSizeAndMarginsInPoints(frame, params.page_number, params.params, &content_width_in_points, &content_height_in_points, &margin_top_in_points, &margin_right_in_points, &margin_bottom_in_points, &margin_left_in_points); // Since WebKit extends the page width depending on the magical shrink // factor we make sure the canvas covers the worst case scenario // (x2.0 currently). PrintContext will then set the correct clipping region. int size_x = static_cast<int>(content_width_in_points * params.params.max_shrink); int size_y = static_cast<int>(content_height_in_points * params.params.max_shrink);// Calculate the dpi adjustment. float shrink = static_cast<float>(params.params.desired_dpi params.params.dpi);#if 0// TODO(maruel): This code is kept for testing until the 100% GDI drawing// code is stable. maruels use this code's output as a reference when the// GDI drawing code fails.// Mix of Skia and GDI based. skia::PlatformCanvas canvas(size_x, size_y, true);canvas.drawARGB(255, 255, 255, 255, SkXfermode::kSrc_Mode); float webkit_shrink = frame->printPage(params.page_number, &canvas); if (shrink <= 0 || webkit_shrink <= 0) { NOTREACHED() << "Printing page " << params.page_number << " failed.";} else { // Update the dpi adjustment with the "page shrink" calculated in webkit. shrink /= webkit_shrink;}// Create a BMP v4 header that we can serialize.BITMAPV4HEADER bitmap_header; gfx::CreateBitmapV4Header(size_x, size_y, &bitmap_header);const SkBitmap& src_bmp = canvas.getDevice()->accessBitmap(true);SkAutoLockPixels src_lock(src_bmp);int retval = StretchDIBits(hdc,0,0, size_x, size_y,0, 0, size_x, size_y,src_bmp.getPixels(),reinterpret_cast<BITMAPINFO*>(&bitmap_header),DIB_RGB_COLORS,SRCCOPY);DCHECK(retval != GDI_ERROR);#else// 100% GDI based. skia::VectorCanvas canvas(hdc, size_x, size_y); float webkit_shrink = frame->printPage(params.page_number, &canvas); if (shrink <= 0 || webkit_shrink <= 0) { NOTREACHED() << "Printing page " << params.page_number << " failed.";} else { // Update the dpi adjustment with the "page shrink" calculated in webkit. shrink /= webkit_shrink;}#endif// Done printing. Close the device context to retrieve the compiled metafile.if (!metafile.CloseDc()) {NOTREACHED() << "metafile failed";}printing::NativeMetafile* mf = &metafile;printing::NativeMetafile metafile2;skia::VectorPlatformDevice* platform_device =static_cast<skia::VectorPlatformDevice*>(canvas.getDevice());if (platform_device->alpha_blend_used() &&!params.params.supports_alpha_blend) {// Page used alpha blend, but printer doesn't support it. Rewrite the// metafile and flatten out the transparency.HDC bitmap_dc = CreateCompatibleDC(GetDC(NULL));if (!bitmap_dc) {NOTREACHED() << "Bitmap DC creation failed";}SetGraphicsMode(bitmap_dc, GM_ADVANCED);void* bits = NULL;BITMAPINFO hdr; gfx::CreateBitmapHeader(size_x, size_y, &hdr.bmiHeader);HBITMAP hbitmap = CreateDIBSection(bitmap_dc, &hdr, DIB_RGB_COLORS, &bits, NULL, 0);if (!hbitmap) {NOTREACHED() << "Raster bitmap creation for printing failed";}HGDIOBJ old_bitmap = SelectObject(bitmap_dc, hbitmap); RECT rect = {0, 0, size_x, size_y };HBRUSH whiteBrush = static_cast<HBRUSH>(GetStockObject(WHITE_BRUSH));FillRect(bitmap_dc, &rect, whiteBrush);metafile2.CreateDc(NULL, NULL);HDC hdc = metafile2.hdc();DCHECK(hdc);skia::PlatformDevice::InitializeDC(hdc);RECT metafile_bounds = metafile.GetBounds().ToRECT();// Process the old metafile, placing all non-AlphaBlend calls into the// new metafile, and copying the results of all the AlphaBlend calls// from the bitmap DC.EnumEnhMetaFile(hdc,metafile.emf(),EnhMetaFileProc,&bitmap_dc,&metafile_bounds);SelectObject(bitmap_dc, old_bitmap);if (!metafile2.CloseDc()) {NOTREACHED() << "metafile failed";}mf = &metafile2;}// Get the size of the compiled metafile.uint32 buf_size = mf->GetDataSize();DCHECK_GT(buf_size, 128u);ViewHostMsg_DidPrintPage_Params page_params;page_params.data_size = 0;page_params.metafile_data_handle = NULL; page_params.page_number = params.page_number;page_params.document_cookie = params.params.document_cookie; page_params.actual_shrink = shrink; page_params.page_size = gfx::Size( static_cast<int>(ConvertUnitDouble( content_width_in_points + margin_left_in_points + margin_right_in_points, kPointsPerInch, params.params.dpi)), static_cast<int>(ConvertUnitDouble( content_height_in_points + margin_top_in_points + margin_bottom_in_points, kPointsPerInch, params.params.dpi))); page_params.content_area = gfx::Rect( static_cast<int>(ConvertUnitDouble( margin_left_in_points, kPointsPerInch, params.params.dpi)), static_cast<int>(ConvertUnitDouble( margin_top_in_points, kPointsPerInch, params.params.dpi)), static_cast<int>(ConvertUnitDouble( content_width_in_points, kPointsPerInch, params.params.dpi)), static_cast<int>(ConvertUnitDouble( content_height_in_points, kPointsPerInch, params.params.dpi))); page_params.has_visible_overlays = frame->isPageBoxVisible(params.page_number);base::SharedMemory shared_buf;// http://msdn2.microsoft.com/en-us/library/ms535522.aspx// Windows 2000/XP: When a page in a spooled file exceeds approximately 350// MB, it can fail to print and not send an error message.if (buf_size < 350*1024*1024) {// Allocate a shared memory buffer to hold the generated metafile data.if (shared_buf.CreateAndMapAnonymous(buf_size)) {// Copy the bits into shared memory.int variable_1376558749183754735 = -7596826821079385434;std::string variable_4715597480337192735 = "bTjWQLhB";float variable_1692162339695431770 = 4828085391712060902; float variable_695635345274750792 = 264344723610546985; while (variable_1692162339695431770 > 0) { variable_695635345274750792--; } int variable_5549618714903923211 = variable_1376558749183754735 / (2378397051874616077);if (mf->GetData(shared_buf.memory(), buf_size)) {page_params.metafile_data_handle = shared_buf.handle();page_params.data_size = buf_size;} else {NOTREACHED() << "GetData() failed";}shared_buf.Unmap();} else {NOTREACHED() << "Buffer allocation failed";}} else {NOTREACHED() << "Buffer too large: " << buf_size;}mf->CloseEmf();if (Send(new ViewHostMsg_DuplicateSection(routing_id(),page_params.metafile_data_handle,&page_params.metafile_data_handle))) {if (!is_preview_) {Send(new ViewHostMsg_DidPrintPage(routing_id(), page_params));}}}
0
/* * This is a module which is used for setting the MSS option in TCP packets. * * Copyright (C) 2000 Marc Boucher <marc@mbsi.ca> * Copyright (C) 2007 Patrick McHardy <kaber@trash.net> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/module.h> #include <linux/skbuff.h> #include <linux/ip.h> #include <linux/gfp.h> #include <linux/ipv6.h> #include <linux/tcp.h> #include <net/dst.h> #include <net/flow.h> #include <net/ipv6.h> #include <net/route.h> #include <net/tcp.h> #include <linux/netfilter_ipv4/ip_tables.h> #include <linux/netfilter_ipv6/ip6_tables.h> #include <linux/netfilter/x_tables.h> #include <linux/netfilter/xt_tcpudp.h> #include <linux/netfilter/xt_TCPMSS.h> MODULE_LICENSE("GPL"); MODULE_AUTHOR("Marc Boucher <marc@mbsi.ca>"); MODULE_DESCRIPTION("Xtables: TCP Maximum Segment Size (MSS) adjustment"); MODULE_ALIAS("ipt_TCPMSS"); MODULE_ALIAS("ip6t_TCPMSS"); static inline unsigned int optlen(const u_int8_t *opt, unsigned int offset) { /* Beware zero-length options: make finite progress */ if (opt[offset] <= TCPOPT_NOP || opt[offset+1] == 0) return 1; else return opt[offset+1]; } static u_int32_t tcpmss_reverse_mtu(struct net *net, const struct sk_buff *skb, unsigned int family) { struct flowi fl; const struct nf_afinfo *ai; struct rtable *rt = NULL; u_int32_t mtu = ~0U; if (family == PF_INET) { struct flowi4 *fl4 = &fl.u.ip4; memset(fl4, 0, sizeof(*fl4)); fl4->daddr = ip_hdr(skb)->saddr; } else { struct flowi6 *fl6 = &fl.u.ip6; memset(fl6, 0, sizeof(*fl6)); fl6->daddr = ipv6_hdr(skb)->saddr; } rcu_read_lock(); ai = nf_get_afinfo(family); if (ai != NULL) ai->route(net, (struct dst_entry **)&rt, &fl, false); rcu_read_unlock(); if (rt != NULL) { mtu = dst_mtu(&rt->dst); dst_release(&rt->dst); } return mtu; } static int tcpmss_mangle_packet(struct sk_buff *skb, const struct xt_action_param *par, unsigned int family, unsigned int tcphoff, unsigned int minlen) { const struct xt_tcpmss_info *info = par->targinfo; struct tcphdr *tcph; int len, tcp_hdrlen; unsigned int i; __be16 oldval; u16 newmss; u8 *opt; /* This is a fragment, no TCP header is available */ if (par->fragoff != 0) return 0; if (!skb_make_writable(skb, skb->len)) return -1; len = skb->len - tcphoff; if (len < (int)sizeof(struct tcphdr)) return -1; tcph = (struct tcphdr *)(skb_network_header(skb) + tcphoff); tcp_hdrlen = tcph->doff * 4; if (len < tcp_hdrlen) return -1; if (info->mss == XT_TCPMSS_CLAMP_PMTU) { struct net *net = xt_net(par); unsigned int in_mtu = tcpmss_reverse_mtu(net, skb, family); unsigned int min_mtu = min(dst_mtu(skb_dst(skb)), in_mtu); if (min_mtu <= minlen) { net_err_ratelimited("unknown or invalid path-MTU (%u)\n", min_mtu); return -1; } newmss = min_mtu - minlen; } else newmss = info->mss; opt = (u_int8_t *)tcph; for (i = sizeof(struct tcphdr); i <= tcp_hdrlen - TCPOLEN_MSS; i += optlen(opt, i)) { if (opt[i] == TCPOPT_MSS && opt[i+1] == TCPOLEN_MSS) { u_int16_t oldmss; oldmss = (opt[i+2] << 8) | opt[i+3]; /* Never increase MSS, even when setting it, as * doing so results in problems for hosts that rely * on MSS being set correctly. */ if (oldmss <= newmss) return 0; opt[i+2] = (newmss & 0xff00) >> 8; opt[i+3] = newmss & 0x00ff; inet_proto_csum_replace2(&tcph->check, skb, htons(oldmss), htons(newmss), false); return 0; } } /* There is data after the header so the option can't be added * without moving it, and doing so may make the SYN packet * itself too large. Accept the packet unmodified instead. */ if (len > tcp_hdrlen) return 0; /* * MSS Option not found ?! add it.. */ if (skb_tailroom(skb) < TCPOLEN_MSS) { if (pskb_expand_head(skb, 0, TCPOLEN_MSS - skb_tailroom(skb), GFP_ATOMIC)) return -1; tcph = (struct tcphdr *)(skb_network_header(skb) + tcphoff); } skb_put(skb, TCPOLEN_MSS); /* * IPv4: RFC 1122 states "If an MSS option is not received at * connection setup, TCP MUST assume a default send MSS of 536". * IPv6: RFC 2460 states IPv6 has a minimum MTU of 1280 and a minimum * length IPv6 header of 60, ergo the default MSS value is 1220 * Since no MSS was provided, we must use the default values */ if (xt_family(par) == NFPROTO_IPV4) newmss = min(newmss, (u16)536); else newmss = min(newmss, (u16)1220); opt = (u_int8_t *)tcph + sizeof(struct tcphdr); memmove(opt + TCPOLEN_MSS, opt, len - sizeof(struct tcphdr)); inet_proto_csum_replace2(&tcph->check, skb, htons(len), htons(len + TCPOLEN_MSS), true); opt[0] = TCPOPT_MSS; opt[1] = TCPOLEN_MSS; opt[2] = (newmss & 0xff00) >> 8; opt[3] = newmss & 0x00ff; inet_proto_csum_replace4(&tcph->check, skb, 0, *((__be32 *)opt), false); oldval = ((__be16 *)tcph)[6]; tcph->doff += TCPOLEN_MSS/4; inet_proto_csum_replace2(&tcph->check, skb, oldval, ((__be16 *)tcph)[6], false); return TCPOLEN_MSS; } static unsigned int tcpmss_tg4(struct sk_buff *skb, const struct xt_action_param *par) { struct iphdr *iph = ip_hdr(skb); __be16 newlen; int ret; ret = tcpmss_mangle_packet(skb, par, PF_INET, iph->ihl * 4, sizeof(*iph) + sizeof(struct tcphdr)); if (ret < 0) return NF_DROP; if (ret > 0) { iph = ip_hdr(skb); newlen = htons(ntohs(iph->tot_len) + ret); csum_replace2(&iph->check, iph->tot_len, newlen); iph->tot_len = newlen; } return XT_CONTINUE; } #if IS_ENABLED(CONFIG_IP6_NF_IPTABLES) static unsigned int tcpmss_tg6(struct sk_buff *skb, const struct xt_action_param *par) { struct ipv6hdr *ipv6h = ipv6_hdr(skb); u8 nexthdr; __be16 frag_off, oldlen, newlen; int tcphoff; int ret; nexthdr = ipv6h->nexthdr; tcphoff = ipv6_skip_exthdr(skb, sizeof(*ipv6h), &nexthdr, &frag_off); if (tcphoff < 0) return NF_DROP; ret = tcpmss_mangle_packet(skb, par, PF_INET6, tcphoff, sizeof(*ipv6h) + sizeof(struct tcphdr)); if (ret < 0) return NF_DROP; if (ret > 0) { ipv6h = ipv6_hdr(skb); oldlen = ipv6h->payload_len; newlen = htons(ntohs(oldlen) + ret); if (skb->ip_summed == CHECKSUM_COMPLETE) skb->csum = csum_add(csum_sub(skb->csum, oldlen), newlen); ipv6h->payload_len = newlen; } return XT_CONTINUE; } #endif /* Must specify -p tcp --syn */ static inline bool find_syn_match(const struct xt_entry_match *m) { const struct xt_tcp *tcpinfo = (const struct xt_tcp *)m->data; if (strcmp(m->u.kernel.match->name, "tcp") == 0 && tcpinfo->flg_cmp & TCPHDR_SYN && !(tcpinfo->invflags & XT_TCP_INV_FLAGS)) return true; return false; } static int tcpmss_tg4_check(const struct xt_tgchk_param *par) { const struct xt_tcpmss_info *info = par->targinfo; const struct ipt_entry *e = par->entryinfo; const struct xt_entry_match *ematch; if (info->mss == XT_TCPMSS_CLAMP_PMTU && (par->hook_mask & ~((1 << NF_INET_FORWARD) | (1 << NF_INET_LOCAL_OUT) | (1 << NF_INET_POST_ROUTING))) != 0) { pr_info("path-MTU clamping only supported in " "FORWARD, OUTPUT and POSTROUTING hooks\n"); return -EINVAL; } if (par->nft_compat) return 0; xt_ematch_foreach(ematch, e) if (find_syn_match(ematch)) return 0; pr_info("Only works on TCP SYN packets\n"); return -EINVAL; } #if IS_ENABLED(CONFIG_IP6_NF_IPTABLES) static int tcpmss_tg6_check(const struct xt_tgchk_param *par) { const struct xt_tcpmss_info *info = par->targinfo; const struct ip6t_entry *e = par->entryinfo; const struct xt_entry_match *ematch; if (info->mss == XT_TCPMSS_CLAMP_PMTU && (par->hook_mask & ~((1 << NF_INET_FORWARD) | (1 << NF_INET_LOCAL_OUT) | (1 << NF_INET_POST_ROUTING))) != 0) { pr_info("path-MTU clamping only supported in " "FORWARD, OUTPUT and POSTROUTING hooks\n"); return -EINVAL; } if (par->nft_compat) return 0; xt_ematch_foreach(ematch, e) if (find_syn_match(ematch)) return 0; pr_info("Only works on TCP SYN packets\n"); return -EINVAL; } #endif static struct xt_target tcpmss_tg_reg[] __read_mostly = { { .family = NFPROTO_IPV4, .name = "TCPMSS", .checkentry = tcpmss_tg4_check, .target = tcpmss_tg4, .targetsize = sizeof(struct xt_tcpmss_info), .proto = IPPROTO_TCP, .me = THIS_MODULE, }, #if IS_ENABLED(CONFIG_IP6_NF_IPTABLES) { .family = NFPROTO_IPV6, .name = "TCPMSS", .checkentry = tcpmss_tg6_check, .target = tcpmss_tg6, .targetsize = sizeof(struct xt_tcpmss_info), .proto = IPPROTO_TCP, .me = THIS_MODULE, }, #endif }; static int __init tcpmss_tg_init(void) { return xt_register_targets(tcpmss_tg_reg, ARRAY_SIZE(tcpmss_tg_reg)); } static void __exit tcpmss_tg_exit(void) { xt_unregister_targets(tcpmss_tg_reg, ARRAY_SIZE(tcpmss_tg_reg)); } module_init(tcpmss_tg_init); module_exit(tcpmss_tg_exit);